bjoerge / debounce-promise

Create a debounced version of a promise returning function
MIT License
241 stars 27 forks source link

Clarify accumulate: true example #10

Closed IlyaSemenov closed 6 years ago

IlyaSemenov commented 6 years ago

The existing squareValues example is misleading in the sense that it makes a reader believe that values is (naturally) an array of passed values. However, values in the example is actually an array of arguments arrays:

function squareValues (values) {
  console.log(values) // [ [ 1 ], [ 2 ], [ 3 ], [ 4 ] ]
  return Promise.all(values.map(val => val * val))
}

Coincidentally, multiplying arrays [ 2 ] * [ 2 ] gives 4 in Javascript, which obscures the fact that values consists of arrays rather than values. But this conversion is not going to take place in most other circumstances. For instance, if you return val + val instead of val * val in your example, the debounced promise will resolve to 11 22 33 44 instead of 1 2 4 8.

The PR makes it more obvious to infer the actual API from the example:

function squareValues (argTuples) {
  return Promise.all(argTuples.map(args => args[0] * args[0]))
}

Another options would be to use arguments destructuring:

function squareValues (argTuples) {
  return Promise.all(argTuples.map(({0: value}) => value * value))
}

but I think it's even harder to comprehend.

bjoerge commented 6 years ago

Ah, good catch! Agreed about the first example being clearer. Thanks!