Created
March 7, 2019 23:00
-
-
Save javcasas/3cf21296a1a3a9275af02831d32f4d16 to your computer and use it in GitHub Desktop.
This file contains 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
////////////// | |
// index.js // | |
////////////// | |
function flatten1(arr) { | |
// Imperative flatten that works by attaching elements to a resulting array | |
const res = []; | |
function inner(a) { | |
if(Array.isArray(a)) { | |
a.forEach(inner); | |
} else { | |
res.push(a); | |
} | |
} | |
inner(arr); | |
return res; | |
} | |
function flatten2(arr) { | |
// Functional flatten. Works by recursively flattening the array, or converting non-array items into a singleton array. | |
if (Array.isArray(arr)) { | |
return [].concat(...arr.map(flatten2)) | |
} else { | |
return [arr] | |
} | |
} | |
function flatten3(arr) { | |
// Functional flatten. Works by appending the rest of the items one by one. | |
return arr.reduce((acc, cval) => { | |
if (Array.isArray(cval)) { | |
return acc.concat(flatten3(cval)); | |
} else { | |
return acc.concat([cval]); | |
} | |
}, []) | |
} | |
exports.flatten1 = flatten1 | |
exports.flatten2 = flatten2 | |
exports.flatten3 = flatten3 | |
/////////////////// | |
// index.test.js // | |
/////////////////// | |
const {flatten2, flatten2, flatten3} = require('./index'); | |
const base = [[1,2,[3]],4]; | |
const expected = [1,2,3,4]; | |
test('flatten1 works as expected', () => { | |
expect(flatten1(base)).toEqual(expected); | |
}); | |
test('flatten2 works as expected', () => { | |
expect(flatten2(base)).toEqual(expected); | |
}); | |
test('flatten3 works as expected', () => { | |
expect(flatten3(base)).toEqual(expected); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment