Default Parameters with Generic JSX

node v8.17.0
version: 3.0.0
endpointsharetweet
With Generic JSX, the idea of default parameters actually becomes unified with that of curried parameters. Let's begin with writing a function that converts a string to an integer:
/* @jsx (curry(_=>eval(_))) */ var { curry, from } = require("generic-jsx"); // Pretty simple shim for parseInt, only we're using named parameters: function stringToInt({ string, base }) { return parseInt(string, base); } <stringToInt string = "55" base = { 10 } />()
We COULD HAVE just written "= 10" after base to set the default base, but we can actually use currying to achieve the same result:
// Now if we export this, it'll be as if we had set a default parameter. stringToInt = <stringToInt base = { 10 } />; <stringToInt string = "55" />();
Again, since Generic JSX currying can be done multiple times, the fact that we curried in base doesn't prevent us from overriding it later:
<stringToInt string = "55" base = { 12 } />();
Since we use named parameters, we don't fall into the classic map pitfall of accidentally applying the wrong base:
console.log(["1", "2", "3", "4", "5"].map(<stringToInt string = { from(0) }/>) + " vs. " + ["1", "2", "3", "4", "5"].map(parseInt));
Loading…

no comments

    sign in to comment