ViacomInc / data-point

JavaScript Utility for collecting, processing and transforming data
Apache License 2.0
67 stars 34 forks source link

reducer helper: fromValue and fromAccumulator #337

Open acatl opened 5 years ago

acatl commented 5 years ago

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 commented 5 years ago

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

raingerber commented 5 years ago

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?

acatl commented 5 years ago

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.