UNPKG

@thi.ng/pointfree

Version:

Pointfree functional composition / Forth style stack execution engine

38 lines (37 loc) 729 B
import { $ } from "./safe.js"; import { $stackFn } from "./word.js"; const defLoop = (test, body) => { const _test = $stackFn(test); const _body = $stackFn(body); return (ctx) => { while (true) { ctx = _test(ctx); $(ctx[0], 1); if (!ctx[0].pop()) { return ctx; } ctx = _body(ctx); } }; }; const loopq = (ctx) => { const stack = ctx[0]; $(stack, 2); const body = stack.pop(); return defLoop(stack.pop(), body)(ctx); }; const dotimes = (ctx) => { let stack = ctx[0]; $(stack, 2); const w = $stackFn(stack.pop()); for (let i = 0, n = stack.pop(); i < n; i++) { ctx[0].push(i); ctx = w(ctx); } return ctx; }; export { defLoop, dotimes, loopq };