prelude-ls icon indicating copy to clipboard operation
prelude-ls copied to clipboard

Add Func.tap

Open cprecioso opened this issue 8 years ago • 1 comments

Description

tap applies a function only for its side effects and discards the result, returning the given argument.

Reasoning

tap would be really useful for use in big chains of pipes, compositions and partial application, without the syntactic overhead of a cascade in an explicit function.

Implementation

tap = (f, x) --> f x; return x

Example 1

In this example, we convert a date object with a month in human form (one-indexed) for use in moment.js, which requires zero-indexed months.

Before:

get-date # e.g. {year: 2016, month: 7, day: 31}
|> ->
  it.month--
  return it # We have to return the given argument to continue chaining
|> moment

Now:

get-date
|> tap (.month--) # :D
|> moment

Example 2

Here we use a console.log for debug purposes.

get-whatever-data!
|> process-that-data
|> tap (.1) >> console~log
|> keep-processing-that-data

cprecioso avatar Jul 31 '16 15:07 cprecioso

The name comes from a Q Promise method that does the same but for promises (and is incredibly useful), though I'm not sure whether that's the best name for it.

cprecioso avatar Jul 31 '16 15:07 cprecioso