Skip to content

Instantly share code, notes, and snippets.

@rajatjain-21
Last active June 15, 2021 02:47
Show Gist options
  • Select an option

  • Save rajatjain-21/497d2561e0e9ec74997955ab017c8ba8 to your computer and use it in GitHub Desktop.

Select an option

Save rajatjain-21/497d2561e0e9ec74997955ab017c8ba8 to your computer and use it in GitHub Desktop.
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());
@Priyadarshanvijay
Copy link
Copy Markdown

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:

Array.prototype.flattenWithReduce = function() {
	if (this.reduce) {
  	return this.reduce((acc, item) => {
      if (Array.isArray(item)) {
        return [...acc, ...item.flattenWithReduce()];
      }
      return [...acc, item];
    }, []);
  }
}

Just suggesting, I might be wrong as well 😅

@rajatjain-21
Copy link
Copy Markdown
Author

Hey Priyadarshanvijay, completely agree with what you pointed out here. Pure functions are indeed the essence of FP. Pushed another commit with the changes

@Priyadarshanvijay
Copy link
Copy Markdown

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