npm test
npm run console
var flatten = require("./flatten.js").default
flatten([1,2,[3])
{ "presets": ["es2015"] } |
const unpack = (el) => { | |
if(Array.isArray(el)) { | |
return flatten(el); | |
} else { | |
return el; | |
} | |
}; | |
export default function flatten(array) { | |
if(!Array.isArray(array)) { | |
throw "Only arrays can be flatten"; | |
} | |
return array.reduce((a, b) => { | |
return unpack(a).concat(unpack(b)); | |
}, []); | |
}; |
var test = require('tape'); | |
import flatten from './flatten'; | |
test('flatten of empty array is empty array', (t) => { | |
t.plan(3); | |
var flatten_empty = flatten([]); | |
t.same(flatten_empty, [], 'array with no elements is already flatten'); | |
var flatten_empty_nested = flatten([[]]); | |
t.same(flatten_empty_nested, [], 'array with nested empty array should be flatten to empty array'); | |
var flatten_empty_two_levels = flatten([[[]]]); | |
t.same(flatten_empty_two_levels, [], 'array with multiple levels of empty array should be flatten to empty array'); | |
}); | |
test('flatten of multiple levels', (t) => { | |
t.plan(2); | |
var flatten_two_levels = flatten([1,2, [3,4]]); | |
t.same(flatten_two_levels, [1,2,3,4], 'elements from inside array should be on the same level after flattening') | |
var flatten_five_levels = flatten([1,2, [3,[[4]]]]); | |
t.same(flatten_two_levels, [1,2,3,4], 'elements from inside array should be on the same level after flattening') | |
}); | |
test('flatten of example array', (t) => { | |
t.plan(1); | |
t.same(flatten([1,2,[3],4]), [1,2,3,4]); | |
}); |
{ | |
"name": "citrusbyte_flatten", | |
"version": "1.0.0", | |
"description": "", | |
"main": "flatten.js", | |
"scripts": { | |
"pretest": "npm install", | |
"test": "babel-node flatten_test.js" | |
}, | |
"author": "", | |
"license": "ISC", | |
"devDependencies": { | |
"babel-cli": "^6.9.0", | |
"babel-core": "^6.9.0", | |
"babel-preset-es2015": "^6.9.0", | |
"tape": "^4.5.1" | |
} | |
} |