Skip to content

Instantly share code, notes, and snippets.

@musicm122
Created May 30, 2019 20:54
Show Gist options
  • Save musicm122/9cc3e2575bf53371c7a29c9a29236e66 to your computer and use it in GitHub Desktop.
Save musicm122/9cc3e2575bf53371c7a29c9a29236e66 to your computer and use it in GitHub Desktop.
Typescript Numeric Array Flatten
/*
Write some code, that will flatten an array of arbitrarily nested arrays of integers into a flat array of integers. e.g. [[1,2,[3]],4] -> [1,2,3,4].
Your solution should be a link to a gist on gist.github.com with your implementation.
When writing this code, you can use any language you're comfortable with. The code must be well tested and documented. Please include unit tests and any documentation you feel is necessary. In general, treat the quality of the code as if it was ready to ship to production.
Try to avoid using language defined methods like Ruby's Array#flatten.
Thank you so much!! *
*/
/**
* Function that takes an array of numbers
* with any amount of array nesting and converts nested
* arrays to a single array with all elements.
*/
export function fold(arr: any) {
let i: number = 0;
for (i = 0; i < arr.length; i++) {
while (true) {
if (Array.isArray(arr[i])) {
//If element is
arr.splice(i, 1, ...arr[i]);
} else {
break;
}
}
}
return arr;
}
import { fold } from './index';
import { expect } from 'chai';
import 'mocha';
describe('Fold function', () => {
it('undefined argument should throw ', () => {
expect(()=>fold(undefined)).to.throw();
});
it('null argument should throw ', () => {
expect(()=>fold(null)).to.throw();
});
it('empty array should throw', () => {
let expected:number[] = [];
let arg:number[] = [];
let actual = fold(arg);
expect(expected).to.eql(actual);
});
it('single index array should return argument passed', () => {
let input = [1];
let expected = [1];
let actual = fold(input);
expect(expected).to.eql(actual);
});
it('array with single nested array should return single array', () => {
let input = [1,[2]];
let expected = [1,2];
let actual = fold(input);
expect(expected).to.eql(actual);
});
it('array with multiple one level deep nested array should return single array', () => {
let input = [1,[2],[3]];
let expected = [1,2,3];
let actual = fold(input);
expect(expected).to.eql(actual);
});
it('array with multiple many level deep nested array should return single array', () => {
let input = [1,[2],[3,[23,33]], [1,2,3,4],[21,21,2,1]];
let expected = [1,2,3,23,33,1,2,3,4,21,21,2,1];
let actual = fold(input);
expect(expected).to.eql(actual);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment