DEV Community

Discussion on: How to Decimate an Array.

Collapse
 
tiagojpdias profile image
Tiago Dias • Edited

I would suggest 4 improvements (3 minor and 1 critical)

Critical bug

1) Provide the fidelity parameter as argument to the function, otherwise will only have a value other than 2 in the first step of the recursion;

Minor suggestions

1) Reduce LOC by decreasing by one in the if statement;
2) Remove obsolete else branch;
3) No need to reassign the variable, just return the result right away;

function decimateArray(arr, passes = 1, fidelity = 2) {
    const filteredArray = arr.filter((_, index) => index % fidelity === 0);

    if (--passes) {
        return decimateArray(filteredArray, passes, fidelity);
    }

    return filteredArray;
}

const parameters = [
    Array.from({ length: 100 }, (_, i) => i + 1),
    2,
    4,
];

const decimatedArray = decimateArray(...parameters);

console.log({ decimatedArray }); // { decimatedArray: [ 1, 17, 33, 49, 65, 81, 97 ] }

BTW sorry if I sound picky...

Collapse
 
adam_cyclones profile image
Adam Crockett 🌀

Array from with a function callback isn't as fast as mapping an empty array from an Array constructor. 🤣

It's not the point that it's buggy, it's important that you can take my crappy code and make something better, success. Still the failure to pass args recursively is something il fix.