mirror of
https://github.com/samsonjs/batteries.git
synced 2026-04-27 15:07:42 +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
|
// pack
|
||||||
// partition
|
// 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) {
|
, toString: function(a) {
|
||||||
return '[' + ArrayToString.call(a) + ']';
|
return '[' + ArrayToString.call(a) + ']';
|
||||||
}
|
}
|
||||||
|
|
@ -77,3 +93,34 @@ var ArrayExt = exports.ArrayExt = {
|
||||||
return b;
|
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