Created
August 27, 2019 19:09
-
-
Save THEozmic/bf528d13583c8c48ec179fa2914684c5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export default function flat () { | |
var depth = isNaN(arguments[0]) ? 1 : Number(arguments[0]); | |
return depth ? Array.prototype.reduce.call(this, function (acc, cur) { | |
if (Array.isArray(cur)) { | |
acc.push.apply(acc, flat.call(cur, depth - 1)); | |
} else { | |
acc.push(cur); | |
} | |
return acc; | |
}, []) : Array.prototype.slice.call(this); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import flat from '../src/flat'; | |
test('flat() examples', () => { | |
// basic nesting | |
expect(flat.call([1, 2, [3, 4]], 0)).toEqual([1, 2, [3, 4]]); | |
expect(flat.call([1, 2, [3, 4]], 1)).toEqual([1, 2, 3, 4]); | |
expect(flat.call([1, 2, [3, 4]])).toEqual([1, 2, 3, 4]); | |
// double nesting | |
expect(flat.call([[1], [2], [3], [4]])).toEqual([1, 2, 3, 4]); | |
// triple nesting | |
expect(flat.call([1, 2, [3, 4, [5, 6]]])).toEqual([1, 2, 3, 4, [5, 6]]); | |
expect(flat.call([1, 2, [3, 4, [5, 6]]], 0)).toEqual([1, 2, [3, 4, [5, 6]]]); | |
expect(flat.call([1, 2, [3, 4, [5, 6]]], 1)).toEqual([1, 2, 3, 4, [5, 6]]); | |
expect(flat.call([1, 2, [3, 4, [5, 6]]], 2)).toEqual([1, 2, 3, 4, 5, 6]); | |
// complex nesting | |
expect(flat.call([1, 2, 3, [4, [5, 6], 7, [8, 9, 10]]], 2)).toEqual([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); | |
expect(flat.call([[[1]], [2], [3], [4]])).toEqual([[1], 2, 3, 4]); | |
expect(flat.call([[[1]], [2], [3], [4]], 2)).toEqual([1, 2, 3, 4]); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment