def

node v10.24.1
version: master
endpointsharetweet
const fdef = require('fdef') const def = fdef('myNamespace')
def is a function that receives a template string defining the name and the pattern to match and return a function that receives a function that will be invoked when pattern is matched. Bellow whe define a function x, named funcName, that for every string received returns the string itself
const x = def `funcName ${String}` (R.identity)
And for every time you pass it 42 it will return 'The anwser!'
def `funcName ${42}` (R.always('The anwser!'))
And finally, for every two numbers, their sum
def `funcName ${Number} ${Number}` (R.add)
You can see the results
console.log(x('mehh')) console.log(x(42)) x(1, 2)
Now, lets define something more usefull: The fibonacci function.
const fib = def `fib ${0}` (R.always(1)) def `fib ${1}` (R.always(1)) def `fib ${Number}` (n => fib (n - 1) + fib (n - 2)) console.log('fib 1 = ' + fib (1)) console.log('fib 6 = ' + fib (6)) fib(10)
If you call fib within something unexpected (e.g a string) it will throw a TypeError:
console.log('fib "a" = ' + fib ("a"))
Loading…

no comments

    sign in to comment