Last active
September 17, 2019 14:30
-
-
Save theodesp/3604db3d031c890143ef8927d92bab92 to your computer and use it in GitHub Desktop.
Flattens an array of arbitrarily nested arrays of integers into a flat array of integers #go
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
| /** | |
| * Flattens an array of arbitrarily nested arrays of integers | |
| * into a flat array of integers. | |
| * | |
| * @param {array} arr The array to flatten. | |
| * @returns {array} Flattened array | |
| */ | |
| const flatten = (arr = []) => { | |
| if (!isArray(arr)) { | |
| return []; | |
| } | |
| let result = []; | |
| for (let item of arr) { | |
| if (isArray(item)) { | |
| result = result.concat(flatten(item)); | |
| } else { | |
| result = result.concat(item); | |
| } | |
| } | |
| return result; | |
| }; | |
| const isArray = (arr) => { | |
| return arr instanceof Array; | |
| }; | |
| exports.flatten = flatten; |
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
| const test = require('tape'); | |
| const flatten = require('../src/flatten').flatten; | |
| test('flatten tests', function (t) { | |
| t.plan(6); | |
| // format is {'testName': [input, expected]} | |
| const tests = { | |
| 'object':[{},[]], | |
| 'empty': [[], []], | |
| 'oneElementDeep': [[1,2,3], [1,2,3]], | |
| 'twoElementsDeep': [[[1,[3,4],5]], [1,3,4,5]], | |
| 'threeElementsDeep': [[1,[2,[3,4],5]], [1,2,3,4,5]], | |
| 'multipleElementsDeep': [[[[1]],2,[3,[3,5],[6,[7,8]]]], [1,2,3,3,5,6,7,8]], | |
| }; | |
| for (const [key, value] of Object.entries(tests)) { | |
| t.deepEqual(flatten(value[0]), value[1], key); | |
| } | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment