Last active
June 9, 2016 23:31
-
-
Save psypersky/1220172825b94aaaca5c00ce0c493d21 to your computer and use it in GitHub Desktop.
Flat Array
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
node_modules |
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
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; |
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
{ | |
"name": "flat-array", | |
"version": "1.0.0", | |
"description": "", | |
"main": "flatArray.js", | |
"scripts": { | |
"test": "mocha" | |
}, | |
"author": "", | |
"license": "ISC", | |
"dependencies": { | |
"chai": "^3.5.0" | |
} | |
} |
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 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