aksoco
aksoco

Reputation: 191

Passing parameters to reduce function

I have read this article, but I don't seem to understand JavaScript's reduce syntax correctly. How can I pass additional parameters to custom reducer function?

Calling reducer function.

data = Object.values(data.reduce(reducer, {}));

Reducer function example.

const reducer = (acc, cur) => {
if (somethingIsTrue) {
return acc;
}
};

Right now it is working like it should, but let's say that I'm calling reducer function and I want to pass simple variable that contains "Hello World" in away that function doesn't see it as an argument. How can I achieve this?

Upvotes: 0

Views: 3568

Answers (1)

Naphat Amundsen
Naphat Amundsen

Reputation: 1623

You can do function composition to "build up" something called an higher order function. Basically the idea is to create a function that returns a "child function", which will have access to the parent function's variables.

// Parent function (getReducer)
function getReducer(stringToAppend) {
    
    // Child function (reducer)
    function reducer(acc, curr) {
        // Child function has access to parent's variables (in this case stringToAppend)
        acc[curr] = stringToAppend + curr
        return acc
    }
    
    return reducer
}

const data = [0,1,2,3,4,5,6,7,8,9]
const result = data.reduce(getReducer("Hello World "), {})
console.log('result :>> ', result);

In console:

result :>>  {
  '0': 'Hello World 0',
  '1': 'Hello World 1',
  '2': 'Hello World 2',
  '3': 'Hello World 3',
  '4': 'Hello World 4',
  '5': 'Hello World 5',
  '6': 'Hello World 6',
  '7': 'Hello World 7',
  '8': 'Hello World 8',
  '9': 'Hello World 9'
}

I used the function syntax as I found it more verbose and explicit for explaining this. You could of course utilize arrow functions. Using arrow syntax the function could look as simple as:

function getReducer (stringToAppend) {
    return (acc, curr) => {
        acc[curr] = stringToAppend + curr
        return acc
    }
}

Upvotes: 5

Related Questions