FP Learning

by Rafa Ola

JavaScript

someFunction = (a, b, c, ...others) => {
    console.log(a, b, c, others)
};
someFunction(1,2,3,4,5,6,7);

let double = (x) => x * 2
let sum = (x, y) => x + y
let doubleAndSum = (...numbers) => numbers
    .map(double)
    .reduce(sum, 0);

doubleAndSum(1,2,3);
/****
Since Babel wrote an old-school function for us, it can access the arguments object! arguments has indices and a .length property, which is all we need to create a perfect clone of it.

This is why we can use Array methods like map, filter, reduce on rest parameters, because it creates an Array clone of argument
*/
someFunction = function someFunction() {
    var _len = arguments.length;
    // create an array same length
    // as the arguments object
    var args = Array(_len);
    var i = 0;
    // iterate through arguments
    for (i; i < _len; i++) {
        // assign them to
        // the new array
        args[i] = arguments[i];
    }
    // and return it
    return args;
};
/***
Pipe
The concept of pipe is simple — it combines n functions. It’s a pipe flowing left-to-right, calling each function with the output of the last one.
*/

getName = (person) => person.name;
getName({ name: 'Buckethead' });
// 'Buckethead'

name = getName({ name: 'Buckethead' })
uppercase(name)
// 'BUCKETHEAD'
uppercase(getName({ name: 'Buckethead' }));

get6Characters = (string) => string.substring(0, 6)
get6Characters('Buckethead')
// 'Bucket'
get6Characters(uppercase(getName({ name: 'Buckethead' })));
// 'BUCKET'
reverse = (string) => string
  .split('')
  .reverse()
  .join('')
reverse('Buckethead');
// 'daehtekcuB'
reverse(get6Characters(uppercase(getName({ name: 'Buckethead' }))));
// 'TEKCUB'
/***
Pipe to the rescue!
*/
pipe(
  getName,
  uppercase,
  get6Characters,
  reverse 
)({ name: 'Buckethead' })
// 'TEKCUB'

//pipe above, you’d do the opposite.
compose(
  reverse,
  get6Characters,
  uppercase,
  getName,
)({ name: 'Buckethead' })