Last active
August 9, 2017 05:57
-
-
Save oscarmyepes/4303d5970f1c4ee07836805fe6c78775 to your computer and use it in GitHub Desktop.
This file contains 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
// Using commonjs js modules | |
import utils from './services/utils'; | |
let array = [[1,2,[3]],4]; | |
let newArray = utils.flat(array); | |
console.log(newArray); |
This file contains 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
// 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() { | |
} | |
} | |
This file contains 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
//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