Skip to content

How to extend function in JS? [closed]

I have the following function:

private getSquareBoundRectangleElements(elements: HTMLLIElement[] | SVGElement[]): number[] {
    let squares: number[] = [];

    elements.forEach((element) => {
        const coords = getCoords(element);
        const square = coords.width * coords.height;
        squares.push(square);
    });

    return squares;
}

I need to leave this function but extend by case, when requires to return min square and element of this square. How to do that with minimal changes of function.

Answer

I do not know exactly what you mean by extending the function. But consider these three approaches for “extending” a function:

  1. Just use your function in a new function. This requires writing your functions in a pure way to allow for reuse like this. You might want to consider extracting a part of this function to a third function and using that in both this and your new functions.
  2. Function currying. If you wanna keep some data in a closure you can do so by returning your function from another function that keeps something in a closure.
  3. You might also wanna consider the possibility of adding an object as the last parameter of your function to allow for some configurations into the function’s behaviour and then simply using conditional logic to perform certain extra actions.