Created
October 7, 2019 17:54
-
-
Save matiasfha/24abcb0ad815dbcca5d256600f2e3a7e to your computer and use it in GitHub Desktop.
Array flatten for es6
This file contains hidden or 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
/* This function use array.reduce | |
* https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Objetos_globales/Array/reduce | |
* to recursively flatten a multidemensional array. | |
* The array can be arbitrarly deep | |
*/ | |
const flatten = list => list.reduce( | |
(a, b) => a.concat(Array.isArray(b) ? flatten(b) : b), [] | |
); | |
// Testing with chai and mocha | |
describe('Array flatten', function() { | |
it('Should return a flat version of a bi-dimensional array', function() { | |
const array = [[1,2],[3,4]] | |
const flat = flatten(array) | |
const truth = flat.flat(Infinity) | |
expect(flat).to.have.length(truth.length) | |
expect(flat).to.have.deep.members(truth) | |
}) | |
it('Should get a flat version of complext array', function() { | |
/** Boilerplate to generate random custom nested array */ | |
const genObject = () => ({ | |
id: Math.ceil(Math.random()*100), | |
value: Math.random() | |
}) | |
const genTotal = () => { | |
return Math.ceil(Math.random()*100) | |
} | |
const genNestedBoard = ({ width, height}) => | |
Array.from({ length: height}, () => Array.from({ length: width }, () => genObject() ) | |
); | |
const nested = genNestedBoard({ width: genTotal(), height: genTotal() }) | |
const flat = flatten(nested) | |
const truth = flat.flat(Infinity) | |
expect(flat).to.have.length(truth.length) | |
expect(flat).to.have.deep.members(truth) | |
}) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment