UNPKG

2.72 kBJavaScriptView Raw
1(function () {
2
3 // ['a.b.c', 'd'] -> ['a', 'b', 'c', 'd']
4 function splitDots(list) {
5 var result = [];
6 list.forEach(function (x) {
7 if (typeof x === 'string') {
8 x.split('.').forEach(function (part) {
9 result.push(part);
10 });
11 } else {
12 result.push(x);
13 }
14 });
15 return result;
16 }
17
18 function assemble() {
19
20 function isStringOrFunction(f) {
21 return typeof f === 'string' ||
22 typeof f === 'function';
23 }
24
25 function humanizeArgument(f, k) {
26 if (typeof f === 'string') {
27 return k + ': string ' + f;
28 }
29 if (typeof f === 'function') {
30 return k + ': function ' + f.name;
31 }
32 if (typeof f === 'undefined') {
33 return k + ': undefined argument';
34 }
35 return k + ': ' + (typeof f) + ' argument';
36 }
37
38 // Creates an optimistic chain, no checks before calling a function
39 // or accessing a property, or calling a method
40 function fp() {
41 var args = Array.prototype.slice.call(arguments, 0);
42 if (args.length) {
43 if (!args.every(isStringOrFunction)) {
44 var signature = args.map(humanizeArgument).join('\n\t');
45 throw new Error('Invalid arguments to functional pipeline - not a string or function\n\t' +
46 signature);
47 }
48
49 var fns = splitDots(args);
50 return function (d) {
51 var originalObject = d;
52 fns.forEach(function (fn) {
53 if (typeof fn === 'string') {
54 if (typeof d[fn] === 'function') {
55 d = d[fn].call(d, d);
56 } else if (typeof d[fn] !== 'undefined') {
57 d = d[fn];
58 } else {
59 var signature = args.map(humanizeArgument).join('\n\t');
60 throw new Error('Cannot use property ' + fn + ' from object ' +
61 JSON.stringify(d, null, 2) + '\npipeline\n\t' + signature +
62 '\noriginal object\n' + JSON.stringify(originalObject, null, 2));
63 }
64 } else if (typeof fn === 'function') {
65 d = fn(d);
66 } else {
67 throw new Error('Cannot apply ' + JSON.stringify(fn, null, 2) +
68 ' to value ' + d + ' not a property name or a function');
69 }
70 });
71 return d;
72 };
73 }
74 }
75
76 return fp;
77 }
78
79 function register(value, name) {
80 if (typeof window === 'object') {
81 /* global window */
82 window[name] = value;
83 } else if (typeof module === 'object') {
84 module.exports = value;
85 } else {
86 throw new Error('Do not know how to register ' + name);
87 }
88 }
89
90 var fp = assemble();
91 fp.debug = true;
92 register(fp, 'fp');
93
94}());