emmanueltouzery / prelude-ts

Functional programming, immutable collections and FP constructs for typescript and javascript
ISC License
377 stars 21 forks source link

Vector.select(fn: (length: number) => Option<number>): Option<T> #38

Closed aleksei-berezkin closed 4 years ago

aleksei-berezkin commented 4 years ago

In other words, get item given a function which calculates index given current vector length. This adds some sugar for my particular task: getting random item which is now like

const items = vector.map(...)....;
if (items.isEmpty()) {
    return undefined;
}
return items.get(getRandom(0, items.length)).getOrThrow();

It'll be also useful for getting median and other quantiles.

Perhaps it worth allowing selecting multiple items like Numpy-style, so signature will be like

Vector.select(fn: (length: number) => Vector<number>): Vector<T>

Or create both versions using overload. What are your thoughts?

emmanueltouzery commented 4 years ago

Hi, thank you for another suggestion! Hmm I don't know. Is that function common in other libraries/frameworks? I'd like to keep prelude 'clean', to a degree. So, batteries included, but not unwieldy, that you have trouble making sure whether a certain feature is available or not, because there are so many methods (thin line to walk, granted..).

This use-case reminds me of 'shuffle'. But it's true that shuffle has some overhead if you are interested in only a few elements and the list is really large. If that your case? Otherwise you can do .shuffle().head() or .shuffle().take(n).

Depending on how common this use-case is (and you may still convince me that it's a common case!), an alternative could also be to leverage 'transform', which allows you to keep the chaining style, without adding members in prelude, so:

const L = {
 select: <T> (l: Seq<T>) => ...
}

list.transform(L.select)

What do you think?

aleksei-berezkin commented 4 years ago

No, never encountered anything like that in any other lib (and somewhat missed that). Transform seems viable alternative, thanks. Closing the issue.