How To Prevent A Recursive Function From Re-initializing An Accumulating Variable?
This function is written in JavaScript but I think that the concept can be implemented with some other programming languages. function uniteUnique(arr) { let seenBefore = [];
Solution 1:
Another possibility would be to define seenBefore
as the empty array as a default second parameter, which is recursively passed to every call of the function:
functionuniteUnique(arr, seenBefore = []) {
for (const item of arr) {
if (typeof (item) == "object") {
uniteUnique(item, seenBefore);
}
elseif (!seenBefore.includes(item)) {
seenBefore.push(item);
}
}
return seenBefore;
}
uniteUnique(someArr);
Note that this accepts a single argument as an array, rather than multiple arguments.
Solution 2:
You can utilize a nested function, so that you don't need to reinitialize the accumulating array each time:
functionuniteUnique(arr) {
functioniterate(seenBefore, arr)
{
for (let item of arr) {
if (Array.isArray(item)) {
iterate(seenBefore, item);
}
elseif (!seenBefore.includes(item)) {
seenBefore.push(item);
}
}
}
let result = []; // the accumulating arrayiterate(result, arr);
return result ;
}
You don't actually need to use arguments
and spread operator here, because your function expects an array and you can simply pass an array.
You may also want to use Set
for seenBefore
, because Array.prototype.includes
scans through an array, which is ineffective.
Solution 3:
Just in case: if you can use the last ES2019 features and prefer simplicity, this can also be achieved with a one-liner:
const uniquesArray = [...newSet(nestedArray.flat(Infinity))];
Post a Comment for "How To Prevent A Recursive Function From Re-initializing An Accumulating Variable?"