/
fluent-arr.js
73 lines (60 loc) · 1.74 KB
/
fluent-arr.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
function oldInsert(value) {
return {
into: function (array) {
return {
after: function (afterValue) {
array.splice(array.indexOf(afterValue) + 1, 0, value);
return array;
}
}
}
}
}
function fluent(extend) {
var propertySpec = {}, builder = new Proxy({}, {
get: function (target, prop, receiver) {
return prop === '_then' ? _then : function () {
propertySpec[prop] = Array.from(arguments);
return builder;
};
}
});
function setContextProperties(forFn, withContext, args) {
var argIndex = 0;
propertySpec[forFn].forEach(function () {
withContext.push(args[argIndex]);
});
}
function _then(handler) {
var fnIndex = 0, fns = Object.keys(propertySpec), context = [], thisArg;
function updateContext() {
thisArg = extend && fnIndex === 0 ? this : thisArg;
setContextProperties(fns[fnIndex], context, arguments);
var next = {}, nextFn = fns[++fnIndex];
if (nextFn) {
next[nextFn] = updateContext;
return next;
} else {
return handler.apply(thisArg, context);
}
}
if (extend) {
extend[fns[0]] = updateContext;
}
return updateContext;
}
return builder;
}
var insert = fluent().insert('*').into('array').after('*')._then(function (value, array, otherValue) {
array.splice(array.indexOf(otherValue) + 1, 0, value);
return array;
});
var result = insert(2).into([1, 3]).after(1);
console.log(result);
fluent(Array.prototype).with('*').after('*')._then(function (value, otherValue) {
var copy = this.slice(0);
copy.splice(copy.indexOf(otherValue) + 1, 0, value);
return copy;
});
var arr = ['this', 'awesome'];
console.log(arr, arr.with('is').after('this'));