This repository has been archived by the owner on Nov 4, 2022. It is now read-only.
forked from jashkenas/underscore
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathflatten.js
43 lines (38 loc) · 1.48 KB
/
flatten.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
// Internal implementation of a recursive `flatten` function.
var property = require('./property');
// Helper for collection methods to determine whether a collection
// should be iterated as an array or as an object.
// Related: http://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength
// Avoids a very nasty iOS 8 JIT bug on ARM-64. #2094
var MAX_ARRAY_INDEX = Math.pow(2, 53) - 1;
var getLength = property('length');
var isArrayLike = function(collection) {
var length = getLength(collection);
return typeof length === 'number' && length >= 0 && length <= MAX_ARRAY_INDEX;
};
function isArguments(value) {
return Object.prototype.toString.call(value) === '[object Arguments]';
}
var flatten = function(input, shallow, strict, output) {
output = output || [];
var idx = output.length;
for (var i = 0, length = getLength(input); i < length; i++) {
var value = input[i];
if (isArrayLike(value) && (Array.isArray(value) || isArguments(value))) {
//flatten current level of array or arguments object
if (shallow) {
var j = 0, len = value.length;
while (j < len) output[idx++] = value[j++];
} else {
flatten(value, shallow, strict, output);
idx = output.length;
}
} else if (!strict) {
output[idx++] = value;
}
}
return output;
};
module.exports = function (array, shallow) {
return flatten(array, shallow, false);
};