Last active
June 15, 2021 02:47
-
-
Save rajatjain-21/497d2561e0e9ec74997955ab017c8ba8 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
const input = [ | |
1, 2, 3, | |
[4], | |
[5, 6, [7], [8, [9, [10]]]], | |
11, 12, 13, | |
[14, [[[[[15, [16]]]]]]], | |
17, 18, | |
[19, [20, [21, [22, [23, [24, [[[[[25]]]]]]]]]]] | |
]; | |
// SOLUTION 1 | |
const resultArry = []; | |
Array.prototype.flattenNaïve = function() { | |
const obj = this || []; | |
if(obj.forEach) { | |
obj.forEach(item => { | |
if(Array.isArray(item)) { | |
item.flattenNaïve(); | |
} else { | |
resultArry.push(item); | |
} | |
}); | |
} | |
return resultArry; | |
} | |
console.log(input.flattenNaïve()); | |
// SOLUTION 2 | |
Array.prototype.flattenWithReduce = function() { | |
if (this.reduce) { | |
return this.reduce((acc, item) => { | |
if (Array.isArray(item)) { | |
return [...acc, ...item.flattenWithReduce()] | |
} else { | |
return [...acc, item]; | |
} | |
}, []); | |
} | |
} | |
console.log(input.flattenWithReduce()); |
Hey Priyadarshanvijay, completely agree with what you pointed out here. Pure functions are indeed the essence of FP. Pushed another commit with the changes
Thanks @rajatjain-21 , learnt all this from CodeAsylums only 😄
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
But wouldn't pushing to
acc
in the reduce function make it an impure function, hence violating the functional programming paradigm. Can we instead do it this way:Just suggesting, I might be wrong as well 😅