-
-
Save vologab/a4994f82b1067284edb48cbfc5287945 to your computer and use it in GitHub Desktop.
JS array flatten polyfill
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
const assert = require('assert'); | |
function flatten(a) { | |
if (!Array.isArray(a)) throw new Error('Input value should be array'); | |
let stack = JSON.parse(JSON.stringify(a)) | |
let result = []; | |
while (stack.length) { | |
let a = stack.pop(); | |
if (Array.isArray(a)) { | |
stack.push(...a); | |
} else { | |
result.push(a); | |
} | |
} | |
return result.reverse(); | |
} | |
console.log('Starting tests 🤖'); | |
assert.deepEqual(flatten([1, 2, 3, [4, 5, [3]]]), [1, 2, 3, 4, 5, 3], 'Array should be flatten'); | |
assert.notDeepEqual(flatten([1, 2, 3, [4, 5, [3]]]), [3, 5, 4, 3, 2, 1], 'Order of array should be correct'); | |
assert.deepEqual(flatten([]), [], 'Should works correctly with empty array'); | |
assert.throws(() => flatten('incorrect input'), Error, 'Should throws error for incorrect input'); | |
console.log('Tests finished successfully 🎉'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment