November 29, 2017

ES6 Recursion

I’ve been working with ES6 for over a year now and can easily say the spread operator and destructuring are by far my most frequently used features.

Spread Operator

Allows the expansion of items inside an object or array - or if you’re working with functions,arguments. This is especially useful when you want to overwrite the value of a key in an object while still preserving the object’s original contents.

Destructuring

Allows the “extraction” of particular values from an iterable list. For arrays, this extraction is index-based, while attribute values from objects are extracted using the “key” they belong to.

Recursion using both

I coded a small recursive function that leverages both these features. It takes in a list of numbers and multiplier value, then returns the transformed list where each original value is multiplied by the mutliplier value argument.

function multiply(arr, multiplier, prev = []) {
    // Extract the first element from the number list.
    const [number, ...rest] = arr;

    // Base-case: if there are no numbers to extract, then return.
    if (!number) return [...prev, ...arr];

    // Otherwise, we pass the remaining of the array to multiply again, the multiplier, and the accumulated transformed list.
    return multiply(rest,  multiplier, [...prev, number*multiplier]);
}

© Micah Tigley 2020

Powered by Hugo & Kiss.