Repository navigation
Expand file tree
/
Copy pathindex.js
More file actions
82 lines (66 loc) · 1.81 KB
/
Copy pathindex.js
File metadata and controls
82 lines (66 loc) · 1.81 KB
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
/* eslint-disable no-extend-native */
var test = require('../util/test')(__filename);
var flatten = require('../../packages/array-flatten');
var protoFlat = Array.prototype.flat;
Array.prototype.flat = null;
test('flattened arrays are unchanged', function(t) {
t.plan(1);
var arr = [1, 2, 3, 4, 5];
t.deepEqual(flatten(arr), arr);
t.end();
});
test('unflattened arrays are flattened', function(t) {
t.plan(2);
var arr1 = [1, [2, 3], [4, [5, 6], 7], 8];
t.deepEqual(flatten(arr1), [1, 2, 3, 4, 5, 6, 7, 8]);
var arr2 = [{a: 4}, [{b: 5}, {c: false}], {d: 'd'}];
t.deepEqual(flatten(arr2), [{a: 4}, {b: 5}, {c: false}, {d: 'd'}]);
t.end();
});
test('throws on non-arrays return an empty array', function(t) {
t.plan(3);
t.throws(function() {
flatten({n: 4});
});
t.throws(function() {
flatten(2);
});
t.throws(function() {
flatten(undefined);
});
t.end();
});
test('returns a new array with all sub-arrays items concatenated into it up to the specific depth',
function(t) {
t.plan(5);
var arr = [1, [2, [3, [4, [5]]]]];
t.deepEqual(flatten(arr, 0), arr);
t.deepEqual(flatten(arr, 1), [1, 2, [3, [4, [5]]]]);
t.deepEqual(flatten(arr, 2), [1, 2, 3, [4, [5]]]);
t.deepEqual(flatten(arr, 3), [1, 2, 3, 4, [5]]);
t.deepEqual(flatten(arr, 4), [1, 2, 3, 4, 5]);
t.end();
});
test('throws when depth is not a number', function(t) {
t.plan(5);
t.throws(function() {
flatten([1, 2, 3], 'depth');
});
t.throws(function() {
flatten([1, 2, 3], null);
});
t.throws(function() {
flatten([1, 2, 3], {});
});
t.throws(function() {
flatten([1, 2, 3], []);
});
t.throws(function() {
flatten([1, 2, 3], function() {});
});
t.end();
});
Object.defineProperty(Array.prototype, 'flat', {
value: protoFlat,
writable: false,
});