Skip to content

Instantly share code, notes, and snippets.

@bmdalex
Last active November 17, 2018 01:40
Show Gist options
  • Select an option

  • Save bmdalex/1514e60ab36d2b36a4e330fb2b659f84 to your computer and use it in GitHub Desktop.

Select an option

Save bmdalex/1514e60ab36d2b36a4e330fb2b659f84 to your computer and use it in GitHub Desktop.
citrusbyte problem
// 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