Skip to content

Instantly share code, notes, and snippets.

@itelo
Created August 11, 2019 21:08
Show Gist options
  • Save itelo/6256fd300ed72410fa69768203577deb to your computer and use it in GitHub Desktop.
Save itelo/6256fd300ed72410fa69768203577deb to your computer and use it in GitHub Desktop.
// flatten.js
const flatten = (array) => {
return array.reduce((acc, elm) => {
if (Array.isArray(elm)) {
acc.push(...flatten(elm))
} else {
acc.push(elm);
}
return acc;
}, []);
}
module.exports = flatten;
// flatten-test.js
const flatten = require('./flatten');
describe('flatten', () => {
it('[[1,2,[3]],4] should return [1, 2, 3, 4]', () => {
expect(flatten([[1,2,[3]],4])).toEqual(expect.arrayContaining([1, 2, 3, 4]));
});
it('[[[[1]]]] should return [1]', () => {
expect(flatten([[[[1]]]])).toEqual(expect.arrayContaining(([1])));
});
});
// the code run in https://repl.it/repls/HelplessLoudScripts
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment