Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // 'flatten' flattend arbitrary nested value sequences into
- // a single array of values
- const flatten = (input: []): number[] => {
- const flattened: number[] = []
- for (let i = 0; i < input.length; i++) {
- // If current value is an array, call flatten on it too
- if (Array.isArray(input[i])) {
- // flatten returned array with spread operator
- flattened.push(...flatten(input[i]))
- } else {
- // If value is a primitive, push it into answer array
- flattened.push(input[i])
- }
- }
- return flattened
- }
- module.exports = flatten
- //// Tests
- //// Since you guys asked for a single file, I've added the commented tests below :)
- /*
- const flatten = require('./flatten.ts')
- describe('flatten', () => {
- expect(flatten([
- [1, 2, [3]], a
- 4
- ])).toEqual([
- 1, 2, 3, 4
- ])
- expect(flatten([
- [1, [2, [3]]],
- [[4]]
- ])).toEqual([
- 1, 2, 3, 4
- ])
- expect(flatten([
- [[[[[[[[1]]]]]]], 2],
- [[3], [[[[[[4]]]]]]], 5
- ])).toEqual([
- 1, 2, 3, 4, 5
- ])
- })
- */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement