Enhancing our toolbox

artydev - Nov 23 '23 - - Dev Community

There is a little problems with some of our functions.


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

Given :

let pets = [
  {
    petname : "Bill",
    breed : "poodle",
    weight: 12,
    owner : {
      ownername : "Paul",
      contribution : {
        amount : 32,
        payed : false
      },
      address : {
        city :  "Paris"
      }
    }
  },
  {
    petname : "Maya",
    race : "pointer",
    weight: 27,
    owner : {
      ownername : "Henri",
      contribution :  {
        amount : 12,
        payed : true
      },
      address : {
         city :  "London"
      }
    }
  },
  {
    petname : "Ooper",
    race : "setter",
    weight: 20,
    owner : {
      ownername : "Nicolas",
      contribution :  {
        amount : 12,
        payed : true
      },
      address : {
         city :  "London"
      }
    }
  }
]
Enter fullscreen mode Exit fullscreen mode

We can only pass one argument at a time. So we can not write :


const petNameOne = pickprop("petname", pets[0])

Enter fullscreen mode Exit fullscreen mode

That's because pickprop is not really curried

So, let's "spice" them :



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((f, arr) => arr.map(f));

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

Enter fullscreen mode Exit fullscreen mode

We can now call our function pickprop using two syntax :


let petNameOne = pickprop("petname", pets[0])

console.log(petNameOne)

petNameOne = pickprop("petname")(pets[0])

console.log(petNameOne)


Enter fullscreen mode Exit fullscreen mode

Great :-)

You can play with the demo here : Demo

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player