From abefb9876b273ee473b6d4a5b4e9ba236aac09a5 Mon Sep 17 00:00:00 2001 From: Sami Samhuri Date: Sat, 5 Nov 2011 16:07:29 -0700 Subject: [PATCH] WIP array methods for objects --- lib/object.js | 52 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) diff --git a/lib/object.js b/lib/object.js index 3f5f999..aa54c02 100644 --- a/lib/object.js +++ b/lib/object.js @@ -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) {