mirror of
https://github.com/samsonjs/batteries.git
synced 2026-03-29 09:55:47 +00:00
WIP array methods for objects
This commit is contained in:
parent
59e6566d51
commit
abefb9876b
1 changed files with 52 additions and 0 deletions
|
|
@ -20,10 +20,19 @@ function cmp(a, b) {
|
|||
throw new Error('cannot effectively compare values');
|
||||
}
|
||||
|
||||
function compact(o) {
|
||||
return reduce(o, function(p, key) {
|
||||
var val = o[key];
|
||||
if (val !== null && val !== undefined) p[key] = val;
|
||||
return p;
|
||||
}, {});
|
||||
}
|
||||
|
||||
function extend(a, b) {
|
||||
Object.getOwnPropertyNames(b).forEach(function(k) {
|
||||
a[k] = b[k];
|
||||
});
|
||||
return a;
|
||||
}
|
||||
|
||||
function extendPrototype(obj, ext) {
|
||||
|
|
@ -38,6 +47,49 @@ function extendPrototype(obj, ext) {
|
|||
});
|
||||
}
|
||||
|
||||
function flatten(o) {
|
||||
return reduce(o, function(p, key) {
|
||||
var val = o[key];
|
||||
if (val && !Array.isArray(val) && typeof val.flatten === 'function') {
|
||||
extend(p, val.flatten());
|
||||
}
|
||||
else if (typeof val === 'object' && !Array.isArray(val)) {
|
||||
extend(p, flatten(val));
|
||||
}
|
||||
else {
|
||||
p[key] = val;
|
||||
}
|
||||
return p;
|
||||
});
|
||||
}
|
||||
function grep(o, regex) {
|
||||
|
||||
return reduce(o, function(p, key) {
|
||||
if (regex.test(key)) p[key] = o[key];
|
||||
return p;
|
||||
}, {});
|
||||
}
|
||||
|
||||
function grepValues(o, regex) {
|
||||
return reduce(o, function(p, key) {
|
||||
var val = o[key];
|
||||
if (regex.test(val)) p[key] = val;
|
||||
return p;
|
||||
});
|
||||
}
|
||||
|
||||
function map(o, fn) {
|
||||
return reduce(o, function(p, key) {
|
||||
p[key] = fn(o[key], p, o);
|
||||
return p;
|
||||
});
|
||||
}
|
||||
|
||||
function reduce(o, fn, initial) {
|
||||
var keys = Object.getOwnPropertyNames(o || {});
|
||||
return keys.reduce(fn, initial || {});
|
||||
}
|
||||
|
||||
// Make a wrapper than passes `this` as the first argument, Python style. All
|
||||
// extension functions that can extend native types must follow this convention.
|
||||
function methodWrapper(fn) {
|
||||
|
|
|
|||
Loading…
Reference in a new issue