A quick ES6 prototype of my https://www.npmjs.com/package/flatten-arr
tests are written without a test library, just intrinsice Node.js
assert
.
yarn test
https://gist.github.com/wilmoore/579383ea7288b842f522d04c06232007
A quick ES6 prototype of my https://www.npmjs.com/package/flatten-arr
tests are written without a test library, just intrinsice Node.js
assert
.
yarn test
https://gist.github.com/wilmoore/579383ea7288b842f522d04c06232007
const toString = Object.prototype.toString | |
/** | |
* Recursive list item concatenation. | |
* | |
* @param {Array} nested | |
* Nested array. | |
* | |
* @param {Array} flat | |
* Initial/Flattended array. | |
* | |
* @return {Array} | |
* Flattened array. | |
*/ | |
const concat = (nested, flat) => { | |
let end = nested.length | |
let idx = -1 | |
while (++idx < end) { | |
if (toString.call(nested[idx]) === '[object Array]') { | |
concat(nested[idx], flat) | |
} else { | |
flat.push(nested[idx]) | |
} | |
} | |
return flat | |
} | |
/** | |
* Flattens a nested array recursively. | |
* | |
* @param {Array} list | |
* Nested array. | |
* | |
* @return {Array} | |
* Flattened array. | |
*/ | |
exports.flatten = (list) => concat(list, []) |
{ | |
"name": "gist", | |
"version": "1.0.0", | |
"main": "index.js", | |
"license": "MIT", | |
"scripts": { | |
"test": "node test" | |
} | |
} |
const assert = require('assert') | |
const { flatten } = require('./') | |
{ | |
const original = [[1, 2, [3]], 4] | |
const expected = [1, 2, 3, 4] | |
assert.deepEqual(flatten(original), expected) | |
} | |
{ | |
const original = [1, [[[2, [[3, 4]], 5], 6]], [7], [[[8]]], 9] | |
const expected = [1, 2, 3, 4, 5, 6, 7, 8, 9] | |
assert.deepEqual(flatten(original), expected) | |
} |