data-point icon indicating copy to clipboard operation
data-point copied to clipboard

reducer helper: fromValue and fromAccumulator

Open acatl opened this issue 6 years ago • 3 comments
trafficstars

Problem description:

More than often we find ourselves writing reducer functions that only need either the input or the accumulator parameters. The result is functions such as:

// no need for the accumulator
function doSomethingWithValue(input, acc) {
  // stuff only with the input
 return input 
}

// no need for the input
function doSomethingWithAccumulator(input, acc) {
  // stuff only with the accumulator
 return acc.locals.foo 
}

Very often this caught by PRs and asked the devs to refactor methods to only accept the right param, or we end up ignoring the function param signature and just let it be.

but testing becomes annoying and we end up having a method signature that is not the right one for the purpose of the function.

Suggested solution:

export from datapoint object 2 function:

function fromValue(callback) { 
  return function getValueReducer (input, acc) {
    return callback(input)
  }
}

function fromAccumulator(callback) { 
  return function getValueReducer (input, acc) {
    return callback(acc)
  }
}

These methods would allow the previous methods to be written as:

// no need for the accumulator
function doSomethingWithValue(input) {
  // stuff only with the input
 return input 
}

// no need for the input
function doSomethingWithAccumulator(acc) {
  // stuff only with the accumulator
 return acc.locals.foo 
}

const doSomethingWithValueReducer = DataPoint.fromValue(doSomethingWithValue)
const doSomethingWithAccumulatorReducer = DataPoint.fromAccumulator(doSomethingWithAccumulator)

On this case, the main methods only are expecting the right parameters which will make unit testing easier, and the augmented functions can have the name Reducer as part of their name to be more expressive of what they do.

acatl avatar Jan 27 '19 15:01 acatl

any ideas? is this bad idea? maybe the name of the methods is not the best? can we improve?

acatl avatar Jan 27 '19 15:01 acatl

but testing becomes annoying and we end up having a method signature that is not the right one for the purpose of the function.

I'm not sure that I understand what you mean, since all reducer functions have the same signature, whether or not the function uses every argument.

What do you think about calling reducer functions with the accumulator set as this?

raingerber avatar Jan 27 '19 18:01 raingerber

mainly ive seen many functions created that manipulate data that if created as a function with only the arguments needed they would be more reusable and have less coupling with datapoint’s reducer api.

acatl avatar Jan 27 '19 22:01 acatl