marpple / FxTS

A functional programming library for TypeScript/JavaScript
https://fxts.dev
Apache License 2.0
881 stars 63 forks source link

Better documentation and parameter name for `reduce` #240

Closed Phryxia closed 8 months ago

Phryxia commented 8 months ago

Suggestion

⭐ Suggestion

Bad parameter name or generic name

In the jsdoc of reduce, variable name is really confusing since it's just a and b. It's different to simple binary operation (like add or mul). After I inspect type signature, it's getting worse because of (a: B, b: A) => B.

In tslib, they used following for Array.prototype.reduce .

reduce<U>(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: T[]) => U, initialValue: U): U;

In #MDN reference, they use following description.

Its return value becomes the value of the accumulator parameter on the next invocation of callbackFn.

For my suggestion, how about this? I think people use T often to express generic type for input. R means return, but if you have better ideas, please go with them.

reduce<T, R>(f: (acc: R, value: T) => R, seed: R, ...)

Requires more elaboration for docs of reduce

I think It's good to explain case of accumulator differ to value. I think it's pretty common in real life. Like adding following in the jsdoc of reduce.

// with accumulator
const data = [{ name: 'ppeeou', score: 25751 }, { name: 'shine1594': score: 74317 }, { name: 'jbl428', score: 366 }]
const scoreSum = reduce((acc, { score }) => acc + score, 0, data)

Also always thanks for great library, it helps me a lot.

💻 Use Cases

More developers can understand the powerful features of reduce.

ppeeou commented 8 months ago

For my suggestion, how about this? I think people use T often to express generic type for input. R means return, but if you have better ideas, please go with them.

I didn't know there was such a rule or convention in TypeScript. I like the method you suggested.

I think It's good to explain case of accumulator differ to value. I think it's pretty common in real life. Like adding following in the jsdoc of reduce.

Also, I think it would be a good idea to add the explanation you wrote above.

If it's okay with you, could you please create a PR??

Phryxia commented 8 months ago

I didn't know there was such a rule or convention in TypeScript.

Oh there is no such explicit rule! But as my experience, many types of other libraries or example code seem to use T for such purpose. (Maybe because it stands for Type) R was just my private opinion :p

I'll raise a PR soon so let's enhance them :)