mirror of
https://github.com/samsonjs/batteries.git
synced 2026-03-25 09:15:46 +00:00
make flatten work on objects and arrays
This commit is contained in:
parent
92912c0678
commit
59e6566d51
1 changed files with 11 additions and 5 deletions
16
lib/array.js
16
lib/array.js
|
|
@ -35,7 +35,6 @@ function at(a, i) {
|
|||
return a[a.length + i];
|
||||
}
|
||||
|
||||
// TODO make this work for non-array objects
|
||||
function compact(a) {
|
||||
var b = []
|
||||
, i = a.length
|
||||
|
|
@ -50,10 +49,17 @@ function first(a) { return a[0]; }
|
|||
|
||||
// Based on underscore.js's flatten
|
||||
function flatten(a) {
|
||||
return a.reduce(function(initial, elem) {
|
||||
if (elem && elem.flatten) initial = initial.concat(elem.flatten());
|
||||
else initial.push(elem);
|
||||
return initial;
|
||||
return a.reduce(function(flat, val) {
|
||||
if (val && typeof val.flatten === 'function') {
|
||||
flat = flat.concat(val.flatten());
|
||||
}
|
||||
else if (Array.isArray(val)) {
|
||||
flat = flat.concat(flatten(val));
|
||||
}
|
||||
else {
|
||||
flat.push(val);
|
||||
}
|
||||
return flat;
|
||||
});
|
||||
}
|
||||
|
||||
|
|
|
|||
Loading…
Reference in a new issue