-
-
Notifications
You must be signed in to change notification settings - Fork 5.5k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Shorthand for piping a value through a bunch of functions #2809
Comments
Somebody implemented this as a babel macro: |
@tfga You can easily implement this yourself and then add it to Underscore if you want: var pipe = _.restArguments(function(input, functions) {
return _.compose.apply(null, functions.reverse())(input);
});
_.mixin({pipe: pipe});
_.pipe(a, f1, f2, f3); Or with ES6 syntax: function pipe(input, ...functions) {
functions.reverse();
return _.compose(...functions)(input);
}
_.mixin({pipe});
_.pipe(a, f1, f2, f3); |
@jgonggrijp But then I'd have to duplicate this code in every project. To prevent that, isn't it the point of libraries like underscore? |
No, you don't have to copy it in every project. You can make your own NPM package that imports Underscore, adds your desired functions to it with |
@jgonggrijp Ok. Thanks for the replies. |
@tfga I guess I should have started by mentioning why I think this doesn't belong in Underscore. Sorry for not doing that. I see the added value of _.chain(a).pipe(f1, f2, f3).pipe(f4, f5).value(); But the problem is, there is an infinite space of functions that are not in Underscore but that would have an added value. We can't add all of them. In fact, we have to be conservative because Underscore is trying not to grow fatter (see #2060). I'm not ruling out that new functions would be added (in fact that's not up to me to decide), but given that Another thing I failed to mention is that there is a very similar function available from Underscore-Contrib: |
@jgonggrijp No worries. Thank you for taking the time to explain this. I appreciate it. |
Reopening this, because I'm seriously considering to replace
Ditching FYI @tfga. |
Let's say you want to pipe some value
a
through 3 functionsf1
,f2
,f3
, in that order. How would you do it?Well, you can do it the "normal" way (pure JS):
Or you can use
_.compose()
:But what I'd really like to write is:
Both JS's function composition syntax and
_.compose()
make me write the function list in the reverse order. Clojure has threading macros; in Elm, you could write this using the reverse apply operator:This
_.pipe()
function I'm suggesting would be a way of doing something similar in JS.The text was updated successfully, but these errors were encountered: