Skip to content

Instantly share code, notes, and snippets.

@TimothyDalbey
Created October 11, 2019 00:11
Show Gist options
  • Save TimothyDalbey/21810ff0ad9791c616c0b3f05a4dd9b8 to your computer and use it in GitHub Desktop.
Save TimothyDalbey/21810ff0ad9791c616c0b3f05a4dd9b8 to your computer and use it in GitHub Desktop.
Flatten Array

Install with npm install then execute npm run test

const flattenArray = (t) => {
return t.reduce((current, next) => {
if(Number.isInteger(next)){
current.push(next);
}else if(Array.isArray(next)){
flattenArray(next).map(i => current.push(i));
}else{
throw new Error("Not a Integer or an Array");
}
return current;
}, []);
};
module.exports = {
flattenArray: flattenArray
}
let flattenArray = require('./flattenArray.js');
describe("flattenArray", () => {
test("Successfully flattens into a array of integers", () => {
const test_object = [
1,
[14, 12],
432,
[511, [0],
[212, 5]
],
3
];
const expected_result = [1, 14, 12, 432, 511, 0, 212, 5, 3];
const result = flattenArray.flattenArray(test_object);
expect(result).toEqual(expected_result);
});
});
{
"name": "flattenarray",
"version": "1.0.0",
"description": "Flattens an array of integers and arrays of integers into an array of integers.",
"main": "flattenArray.js",
"author": "Timothy Dalbey",
"license": "ISC",
"dependencies": {
"jest": "^24.9.0"
},
"scripts":{
"test":"jest *.test.js"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment