JSFiddle - React, Tailwind, and code Playground

by gianlucaguarini

JavaScript

/**
 * Function to curry any javascript method
 * @param   {Function}  fn - the target function we want to curry
 * @param   {...[arguments]} acc - initial arguments
 * @returns {Function|*} it will return a function until the target function 
 *                       will receive all its arguments
 */
function curry(fn, ...acc) {
  return (...args) => {
    args = [...acc, ...args]
    
    return args.length < fn.length ? 
       curry(fn, ...args) : 
       fn(...args)
  }
}

const add = (a, b) => a + b
const fetcher = (baseurl, path) => fetch(`${baseurl}/${path}`)

const add2 = curry(add, 2)
const add3 = curry(add, 3)
const fetchHttpbin = curry(fetcher)('https://httpbin.org')

console.log(add2(2))
console.log(add3(2))
fetchHttpbin('get').then(console.log)