WIP array methods for objects

This commit is contained in:
Sami Samhuri 2011-11-05 16:07:29 -07:00
parent 59e6566d51
commit abefb9876b

View file

@ -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) {