Skip to content

Instantly share code, notes, and snippets.

@gutenye
Created July 3, 2016 10:23
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 gutenye/9de2af085166fb11c35f8cc175fa027b to your computer and use it in GitHub Desktop.
Save gutenye/9de2af085166fb11c35f8cc175fa027b to your computer and use it in GitHub Desktop.
#!/usr/bin/env node
//
//
// Does not use ES6 Spread operator or any external dependency.
// flatten an array of arbitrarily nested arrays into a flat array.
//
// USAGE
//
// flatten([[1, 2, [3]], 4]) // -> [1, 2, 3, 4]
//
function flatten(array) {
return _flatten([], array)
}
// I'm a rescurive function.
function _flatten(result, array) {
array.map(value => {
if (isArray(value)) {
_flatten(result, value)
} else {
result.push(value)
}
})
return result
}
// A simple test helper, will throw an error if does not match.
function test(name, input, expect) {
var result = flatten(input)
if (!equalArray(result, expect)) {
throw new Error(`${name}: Expected ${JSON.stringify(expect)}, got ${JSON.stringify(result)}`)
}
}
//
// Helpers
//
// Test is the obj is an Array.
function isArray(obj) {
return Object.prototype.toString.call(obj) === "[object Array]"
}
// A simple equal for array, not a deep equal
function equalArray(array, other) {
if (array.length !== other.length) {
return false
}
for (let i=0; i<array.length; i++) {
if (array[i] !== other[i])
return false
}
return true
}
//
// Main
//
test("empty array", [], [])
test("simple array", [1, 2], [1, 2])
test("one nested array", [1, [2], 3], [1, 2, 3])
test("two nested arrays", [[1, 2, [3]], 4], [1, 2, 3, 4])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment