Skip to content

Instantly share code, notes, and snippets.

@jesterswilde
Last active April 1, 2019 01:23
Show Gist options
  • Save jesterswilde/66afcaa66646f7b19c7e21224c3f1215 to your computer and use it in GitHub Desktop.
Save jesterswilde/66afcaa66646f7b19c7e21224c3f1215 to your computer and use it in GitHub Desktop.
/*
I made a handful of decisions about this function:
1) I know you said array of integers, but I decided to make it a bit more resiliant.
2) If you give me a non-array, I will just spit that back at you
3) This is a functional thing, so I will return a new array instead of flattening in place
4) I did use newer language features, my assumption is that this will run in an environment where that is ok, or it will be transpiled
5) Flatten is strictly about arrays, so I don't do anything with objects.
*/
const flatten = (toFlattenArr) => {
if (!Array.isArray(toFlattenArr)) {
return toFlattenArr;
}
return toFlattenArr.reduce((result, el) => {
if (Array.isArray(el)) {
result.push(...flatten(el));
} else {
result.push(el);
}
return result;
}, []);
};
describe('flatten', () => {
it('should handle empty arrays', () => {
const arr = flatten([]);
expect(arr).toEqual([]);
});
it('should return a new array', () => {
const originalArray = [];
const arr = flatten(originalArray);
expect(arr).not.toBe(originalArray);
});
it('should handle non array values gracefully', () => {
const num = flatten(5);
const obj = {
foo: 'bar'
};
const nil = null;
const und = flatten();
expect(num).toEqual(5);
expect(obj).toEqual({
foo: 'bar'
});
expect(nil).toEqual(null);
expect(und).toEqual(undefined);
});
it('should flatten arbitrarly nested arrays', () => {
const unflattened = [1,
[2, 3],
[4,
[{
foo: []
}, 'a', ['b']],
['c']
]
];
const flattened = flatten(unflattened);
expect(flattened).toEqual([1, 2, 3, 4, { foo: [] }, 'a', 'b', 'c']);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment