JSFiddle - React, Tailwind, and code Playground
by Jason Miller
HTML
<pre id="output"></pre>
JavaScript
Array.prototype.flat = function flat(d,c) {
return c=this.concat.apply([],this),
d>1 && c.some(Array.isArray) ? c.flat(d-1) : c;
};
Array.prototype.flatMap = function(c,a) {
return this.map(c,a).flat();
};
const NativeArray = (() => {
const frame = document.createElement('iframe');
document.body.appendChild(frame);
const Arr = frame.contentWindow.Array;
frame.remove();
return Arr;
})();
function log(...m) { output.append(...m) }
function test(arr, depth) {
const input = JSON.stringify(arr);
const native = new NativeArray().concat(arr);
const actual = JSON.stringify(arr.flat(depth));
const expected = JSON.stringify(native.flat(depth));
const pass = actual === expected;
const title = document.createElement('code');
title.style = `display:block; margin:5px 0 0; color:${pass?'green':'red'};`;
title.append(pass?'✅':'🚫', input+'.flat('+(depth || '')+')');
log(title, '= ' + actual);
}
/** TESTS */
test([1,2,3,4,5,6,7,8,9]);
test([1,[2],3,4,5,6,7,8,9]);
test([1,[2,3],4,5,6,7,8,9]);
test([1,[2,3,4],5,6,7,8,9]);
test([1,[[2]],3,4,5,6,7,8,9]); // 2
test([1,[[2,3]],4,5,6,7,8,9]); // 2
test([1,[[2],3],4,5,6,7,8,9]); // 2
test([1,[[[2]],3],4,5,6,7,8,9]); // 3
test([1,[[[2,3]]],4,5,6,7,8,9]); // 3
test([1,[[[[2]],3]],4,5,6,7,8,9]); // 4
test([1,[[2]],3,4,5,6,7,8,9], 2);
test([1,[[2,3]],4,5,6,7,8,9], 2);
test([1,[[2],3],4,5,6,7,8,9], 2);
test([1,[[[2]],3],4,5,6,7,8,9], 2);
test([1,[[[2,3]]],4,5,6,7,8,9], 2);
test([1,[[[[2]],3]],4,5,6,7,8,9], 2);
test([1,[[[2]],3],4,5,6,7,8,9], 3);
test([1,[[[2,3]]],4,5,6,7,8,9], 3);
test([1,[[[[2]],3]],4,5,6,7,8,9], 3);
test([1,[[[2,3]]],4,5,6,7,8,9], 4);
test([1,[[[[2]],3]],4,5,6,7,8,9], 4);