One of the key challenges was to condense an array of numbers (with consecutive duplicates) by combining neighboring duplicates:
const sumClones = (numbers) => {
if (Array.isArray(numbers)) {
return numbers.reduce((acc, elem, i, arr) => {
if (elem !== arr[i - 1]) acc.push(elem);
else acc[acc.length - 1] += elem;
return acc;
}, []);
}
};
sumClones([1,1,2,1,1,1,1,2,1,1,1]) => [2,2,4,2,3]
Now, I am working on a function called reduceClones that recursively applies sumClones in order to eliminate any consecutive duplicates from the final output.
const reduceClones = (numbers) => {
let result = sumClones(numbers);
while (result[0] === result[1]) {
result = sumClones(result);
}
return result;
};
reduceClones([1,1,2,1,1,1,1,2,1,1,1]) => [8,2,3]
Are there more efficient ways to achieve this task?