Created
August 13, 2019 22:01
-
-
Save ivansnek/e61cfcd1418347697646e6f6651f33c4 to your computer and use it in GitHub Desktop.
Array Flatten Exercise
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
***************************************************************************************** | |
* Source File | |
* Copyright (C) 2019 IvanSnek | |
* | |
* [CHANGE HISTORY] | |
* 1. 2019-Aug-13 (ivansnek) File created | |
* | |
***************************************************************************************** | |
*/ | |
/** | |
* This helper function allows to flatten a given array e.g. [[1,2,[3]],4] -> [1,2,3,4]. | |
* If the value provided to the function is not a valid array it will return null. | |
* @param {Array} values Given array to flatten | |
* @returns {Array} The flatten version of the given value. | |
*/ | |
function flattenArray(values) { | |
if (Array.isArray(values)) { | |
return values | |
.join(",") | |
.split(",") | |
.map(val => parseInt(val)); | |
} | |
return null; | |
} | |
module.exports = { flattenArray }; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
***************************************************************************************** | |
* Source File | |
* Copyright (C) 2019 IvanSnek | |
* | |
* [CHANGE HISTORY] | |
* 1. 2019-Aug-13 (ivansnek) File created | |
* | |
***************************************************************************************** | |
*/ | |
const { flattenArray } = require("./arrayUtils.js"); | |
/** Tests Values*/ | |
const testValues1 = [1]; | |
const testValues2 = [1, 3, 4, [23, 32]]; | |
const testValues3 = [ | |
[[2, 3], [[23, 23, [9, 9, [10, [10]]]]]], | |
1, | |
9, | |
[[23, 23, [9, 9, [10, [10]]]]], | |
[9, 9, [10, [10]]] | |
]; | |
test("arrayUtils.flattenArray should flatten a given valid array", () => { | |
expect(flattenArray(testValues1)).toEqual([1]); | |
expect(flattenArray(testValues2)).toEqual([1, 3, 4, 23, 32]); | |
expect(flattenArray(testValues3)).toEqual([ | |
2, | |
3, | |
23, | |
23, | |
9, | |
9, | |
10, | |
10, | |
1, | |
9, | |
23, | |
23, | |
9, | |
9, | |
10, | |
10, | |
9, | |
9, | |
10, | |
10 | |
]); | |
}); | |
test("arrayUtils.flattenArray should return null with no valid array values", () => { | |
expect(flattenArray("testValue")).toBeNull(); | |
expect(flattenArray(null)).toBeNull(); | |
expect(flattenArray(undefined)).toBeNull(); | |
expect(flattenArray({})).toBeNull(); | |
expect(flattenArray({ key: 1 })).toBeNull(); | |
}); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment