Last active
November 17, 2018 01:40
-
-
Save bmdalex/1514e60ab36d2b36a4e330fb2b659f84 to your computer and use it in GitHub Desktop.
citrusbyte problem
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
| // Implementation: | |
| const callIfArray = (arr, cb) => Array.isArray(arr) ? cb(arr) : arr; | |
| const flattenRec = (arr) => arr.reduce( | |
| (acc, curr) => acc.concat(callIfArray(curr, flattenRec)), | |
| [] | |
| ); | |
| const flattenArray = (arr) => callIfArray(arr, flattenRec); | |
| // Testing: | |
| const tests = [ | |
| { | |
| input: undefined, | |
| expected: undefined, | |
| }, | |
| { | |
| input: [], | |
| expected: [], | |
| }, | |
| { | |
| input: '', | |
| expected: '', | |
| }, | |
| { | |
| input: [[1,2,[3]],4], | |
| expected: [ 1, 2, 3, 4 ], | |
| }, | |
| { | |
| input: [[1,2,[3, [[1,[[[]],[]],2,[3]],[[1,2,[3]],4], [[1,2,[3]],4]]]],4], | |
| expected: [ 1, 2, 3, 1, 2, 3, 1, 2, 3, 4, 1, 2, 3, 4, 4 ], | |
| }, | |
| { | |
| input: [[[1,2,[3]],4], [[1,2,[3]],], [[1,2,[3]],4]], | |
| expected: [ 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4 ], | |
| }, | |
| ] | |
| tests.forEach(({ input, expected }, index) => { | |
| const actual = flattenArray(input); | |
| if (JSON.stringify(expected) === JSON.stringify(actual)) { | |
| console.log('PASSED!') | |
| } else { | |
| console.error('Test ', index, ' has failed. Expected:\n', expected, '\nbut got:\n', actual); | |
| } | |
| }) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment