DEV Community

artydev
artydev

Posted on

Completing our toolbox with the mapper function

In the previous post we discover a new utility :


function pick (path) {
  let pickprops =  map((prop) => pickprop(prop), path.split("."));
  return pipe(...pickprops);
}

const mapper = compose(map, pick);

Enter fullscreen mode Exit fullscreen mode

Here is a use case :


let citymapper = mapper("owner.address.city")

cities = citymapper(pets)

console.log(cities);

Enter fullscreen mode Exit fullscreen mode

Here is our toolbox now :



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 = curry((prop, obj) => obj[prop] ?? null); 

const map = curry((fn, arr) => arr.map(fn));

const filter = curry((fn, arr) => arr.filter(fn));

function pick (path) {
  let pickprops =  map((prop) => pickprop(prop), path.split("."));
  return pipe(...pickprops);
}

const mapper = compose(map, pick);

Enter fullscreen mode Exit fullscreen mode

You can play with a demo here Demo

Top comments (0)