mirror of
https://github.com/samsonjs/batteries.git
synced 2026-04-27 15:07:42 +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];
|
return a[a.length + i];
|
||||||
}
|
}
|
||||||
|
|
||||||
// TODO make this work for non-array objects
|
|
||||||
function compact(a) {
|
function compact(a) {
|
||||||
var b = []
|
var b = []
|
||||||
, i = a.length
|
, i = a.length
|
||||||
|
|
@ -50,10 +49,17 @@ function first(a) { return a[0]; }
|
||||||
|
|
||||||
// Based on underscore.js's flatten
|
// Based on underscore.js's flatten
|
||||||
function flatten(a) {
|
function flatten(a) {
|
||||||
return a.reduce(function(initial, elem) {
|
return a.reduce(function(flat, val) {
|
||||||
if (elem && elem.flatten) initial = initial.concat(elem.flatten());
|
if (val && typeof val.flatten === 'function') {
|
||||||
else initial.push(elem);
|
flat = flat.concat(val.flatten());
|
||||||
return initial;
|
}
|
||||||
|
else if (Array.isArray(val)) {
|
||||||
|
flat = flat.concat(flatten(val));
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
flat.push(val);
|
||||||
|
}
|
||||||
|
return flat;
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue