DEV Community

Discussion on: Currying in JavaScript

Collapse
 
functional_js profile image
Functional Javascript

I make heavy use of currying with functional pipelines.

Here's an example of comparing a function pipeline with method chaining from a recent tweet.

Alt Text

src

twitter.com/Reactivizer/status/127...

the filterNotStartsWith and replaceByRegex funcs are curried (they are funcs that return funcs)

Here are their implementations....

/**
@func
from the supplied arr,
- remove the elems that don't start with the supplied str

@param {string} chunk
@return {(a: string[]) => string[]}
*/
export const filterStartsWith = chunk => a => fil(s => s.startsWith(chunk), a);


/**
@func
replace a substring with another substring in a haystack of text

@param {RegExp} n needleRegex
@param {string} r replacement
@return {(h: string) => string} - haystack
*/
export const replaceByRegex = (n, r) => h => h.replace(n, r);

Notice that if a func takes exactly one arg, I don't have to curry it in order to use it in a functional pipeline.

Finally, the functional pipeline can be executed like this...

functionalPipeline(`
pwd
git status
git stash --include-untracked
git pull
git stash pop
`);