Today on 'Cooking with Metho', we'll be making a nice curry.
Ingredients
- 1 x
metho
- available in your local NPM - 1 x
Function
prototype - 1 x
curry
function (generic is fine) - 1 x function of your choosing
- A pinch of JS knowledge
Method
- Add the
metho
to the bowl:
import * as Metho from "metho"
- To make the 'curried' sauce, combine the
curry
function and theFunction
prototype, using Metho to bind them together:
const target = Function.prototype
function curry(func) {
return function curried(...args) {
if (args.length >= func.length) {
return func.apply(this, args)
} else {
return function(...args2) {
return curried.apply(this, args.concat(args2))
}
}
}
}
const curried = Metho.add(
target,
function() {
return curry(this)
}
)
- Add sauce to your chosen function for a delicious combination!
function myAdd(a, b) {
return a + b
}
// without 'curried' sauce - kinda bland
console.log(myAdd(2, 3)) // 5
// with sauce - tasty!
const add2 = myAdd[curried](2)
console.log(add2(3)) // 5
// versatile! map it with an array
console.log([2, 4, 6].map(myAdd[curried](11))) // [13, 15, 17]
Alternative Method
The main ingredients are also available pre-mixed as metho-function
- also available in all good NPMs. Simply import the curried
sauce straight from the packet, and continue as before:
import { curried } from 'metho-function'
...
That's all!
If you like this recipe or have any ideas on how to improve it, please drop me a line here or at the Metho cookery school.
Top comments (2)
You strike again with another feature that exists in my library! Are our minds connected? :D Once again, your implementation is better than mine, but who knows, maybe the scales will topple soon... ;)
I have many more ideas for improvements to Metho, and more 'prototype extension' libraries to take advantage of it. As with everything though, it's just a question of finding the time π