Skip to content

Instantly share code, notes, and snippets.

@javcasas
Created March 7, 2019 23:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save javcasas/3cf21296a1a3a9275af02831d32f4d16 to your computer and use it in GitHub Desktop.
Save javcasas/3cf21296a1a3a9275af02831d32f4d16 to your computer and use it in GitHub Desktop.
//////////////
// 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