Last active
May 20, 2016 00:42
-
-
Save heyolajyd/24453fedb24aae402cfd12d1a480b7e8 to your computer and use it in GitHub Desktop.
Simple function to flatten an array of arbitrarily nested arrays of integers into a flat array of integers with tests in 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
Set up a simple folder strucure thus: | |
``` | |
FlattenList | |
|-src | |
| |-index.js | |
|-test | |
| |-test.js | |
|-package.json | |
``` | |
To run tests: | |
simply run: `npm run test` |
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
// Helper function to flatten a given nested array | |
export default function flattenList(arr) { | |
return arr.reduce((current, next) => current.concat( | |
Array.isArray(next) ? flattenList(next) : next), [] | |
) | |
}; |
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
{ | |
"name": "flattenlist", | |
"version": "1.0.0", | |
"author": "Jyd", | |
"description": "Simple function to flatten an arbitrary list of nested array", | |
"main": "index.js", | |
"scripts": { | |
"test": "mocha --compilers js:babel-core/register --recursive", | |
"test:watch": "npm run test -- --watch" | |
}, | |
"devDependencies": { | |
"babel-cli": "^6.5.1", | |
"babel-core": "^6.5.2", | |
"babel-preset-es2015": "^6.5.0", | |
"mocha": "^2.4.5", | |
"chai": "^3.5.0" | |
}, | |
"license": "ISC", | |
"babel": { | |
"presets": [ | |
"es2015" | |
] | |
} | |
} |
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
import flattenList from '../src/index'; | |
import { expect } from 'chai' | |
describe('Flatten an array', () => { | |
const testCaseOne = [[1,2,[3]],4]; | |
const testCaseTwo = [[1], [2, 3], [4, [5, [6, [7, [8]]]]]]; | |
it('should flatten the nested array for testCaseOne', () => { | |
const expected = [1,2,3,4]; | |
const result = flattenList(testCaseOne); | |
expect(result).to.deep.equal(expected); | |
}); | |
it('should flatten the nested array for testCaseTwo', () => { | |
const expected = [1,2,3,4, 5,6,7,8]; | |
const result = flattenList(testCaseTwo); | |
expect(result).to.deep.equal(expected); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment