Skip to content

Instantly share code, notes, and snippets.

@oscarmyepes
Last active August 9, 2017 05:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save oscarmyepes/4303d5970f1c4ee07836805fe6c78775 to your computer and use it in GitHub Desktop.
Save oscarmyepes/4303d5970f1c4ee07836805fe6c78775 to your computer and use it in GitHub Desktop.
// Using commonjs js modules
import utils from './services/utils';
let array = [[1,2,[3]],4];
let newArray = utils.flat(array);
console.log(newArray);
// utils.service
export default const utils = {
flat(array) {
let flatedArr = array.reduce(function iter(acc, item) {
if (Array.isArray(item)) {
return item.reduce(iter, acc);
} else {
return acc.concat(item);
}
}, []);
return flatedArr;
},
otherUtilFcn() {
}
}
//Test done with jest
import utils from './utils';
describe('when need to flat array', () => {
test('should flat normal array', () => {
// Arrange
const arr = [1,2,3,4,5];
// Act
const response = utils.flat(arr);
// Assert
expect(response).toEqual([1,2,3,4,5]);
});
test('should flat complex array', () => {
// Arrange
const arr = [1,2,3,4,5,[1,2], [1, [2,3,[4,5,[6,7]]]],8];
// Act
const response = utils.flat(arr);
// Assert
expect(response).toEqual([1, 2, 3, 4, 5, 1, 2, 1, 2, 3, 4, 5, 6, 7, 8]);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment