Last active
December 19, 2018 14:27
-
-
Save gabejohnson/4458535316647c0820b71fc76fdb3790 to your computer and use it in GitHub Desktop.
You want mixfix? You got it!
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function _(x) { | |
if (x instanceof _) return new _(x._); | |
if (!(this instanceof _)) return new _(x); | |
this._ = x; | |
} | |
_.mixfix = function mixfix(pattern, f) { | |
const [name, ...names] = pattern.split('_'); | |
let startIndex = name === '' ? 1 : 0; | |
let endIndex = pattern[pattern.length-1] === '_' ? -1 : void 0; | |
_[pattern.slice(startIndex, endIndex)] = f; | |
if (name === '') { | |
names.length > 1 | |
? Object.defineProperty(_.prototype, names[0], { | |
enumerable: true, | |
get() { | |
return x => go(names.slice(1), new _(f (this._) (x))); | |
} | |
}) | |
: Object.defineProperty(_.prototype, names[0], { | |
enumerable: true, | |
get() { | |
return new _(f(this._)); | |
} | |
}); | |
} else { | |
_[name] = x => go(names, new _(f(x))); | |
} | |
return _; | |
function go([name, ...names], parent) { | |
if (name !== '') Object.defineProperty(parent, name, { | |
get() { | |
return x => go(names, new _(this._(x))); | |
} | |
}); | |
return parent; | |
} | |
}; | |
_._extend = function extend(lib) { | |
Object.keys(lib).forEach(k => { | |
if(lib[k].length < 1 || k[k.length-1] === '_') { | |
_[k] = lib[k]; | |
} else if (lib[k].length === 1) { | |
_.mixfix(`_${k}`, lib[k]); | |
} else { | |
_.mixfix(`_${k}_`, lib[k]); | |
} | |
}); | |
return _; | |
}; | |
_.mixfix('if_then_else', t => c => a => t ? c() : a()); | |
_.if_then_else (true) (() => 'and...') (() => 'no, really. what\'s your point?'); // "and..." | |
_.if(true) | |
.then(() => 'you\'re crazy!') | |
.else(() => 'like a fox')._; | |
_.mixfix('_and_', x => y => x && y); | |
_.and (true) (false); // false | |
_(true).and(true)._ // true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment