Skip to content

Instantly share code, notes, and snippets.

@nickydonna
Last active January 31, 2017 14:43
Show Gist options
  • Save nickydonna/f8445592b91c31b4d6baa16b62ff8d82 to your computer and use it in GitHub Desktop.
Save nickydonna/f8445592b91c31b4d6baa16b62ff8d82 to your computer and use it in GitHub Desktop.
A simple implementation of flatten
const isArray = Array.isArray;
const reducer = (acc, ele) => {
const elements = isArray(ele) ? flatten(ele) : ele;
return acc.concat(elements);
};
const reduce = (arr) => arr.reduce(reducer, []);
const flatten = arr => isArray(arr) ? reduce(arr) : arr;
module.exports = flatten;

FLATTEN

This code is a simple implementation of the flatten function for Nodejs. There are no external dependencies.

TEST

the assert library is used for testing to avoid external dependencies. To test the function simple run node test.js with node 6.x.x

USAGE

If you want to use the function, just import the library:

const flatten = require('./flatten');

console.log(flatten([1,2,[3]])
const { deepEqual } = require('assert');
const flatten = require('./flatten');
deepEqual(1, flatten(1));
deepEqual([1,2,3], flatten([1,2,3]));
deepEqual([1,2,3], flatten([1,[2],3]));
deepEqual([1,2,3,4], flatten([1,2,[3,[4]]]));
deepEqual([1,2,3,4,5,6,7], flatten([1,2,[3,[4,[5,6,7]]]]));
deepEqual(['a',{},1,1.4], flatten([[[[['a',{},1,1.4]]]]]));
console.log('All Test Passed');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment