Javascript. Currying

Descubre en qué consiste la técnica “currying” y cómo podemos aplicarla más fácilmente gracias a ES6

Image for post
Image for post
Photo by Jason Leung on Unsplash

¿En qué consiste el currying?

const multiply = (a, b) => a * b;
multiply(2, 3)
const curriedMultiply = a => b => a * b;
const curriedMultiply = function(a) {
return function(b) {
return a * b;
}
}
curriedMultiply(2)(3)
const multiplyBy2 = curriedMultiply(2);// latermultiplyBy2(3);

Miniaplicaciones

function log(level, date, message) {
console.log(`[${level}]: ${date} - ${message}`);
}
log('critical', new Date(), 'Some message');
function curriedLog = level => date => message => {
console.log(`[${level}]: ${date} - ${message}`);
}
const logCritical = curriedLog('critical');
logCritical(new Date())('Some message');

Composición de funciones

const sum2 = x => x + 2;
const triplicate = x => x * 3;
const sum5 = x => x + 5;
sum5(sum2(triplicate(4))); // 19
const compose = (...fns) => args => fns.reduceRight((arg, fn) => fn(arg), args);
compose(sum5, sum2, triplicate)(4);
function log(label, value) {
console.log(`[${label}]: ${value}`);
return value;
}
const sum2 = x => x + 2;const triplicate = x => x * 3;
compose(sum2, log, triplicate)(4);
const curriedLog = label => value => {
console.log(`[${label}]: ${value}`);
return value;
}
const sum2 = x => x + 2;const triplicate = x => x * 3;
compose(sum2, curriedLog('Invoked before sum'), triplicate)(4);
value => {
console.log(`[${label}]: ${value}`);
return value;
}

Conclusiones

const curriedMultiply = a => b => a * b;
const duplicate = curriedMultiply(2)

¿Quieres recibir más artículos como este?

Written by

Entre paseo y paseo con Simba desarrollo en Symfony y React

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store