Skip to content

Instantly share code, notes, and snippets.

@psypersky
Last active June 9, 2016 23:31
Show Gist options
  • Save psypersky/1220172825b94aaaca5c00ce0c493d21 to your computer and use it in GitHub Desktop.
Save psypersky/1220172825b94aaaca5c00ce0c493d21 to your computer and use it in GitHub Desktop.
Flat Array
node_modules
function startFlat(arr) {
let arrRes = []
if (!Array.isArray(arr)) {
return null;
}
return flatArray(arr);
function flatArray(arr) {
for (let i = 0; i < arr.length; i++) {
if (Array.isArray(arr[i])) {
flatArray(arr[i])
} else {
arrRes.push(arr[i]);
}
}
return arrRes;
}
}
module.exports = startFlat;
{
"name": "flat-array",
"version": "1.0.0",
"description": "",
"main": "flatArray.js",
"scripts": {
"test": "mocha"
},
"author": "",
"license": "ISC",
"dependencies": {
"chai": "^3.5.0"
}
}
const chai = require('chai');
const flatArray = require('./flatArray');
describe('Array', function() {
it('Should flat nested arrays', function () {
const arr = [[1, 2], 3];
chai.expect(flatArray(arr)).to.eql([1, 2, 3]);
});
it('Should return null if the input is not an array', function() {
chai.assert.equal(flatArray({ foo: 'bar' }), null);
});
it('Should flat deep nested array', function() {
const arr = [
1,
[
[
2,
3,
4,
[{ five: 'six' }, 'seven'],
8
]
],
9
];
chai.expect(flatArray(arr)).to.eql([1, 2, 3, 4, { five: 'six' }, 'seven', 8, 9]);
})
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment