Pampy.js实现可读性极强的JavaScript的模式匹配代码

代码语言:nodejs

所属分类:其他

代码描述:Pampy.js实现可读性极强的JavaScript的模式匹配代码,可以匹配单个字符串、数组元素、对象元素等,安装:npm install pampy

代码标签: Pampy.js 可读性 JavaScrip 模式 匹配 代码

下面为部分代码预览,完整代码请点击下载或在bfwstudio webide中打开

let {match,REST,matchPairs,TAIL,_} = require("pampy");
let x=[1,2,3];
console.log(match(x,
    3,                "this matches the number 3",

    Number,           "matches any JavaScript number",

    [String, Number], (a, b) => "a typed Array [a, b] that you can use in a function",

    [1, 2, _],        "any Array of 3 elements that begins with [1, 2]",

    {x: _},           "any Object with a key 'x' and any value associated",

    _,                "anything else"
));



function lisp(exp) {
    return match(exp,
        Function,           (x) => x,
        [Function, REST],   (f, rest) => f.apply(null, rest.map(lisp)),
        Array,              (l) => l.map(lisp),
        _,                  (x) => x
    );
}
let plus = (a, b) => a + b;
let minus = (a, b) => a - b;
let reduce = (f, l) => l.reduce(f);

cons.........完整代码请登录后点击上方下载按钮下载查看

网友评论0