Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const expect = require('chai').expect;
- // Implementation of flatten(array)
- function flatten(array) {
- // early return if it is not an array or if empty
- if (!array || !Array.isArray(array)) {
- return;
- }
- return array.reduce((flattened, element) => {
- return flattened.concat(Array.isArray(element) ? flatten(element) : [element]);
- }, []);
- }
- // Unit tests to run with Mocha and Chai.
- // In order to install, run
- // "npm install --save-dev mocha chai"
- // and then run "node_modules/.bin/mocha flatten.js"
- describe('flatten(array)', () => {
- const assertResult = (input, output) => expect(flatten(input)).to.deep.equals(output);
- it('should return undefined if the argument is not an array', () => {
- assertResult(undefined, undefined);
- assertResult({}, undefined);
- assertResult(1, undefined);
- assertResult("1", undefined);
- assertResult(true, undefined);
- });
- it('should return an empty array if the argument is an empty array', () => {
- assertResult([], []);
- });
- it('should return the same array if it is already flattened', () => {
- let input = [1, 2, 3];
- assertResult(input, input);
- });
- it('should return a flattened array if it has one array in it', () => {
- let input = [1, [1, 2, 3], 4];
- let output = [1, 1, 2, 3, 4];
- assertResult(input, output);
- });
- it('should return a flattened array for 3 nested levels', () => {
- let input = [1, [1, [2, [3]]], 4];
- let output = [1, 1, 2, 3, 4];
- assertResult(input, output);
- });
- it('should return a flattened array for 99 nested levels', () => {
- let output = Array.from({ length: 99 }, (v, index) => index);
- // here we do not use the output of reduce, because each callback will be returning a reference to the last "nested"
- // array. So maintain the reference from the inital state
- let input = [];
- output.reduce((accum, element) => {
- let lastElementArray = [element];
- accum.push(lastElementArray);
- return lastElementArray;
- }, input);
- assertResult(input, output);
- });
- });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement