Some functional utilities

artydev - Nov 21 '23 - - Dev Community

Here are some utilities I use, when I don't want to rely on any external libraries :


const curry = function (fn) {
  const curried = (...args) => {
    if (args.length >= fn.length) {
      return fn.apply({}, args)
    }
    else {
      return (...vargs) => curried.apply({}, args.concat(vargs))
    }
  }
  return curried
}

const compose = 
    (...fns) => arg => fns.reduceRight((acc, f) => f(acc), arg);

const pipe = 
    (...fns) => arg => fns.reduce((acc, f) => f(acc), arg);

const asyncpipe = 
    (...fns) => arg => fns.reduce((p, fn) => p.then(fn), Promise.resolve(arg));

const pickprop = (prop) => (obj) => obj[prop] ?? null; 

const map = (f) => (arr) => arr.map(f);

const filter = (f) => (arr) => arr.filter(f);

Enter fullscreen mode Exit fullscreen mode

The function passed to the reduce method is called a reducer.

A reducer is a function which has two arguments, the first of type A, the second of type B and the returned type is of type A.

As long as any function has this signature, it can be passed to a reduce method.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .