infinnie / infinnie.github.io

https://infinnie.github.io/
Apache License 2.0
0 stars 1 forks source link

(Simple) pattern matching utility #8

Open infinnie opened 7 years ago

infinnie commented 7 years ago
// definition
var Thing = { run: function () {
    "use strict";
    return (function (args) {
        return function (f) {
            return f.apply(null, args);
        };
    })(Array.prototype.slice.call(arguments, 0));
}, match: function (cond, y, n) {
    if (cond)
        return y && y();
    return n && n();
}, matchRegExp: function (re, str, y, n) {
    if (re.test(str)) {
        return (function (ret) {
            str.replace(re, function () {
                ret = y && y.apply(null, arguments);
            });
            return ret;
        })();
    }
    return n && n(str);
}, matchRegExpMulti: function (re, str, y, n) {
    if (re.test(str)) {
        return (function (ret) {
            str.replace(re, function () {
                ret.push(y && y.apply(null, arguments));
            });
            return ret;
        })([]);
    }
    return n && n(str);
} };

// get rid of local variable scopes
Thing.run(1, 2, 3)(function (a, b, c) {
    return Thing.run(a + b)(function (d) {
        return c + d;
    });
}); // 6

// matching regular expressions
Thing.matchRegExpMulti(/(p)/g, "apple", function (x, y, z, t) {
    // each logged twice
    console.log(x);
    console.log(y);
    console.log(z);
    console.log(t);
    return 1;
}); // returns [1, 1]