Skip to content

Instantly share code, notes, and snippets.

@alenaksu
Last active January 14, 2019 12:37
Show Gist options
  • Save alenaksu/c155aab6948f84278e607ca2e9d73647 to your computer and use it in GitHub Desktop.
Save alenaksu/c155aab6948f84278e607ca2e9d73647 to your computer and use it in GitHub Desktop.
Array.flat polyfill
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;
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