Skip to content

Instantly share code, notes, and snippets.

@THEozmic
Created August 27, 2019 19:09
Show Gist options
  • Save THEozmic/bf528d13583c8c48ec179fa2914684c5 to your computer and use it in GitHub Desktop.
Save THEozmic/bf528d13583c8c48ec179fa2914684c5 to your computer and use it in GitHub Desktop.
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);
}
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