-
Notifications
You must be signed in to change notification settings - Fork 68
/
Copy pathchain.js
44 lines (34 loc) · 1.21 KB
/
chain.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
import checkObjectType from './_helpers/checkobjecttype';
import * as universalMethods from './matreshka/_universalmethods';
import Class from './class';
import apply from './_helpers/apply';
// create a prototype of ChainClass
// store target object at "object" property
const prototype = {
constructor(object) {
this.object = object;
}
};
const methodNames = Object.keys(universalMethods);
// iterate over all universal methods
for (let i = 0; i < methodNames.length; i++) {
const methodName = methodNames[i];
const method = universalMethods[methodName];
// create every chained method
prototype[methodName] = function chainedMethod() {
const args = [this.object];
nofn.forEach(arguments, (argument) => {
args.push(argument);
});
apply(method, undefined, args);
// returning this is important for chained calls
return this;
};
}
const ChainClass = Class(prototype);
// the function allows to chain static function calls on any object
export default function chain(object) {
// check for type and throw an error if it is not an object and is not a function
checkObjectType(object, 'chain');
return new ChainClass(object);
}