Currying is a core concept of functional programming and a useful tool for any developer's toolbelt.
Example 1:
let f = a => b => c => a+b+c;let result = f(1)(2)(3);console.log(result); // 6
Example 2:
JS Bin OneTwoThree
let one = document.getElementById('one');let tow = document.getElementById('two');let three = document.getElementById('three');let f = a => b => c => a.addEventListener(b, (event)=>{ event.target.style.background = c;});f(one)('click')('red');
Example 3:
let one = document.getElementById('one');let tow = document.getElementById('two');let three = document.getElementById('three');let f = a => b => c => a.addEventListener(b, (event)=>{ event.target.style.background = c;});let oneClickEvent = f(one);let twoClickEvent = f(two);oneClickEvent('mouseover')('red');twoClickEvent('mouseout')('blue');
Example 4: include ramda library:
let one = document.getElementById('one');let tow = document.getElementById('two');let three = document.getElementById('three');let f = R.curry((a,b,c) =>{ a.addEventListener(b, (event)=>{ event.target.style.background = c; });});// with placeholder from Ramdaconst clickGreen = f(R.__, 'click', 'green');clickGreen(one);
Example 5: multi placeholders:
let one = document.getElementById('one');let tow = document.getElementById('two');let three = document.getElementById('three');let f = R.curry((a,b,c) =>{ a.addEventListener(b, (event)=>{ event.target.style.background = c; });});// with placeholder from Ramdaconst clickColor = f(R.__, 'click', R.__);clickColor(one, 'yellow');clickColor(two, 'grey');clickColor(three, 'pink');