[NEW] ArrayExt: pluck, sortBy

This commit is contained in:
Sami Samhuri 2010-11-21 20:06:10 -08:00
parent 9f2533e22f
commit b7c529d965

View file

@ -62,6 +62,22 @@ var ArrayExt = exports.ArrayExt = {
// pack
// partition
, pluck: function(a, /* key paths, ... */) {
var args = [].slice.call(arguments, 1);
args.unshift(a);
return pluck.apply(null, args);
}
, sortBy: function(arr, keyPath) {
return arr.slice().sort(function(a, b) {
var propA = drillInto(a)
, propB = drillInto(b);
if (propA < propB) return -1
if (propA > propB) return 1
return 0
});
}
, toString: function(a) {
return '[' + ArrayToString.call(a) + ']';
}
@ -77,3 +93,34 @@ var ArrayExt = exports.ArrayExt = {
return b;
}
};
// pluck
function getProp(thing, key) {
if (thing === null || thing === undefined) return thing
var prop = thing[key]
return typeof prop === 'function' ? prop.call(thing) : prop
}
function drillInto(thing, keyPath) {
return keyPath.split('.').reduce(function(memo, key) {
return getProp(memo, key)
}, thing)
}
function mapInto(thing /* , key paths, ... */) {
var keyPaths = [].slice.call(arguments, 1)
return keyPaths.map(function(keyPath) {
return drillInto(thing, keyPath)
})
}
function pluck(things /* , key paths, ... */) {
var keyPaths = [].slice.call(arguments, 1)
return things.map(function(thing) {
var results = mapInto.apply(null, [thing].concat(keyPaths))
if (results.length > 1) return results
return results[0]
})
}