@thi.ng/pointfree
Version:
Pointfree functional composition / Forth style stack execution engine
48 lines (47 loc) • 1.12 kB
JavaScript
import { illegalState } from "@thi.ng/errors/illegal-state";
import { $ } from "./safe.js";
import { nop } from "./stack.js";
import { $stackFn } from "./word.js";
const defCond = (_then, _else = nop) => (ctx) => {
$(ctx[0], 1);
return $stackFn(ctx[0].pop() ? _then : _else)(ctx);
};
const condq = (ctx) => {
const stack = ctx[0];
$(stack, 3);
const _else = stack.pop();
const _then = stack.pop();
return $stackFn(stack.pop() ? _then : _else)(ctx);
};
const whenq = (ctx) => {
const stack = ctx[0];
$(stack, 2);
const _then = stack.pop();
return stack.pop() ? $stackFn(_then)(ctx) : ctx;
};
const defCases = (cases) => (ctx) => {
$(ctx[0], 1);
const stack = ctx[0];
const tos = stack.pop();
const cas = cases[tos];
if (cas !== void 0) {
return $stackFn(cas)(ctx);
}
if (cases.default) {
stack.push(tos);
return $stackFn(cases.default)(ctx);
}
return illegalState(`no matching case for: ${tos}`);
};
const casesq = (ctx) => {
const stack = ctx[0];
$(stack, 2);
return defCases(stack.pop())(ctx);
};
export {
casesq,
condq,
defCases,
defCond,
whenq
};