Skip to content

Instantly share code, notes, and snippets.

@sgimeno
Created March 27, 2018 12:18
Show Gist options
  • Save sgimeno/52b693ccafda139aa3b134dd934626ab to your computer and use it in GitHub Desktop.
Save sgimeno/52b693ccafda139aa3b134dd934626ab to your computer and use it in GitHub Desktop.
Flatten Arrays
const flatten = (arr) => {
const res = []
const flattenRec = (elem) => {
if (Array.isArray(elem) && elem.length > 0) {
elem.forEach(e => flattenRec(e))
} else {
res.push(elem)
}
}
if (Array.isArray(arr) && arr.length > 0) {
flattenRec(arr, res)
return res
} else {
return arr
}
}
module.exports = flatten
{
"name": "citrus-flatten",
"version": "1.0.0",
"description": "Flatten Arrays",
"main": "flatten.js",
"scripts": {
"test": "node test.js"
},
"devDependencies": {
"tape": "^4.9.0"
}
}
const test = require('tape')
const flatten = require('./flatten')
test('Should only process Array elements', t => {
t.plan(6)
t.equal(flatten(undefined), undefined, 'Should not process undefined')
t.equal(flatten(null), null, 'Should not process null')
t.equal(flatten(1), 1, 'Should not process literals')
t.equal(flatten('foo'), 'foo', 'Should not process literals')
t.deepEqual(flatten({}), {}, 'Should not process objects')
t.deepEqual(flatten([1,2,3]), [1,2,3], 'Should process Arrays')
})
test('Should flatten nested Arrays', t => {
t.plan(1)
t.deepEqual(
flatten([[1,2], [3], 4, [[[6], 5], 20], [[[[null], undefined]]], null, undefined]),
[1, 2, 3, 4, 6, 5, 20, null, undefined, null, undefined],
'Should flatten Arrays'
)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment