26
loading...
This website collects cookies to deliver better user experience
Before we go on, a quick remainder that the x => y
syntax is equivalent to function(x){ return y }
.
const clampedFunc = function(fun, min, max){
return (...args) => Math.max(min, Math.min(max, fun(...args)))
}
// Demonstration
squared1 = x => x*x
squared2 = clampedFunc(squared1, 25, 100)
squared1(3) // 9
squared1(6) // 36
squared1(12) // 144
squared2(3) // 25
squared2(6) // 36
squared2(12) // 100
const linear = function(m, n){
return (x) => m*x + n
}
// Demonstration
f1 = linear(1, 2)
f1(10) // 12
f1(20) // 22
f2 = linear(2, -5)
f2(7) // 9
f2(8) // 11
forEach
: Apply a function to each element of the list and ignore the return values, if any.map
: Apply a function to each element of the list and return a list of all returned values. In other languages it’s called apply.reduce
: Apply a function of two arguments to the two first elements. Then, apply it again to the result and the third element. Then, apply it to the result and the fourth element, etc. In short, accumulate the value of a function for all the elements. In other languages it’s called fold.some
: Return true if at least one element satisfies a condition. In other languages it’s called any.every
: Return true if all elements of the list satisfy a condition.filter
: Return a list only with the elements that satisfy the condition.nums = [ 1, 2, 3, 4, 5 ]
words = [ 'how', 'are', 'you' ]
nums.forEach(x => console.log("- " + x))
// returns nothing but prints nums as a bullet list
nums.map( x => x*3 )
// [ 3, 6, 9, 12, 15 ]
words.reduce( (x, y) => x + ' ' + y )
// 'how are you'
nums.some( x => x > 5 )
// false
words.every( x => x.length == 3 )
// true
nums.filter(x => x % 2 == 0)
// [ 2, 4 ]
// Function to concatenate other two functions (this is called composition)
const compose = function (f1, f2){
return (...args) => f2(f1(...args))
}
// Function to compose any number of functions (general composition)
const gCompose = function(fs){
return fs.reduce(compose)
}
// Function to generate custom formatter functions
const custom_fmt = function(text, variable){
return (value) => text.replace(variable, value)
}
// Convert USD to Euros
const usd2eur = function(x){
return x/1.2
}
// Fix the precision a number to 2
const fix2 = function(x){
return x.toFixed(2)
}
// Store the functions in the order we want to apply them
myComputation = [usd2eur, fix2, custom_fmt("Cost in EUR: x", "x")]
// Compose them into a single function
myComputationFunc = gCompose(myComputation)
// Apply the computation we just created to each element of our list and print the result
usdCosts = [2.50, 10.99, 3.3, 5.72]
usdCosts.map(myComputationFunc).forEach(x => console.log('-',x))
/* Console output
- Cost in EUR: 2.08
- Cost in EUR: 9.16
- Cost in EUR: 2.75
- Cost in EUR: 4.77
*/