Skip to content

Instantly share code, notes, and snippets.

@pacoccino
Created February 7, 2019 11:37
Show Gist options
  • Save pacoccino/b57955a7875ae5513b463813e4881d88 to your computer and use it in GitHub Desktop.
Save pacoccino/b57955a7875ae5513b463813e4881d88 to your computer and use it in GitHub Desktop.
function flatten(arr) {
let flattened = [];
for(let i in arr) {
if(Array.isArray(arr[i])) {
flattened = flattened.concat(flatten(arr[i]));
} else {
flattened.push(arr[i]);
}
}
return flattened;
}
module.exports = flatten;
const expect = require('chai').expect;
const flatten = require('./flatten');
const tests = [
[1, 2, 3, 4],
[1, [2, 3], 4],
[1, [2], [3, 5, 6, [11, 22, 44]], 4],
];
const expected = [
[1, 2, 3, 4],
[1, 2, 3, 4],
[1, 2, 3, 5, 6, 11, 22, 44, 4],
];
describe('flatten', () => {
it('should flatten', () => {
for(let i in tests) {
expect(flatten(tests[i])).to.deep.eq(expected[i]);
}
})
});
{
"name": "flatten",
"version": "1.0.0",
"main": "flatten.js",
"license": "MIT",
"dependencies": {
"chai": "^4.2.0",
"mocha": "^5.2.0"
},
"scripts": {
"test": "mocha -R spec ./flatten.spec.js"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment