mirror of
https://github.com/samsonjs/batteries.git
synced 2026-03-25 09:15:46 +00:00
[NEW] ArrayExt: pluck, sortBy
This commit is contained in:
parent
9f2533e22f
commit
b7c529d965
1 changed files with 47 additions and 0 deletions
|
|
@ -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]
|
||||
})
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue