Skip to content

Instantly share code, notes, and snippets.

@paschalidi
Last active Oct 18, 2019
Embed
What would you like to do?
A simple function that recursively flattens a given `array`
import { flatten } from "./flatten";
describe("flatten method", function() {
it("should flatten deeply arrays", function() {
const array = [1, [2, [3, [4]], 5]];
const flatArray = flatten(array);
const expected = [1, 2, 3, 4, 5];
expect(flatArray).toEqual(expected);
});
it("should work with empty arrays", function() {
var array = [[], [[]], [[], [[[]]]]];
const flatArray = flatten(array);
const expected = [];
expect(flatArray).toEqual(expected);
});
it("should skip from adding empty arrays to the result", function() {
const array = [[1, 2, 3], [], [], []];
const flatArray = flatten(array);
const expected = [1, 2, 3];
expect(flatArray).toEqual(expected);
});
it("should work only with objects", function() {
const array = [{ zero: true }, [{ one: true }, [{ two: true }]]];
const flatArray = flatten(array);
const expected = [{ zero: true }, { one: true }, { two: true }];
expect(flatArray).toEqual(expected);
});
it("should work with a empty strings", function() {
const array = ["", [[[""], ""]]];
const flatArray = flatten(array);
const expected = ["", "", ""];
expect(flatArray).toEqual(expected);
});
it("should work with a variaty of types", function() {
const array = [[1, 2, 3], { zero: true }, [[[{ one: true }, ["a"]]]]];
const flatArray = flatten(array);
const expected = [1, 2, 3, { zero: true }, { one: true }, "a"];
expect(flatArray).toEqual(expected);
});
it("should work with a variaty of types", function() {
const array = [[1, 2, 3], { zero: true }, [[[{ one: true }, ["a"]]]]];
const flatArray = flatten(array);
const expected = [1, 2, 3, { zero: true }, { one: true }, "a"];
expect(flatArray).toEqual(expected);
});
});
/**
* Recursively flattens a given `array`.
*
* @param {Array} array The array to flatten.
* @param {Array} result The accumulated value tha is recursively being flattened.
* @returns {Array} Returns the new flattened array.
*
* @example
* flatten([1, [2, [3, [4]], 5]])
* will result into -> [1, 2, 3, 4, 5]
*/
export function flatten(array: Array<any>, result?: Array<any>): Array<any> {
result || (result = []);
if (array == null) {
return result;
}
array.forEach(value =>
Array.isArray(value) ? flatten(value, result) : result.push(value)
);
return result;
}
@paschalidi
Copy link
Author

paschalidi commented Oct 18, 2019

You can visit this environment in case you would be interested in running the tests.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment