The Currying

What is currying

Currying is the technique of translating the evaluation of a function that takes multiple arguments into evaluating a sequence of functions, each with a single argument. -- Wikipedia
It mean this:

1
2
3
4
5
let add = (x) => (y) => x + y
let addOne = add(1)
let addTwo = add(2)
addOne(11) // 12
addTwo(11) // 13

In order to define functions more easily, we need the loadsh, it will help us to currying the function.

make some using thing

1
2
3
4
5
6
7
8
9
10
11
12
13
var _ = require("loadsh").curry

var match = _((regex, str) => str.match(regex))
var replace = _((regex, replacement, str) => str.replace(regex, replacement))
var filter = _((f, array) => array.filter(f))
match(/\s+/g, "test Message") // [' ']
match(/\s+/g)("test Message") // [' ']

var hasSpace = match(/\s+/g)
hasSpace("testMessage") // null
filter(hasSpace, ["testMessage1", "test Message2", "test Message 3"]) // ['test Message2', 'test Message 3']
var noA = replace(/[Aa]+/g, "*")
noA("aaaabbbAAAc") // '*bbb*c'

some practice

Use curry in rambda.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
// support functions
let curry = require("rambda").curry
let compose = require("rambda").compose
let add = curry((a, b) => a + b)
let match = curry((regex, str) => str.match(regex))
let replace = curry((regex, replacement, str) =>
str.replace(regex, replacement)
)
let filter = curry((f, arr) => arr.filter(f))
let map = curry((f, arr) => arr.map(f))
let split = curry((symbol, str) => str.split(symbol))
let reduce = curry((f, arr, x) => x.reduce(f, arr))
let join = curry((symbol, arr) => arr.join(symbol))
let toUppercase = curry((str) => str.toUpperCase())
let toLowercase = curry((str) => str.toLowerCase())

// 1. remove all the arguments
// var words = str => split(' ', str);

var words = split(" ")
words("hello world !") // ['hello', 'world', '!']

// 2. create a new words function with map to enable mainpulation of string array
var theWords = map(words)
theWords(["first message", "seconde message"]) // [['first', 'message'], ['second', 'message']]

// 3. remove all the arguments
// var filterQString = xs => filter(x => match(/q/i, x), xs);
var filterAString = filter(match(/a/i))
filterAString(["quick", "queue", "apple", "two"]) // ['apple']

// 4. Refactor max with the help function _max to make it a curry function
var _max = (a, b) => (a >= b ? a : b)
// var max = xs => reduce((account, x) => _max(account, x), -Infinity, xs);
var max = reduce(_max, -Infinity)
max([1, 2, 3, 4]) // 4

Currying add

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
function add(x) {
let sum = x

function f(y) {
sum += y
return f
}

f.end = function () {
return sum
}

return f
}

console.log(add(0)(1)(2).end())