-
Notifications
You must be signed in to change notification settings - Fork 0
/
obj.js
89 lines (85 loc) · 1.92 KB
/
obj.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
var curry = require('./curry');
var compose = require('./compose');
var args = require('./args');
var bool = require('./bool');
var utils = require('./utils');
var private = {
iterate: function(o, fn, defaultRet) {
var keys = Object.keys(o);
var abort = false;
var ret = defaultRet;
for (var i = 0; i < keys.length; ++i)
{
fn(keys[i], function(returnValue) {
abort = true;
ret = returnValue;
});
if (abort)
return ret;
}
return ret;
}
};
var obj = {
propEq: function(prop, value, o) {
return o[prop] == value;
},
prop: function(prop, o) {
return o[prop];
},
keys: function(o) {
return Object.keys(o);
},
values: function(o) {
return obj.keys(o).map(function(key) {
return o[key];
});
},
forObj: function(fn, o) {
private.iterate(o, function(key) {
fn(o[key], key, o);
});
},
mapObj: function(fn, o) {
var newObj = {};
private.iterate(o, function(key) {
newObj[key] = fn(o[key], key, o);
});
return newObj;
},
reduceObj: function(fn, acc, o) {
// deep clone accumulator if passed by reference -- N.B. DOES NOT CLONE FUNCTIONS (USE forObj with obj in closure instead)
if (utils.isPassedByRef(acc))
acc = JSON.parse(JSON.stringify(acc));
private.iterate(o, function(key) {
acc = fn(acc, o[key], key, o);
});
return acc;
},
filterObj: function(fn, o) {
var newO = {};
private.iterate(o, function(key) {
if (fn(o[key], key, o))
newO[key] = o[key];
});
return newO;
},
everyObj: function(fn, o) {
return private.iterate(o, function(key, returnWith) {
if (!fn(o[key], key, o))
returnWith(false);
}, true);
},
someObj: function(fn, o) {
return private.iterate(o, function(key, returnWith) {
if (fn(o[key], key, o))
returnWith(true);
}, false);
}
};
var curriedObj = curry.curryObject(obj);
utils.extend(curriedObj, {
// add inverses
rejectObj: args.applyToArg(bool.not, 1, curriedObj.filterObj)
});
module.exports = curriedObj;