Last active
January 14, 2019 12:37
-
-
Save alenaksu/c155aab6948f84278e607ca2e9d73647 to your computer and use it in GitHub Desktop.
Array.flat polyfill
This file contains hidden or 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 const flat = arr => { | |
// Create a copy of the original array | |
const result = [...arr]; | |
for (let i = 0; i < result.length; i++) { | |
while (Array.isArray(result[i])) { | |
// insert in the current position a copy of the original item | |
result.splice(i, 1, ...result[i]); | |
} | |
} | |
return result; | |
} | |
export default flat; |
This file contains hidden or 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 test from 'ava'; | |
import flat from '../src/array-flat'; | |
test('should not mutate the input array', t => { | |
const a = [[[1]], 2, 3, [4, 5], 6]; | |
const b = flat(a); | |
t.not(a, b); | |
t.deepEqual(a, [[[1]], 2, 3, [4, 5], 6]); | |
}) | |
test('flattens single level array', t => { | |
t.deepEqual(flat([[1], [2, 3], 4, [5]]), [1, 2, 3, 4, 5]); | |
t.deepEqual(flat([1, [2], [3], 4, 5]), [1, 2, 3, 4, 5]); | |
}); | |
test('flattens deep level array', t => { | |
t.deepEqual( | |
flat([ | |
[[1]], | |
{}, | |
[[[3]], [4, {}, [1, 2, [1, [1, 2, 3, 4], 3, 4], 4], 5], 6], | |
1, | |
{}, | |
[3, [4, {}, [1, 2, [1, [1, 2, 3, 4], 3, 4], 4], 5], 6] | |
]), | |
[ | |
1, | |
{}, | |
3, | |
4, | |
{}, | |
1, | |
2, | |
1, | |
1, | |
2, | |
3, | |
4, | |
3, | |
4, | |
4, | |
5, | |
6, | |
1, | |
{}, | |
3, | |
4, | |
{}, | |
1, | |
2, | |
1, | |
1, | |
2, | |
3, | |
4, | |
3, | |
4, | |
4, | |
5, | |
6 | |
] | |
); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment