Skip to content

Instantly share code, notes, and snippets.

@anna-oake
Created February 12, 2026 18:20
Show Gist options
  • Select an option

  • Save anna-oake/ea2f3e1098a8224452cbba1ce681d78e to your computer and use it in GitHub Desktop.

Select an option

Save anna-oake/ea2f3e1098a8224452cbba1ce681d78e to your computer and use it in GitHub Desktop.
const isOdd = (() => {
const U = (() => {
const S = Object.freeze({
tag: Symbol("tag"),
ok: Symbol("ok"),
val: Symbol("val"),
err: Symbol("err"),
run: Symbol("run"),
brand: Symbol("brand"),
cache: Symbol("cache"),
meta: Symbol("meta"),
});
const deepFreeze = (x, seen = new WeakSet()) => {
if (x === null || typeof x !== "object") return x;
if (seen.has(x)) return x;
seen.add(x);
for (const k of Object.getOwnPropertyNames(x)) deepFreeze(x[k], seen);
for (const k of Object.getOwnPropertySymbols(x)) deepFreeze(x[k], seen);
return Object.freeze(x);
};
const tag = (t, fields) => {
const o = { [S.tag]: t, ...fields };
Object.defineProperty(o, S.tag, { value: t, enumerable: false });
return deepFreeze(o);
};
const Brand = (name) => deepFreeze({ name, [S.brand]: Symbol(name) });
const Either = (() => {
const Right = (v) => tag("Right", { [S.ok]: true, [S.val]: v });
const Left = (e) => tag("Left", { [S.ok]: false, [S.err]: e });
const fold = (e, onL, onR) =>
e && e[S.tag] === "Right"
? onR(e[S.val])
: e && e[S.tag] === "Left"
? onL(e[S.err])
: onL(new TypeError("not-either"));
const map = (e, f) => fold(e, Left, (v) => Right(f(v)));
const chain = (e, f) => fold(e, Left, f);
return deepFreeze({ Right, Left, fold, map, chain });
})();
const pipe = (...fs) => (x) => fs.reduce((v, f) => f(v), x);
const trampoline = (thunk) => {
let t = thunk;
while (typeof t === "function") t = t();
return t;
};
const Bus = (() => {
const mk = () => {
const m = new Map();
const on = (k, f) => {
const xs = m.get(k) || [];
xs.push(f);
m.set(k, xs);
return () => {
const ys = m.get(k) || [];
m.set(k, ys.filter((g) => g !== f));
};
};
const emit = (k, v) => {
const xs = m.get(k) || [];
for (const f of xs) f(v);
};
return deepFreeze({ on, emit });
};
return deepFreeze({ mk });
})();
const DI = (() => {
const mk = () => {
const store = new Map();
const bind = (k, v) => (store.set(k, v), v);
const must = (k) => {
if (!store.has(k)) throw new Error("missing:" + String(k));
return store.get(k);
};
return deepFreeze({ bind, must });
};
return deepFreeze({ mk });
})();
const memo1 = (f) => {
const cache = new Map();
const keyOf = (x) => {
const t = typeof x;
if (x === null) return "null";
if (t === "object" || t === "function") {
try {
return "o:" + JSON.stringify(x);
} catch (_) {
return "o:" + Object.prototype.toString.call(x);
}
}
return t + ":" + String(x);
};
return (x) => {
const k = keyOf(x);
if (cache.has(k)) return cache.get(k);
const v = f(x);
cache.set(k, v);
return v;
};
};
const proxify = (x) =>
(x !== null && (typeof x === "object" || typeof x === "function"))
? new Proxy(x, {
get(t, p, r) {
return Reflect.get(t, p, r);
},
has(t, p) {
return Reflect.has(t, p);
},
ownKeys(t) {
return Reflect.ownKeys(t);
},
getOwnPropertyDescriptor(t, p) {
return Reflect.getOwnPropertyDescriptor(t, p);
},
})
: x;
return deepFreeze({ S, deepFreeze, tag, Brand, Either, pipe, trampoline, Bus, DI, memo1, proxify });
})();
const env = U.DI.mk();
const bus = U.Bus.mk();
const NormalizeBrand = U.Brand("NormalizeError");
const ParityBrand = U.Brand("ParityError");
const classify = (x) => {
if (x === null) return "null";
if (x === undefined) return "undefined";
const t = typeof x;
if (t === "number" && Number.isNaN(x)) return "nan";
return t;
};
const UTF = (() => {
const cps = (s) => {
const out = [];
for (const ch of s) out.push(ch.codePointAt(0));
return out;
};
const isWS = (cp) =>
cp === 9 || cp === 10 || cp === 13 || cp === 32 || cp === 160 || cp === 8232 || cp === 8233;
const trim = (s) => {
const a = cps(s);
let i = 0;
while (i < a.length && isWS(a[i])) i++;
let j = a.length - 1;
while (j >= i && isWS(a[j])) j--;
return j < i ? "" : String.fromCodePoint(...a.slice(i, j + 1));
};
return U.deepFreeze({ trim });
})();
const Lexer = (() => {
const lex = (s) => {
const src = UTF.trim(String(s));
const a = [];
let i = 0;
const ch = () => (i < src.length ? src.charCodeAt(i) : -1);
const adv = () => (i < src.length ? src.charCodeAt(i++) : -1);
const isDigit = (c) => c >= 48 && c <= 57;
while (true) {
const c = ch();
if (c === -1) break;
if (c === 43 || c === 45) {
a.push({ k: "sign", v: String.fromCharCode(adv()) });
continue;
}
if (isDigit(c)) {
let buf = "";
while (isDigit(ch())) buf += String.fromCharCode(adv());
a.push({ k: "digits", v: buf });
continue;
}
a.push({ k: "junk", v: String.fromCharCode(adv()) });
}
return a;
};
return U.deepFreeze({ lex });
})();
const Parser = (() => {
const parseIntegerish = (s) => {
const toks = Lexer.lex(s);
let sign = "";
let digits = "";
let seenDigits = false;
let seenSign = false;
for (const t of toks) {
if (t.k === "junk") return null;
if (t.k === "sign") {
if (seenDigits || seenSign) return null;
seenSign = true;
sign = t.v === "-" ? "-" : "";
continue;
}
if (t.k === "digits") {
if (seenDigits) return null;
seenDigits = true;
digits = t.v;
continue;
}
return null;
}
if (!seenDigits) return null;
return sign + digits;
};
return U.deepFreeze({ parseIntegerish });
})();
const NumberGate = (() => {
const toBigInt = (n) => {
if (typeof n !== "number") return null;
if (!Number.isFinite(n)) return null;
if (!Number.isSafeInteger(n)) return null;
const buf = new ArrayBuffer(8);
const dv = new DataView(buf);
dv.setFloat64(0, n, false);
const hi = dv.getUint32(0, false);
const lo = dv.getUint32(4, false);
const bits = (BigInt(hi) << 32n) | BigInt(lo);
const exp = (bits >> 52n) & 0x7FFn;
if (exp === 0x7FFn) return null;
try {
return BigInt(String(n));
} catch (_) {
return null;
}
};
return U.deepFreeze({ toBigInt });
})();
const normalize = (() => {
const E = U.Either;
const fail = (msg) => {
const e = new TypeError(msg);
e[NormalizeBrand.name] = true;
return E.Left(e);
};
const ok = (v) => E.Right(v);
const tryValueOf = (x) => {
try {
if (x && typeof x.valueOf === "function") {
const v = x.valueOf();
return ok(v);
}
} catch (_) {}
return fail("valueOf");
};
const tryToString = (x) => {
try {
return ok(String(x));
} catch (_) {
return fail("toString");
}
};
const step = (x) => {
const k = classify(x);
bus.emit("norm:k", k);
if (k === "bigint") return ok(x);
if (k === "boolean") return ok(x ? 1n : 0n);
if (k === "null") return ok(0n);
if (k === "undefined") return fail("undefined");
if (k === "nan") return fail("nan");
if (k === "number") {
const b = NumberGate.toBigInt(x);
return b === null ? fail("number") : ok(b);
}
if (k === "string") {
const s = UTF.trim(x);
let candidate = null;
try {
const j = JSON.parse(s);
if (typeof j === "number" && Number.isSafeInteger(j)) candidate = String(j);
else if (typeof j === "string") candidate = Parser.parseIntegerish(j);
} catch (_) {}
if (candidate === null) candidate = Parser.parseIntegerish(s);
if (candidate === null) return fail("string");
try {
return ok(BigInt(candidate));
} catch (_) {
return fail("bigint");
}
}
if (k === "symbol" || k === "function") return fail(k);
if (k === "object") {
const px = U.proxify(x);
const r = tryValueOf(px);
return E.chain(r, (v) => (v === x ? tryToString(px) : ok(v)));
}
return fail("unknown");
};
const run = (input) => {
const E = U.Either;
const go = (x, depth) => () => {
if (depth > 20) return fail("depth");
const r = step(x);
return E.fold(
r,
(e) => E.Left(e),
(v) => {
const k = classify(v);
if (k === "bigint") return E.Right(v);
return go(v, depth + 1);
}
);
};
return U.trampoline(go(input, 0));
};
return U.deepFreeze({ run });
})();
const Parity = (() => {
const E = U.Either;
const fail = (msg) => {
const e = new Error(msg);
e[ParityBrand.name] = true;
return E.Left(e);
};
const ok = (v) => E.Right(v);
const lsbViaAutomaton = (n) => {
const abs = n < 0n ? -n : n;
const step = (x) => {
const q = x / 2n;
const r = x - q * 2n;
return { q, r };
};
const init = step(abs);
const states = Object.freeze({
S0: Object.freeze({ name: "S0" }),
S1: Object.freeze({ name: "S1" }),
});
const trans = (state, bit) => {
if (bit === 0n) return states.S0;
if (bit === 1n) return states.S1;
return state;
};
const finalState = trans(states.S0, init.r);
return finalState === states.S1;
};
const parity = (n) => (typeof n !== "bigint" ? fail("not-bigint") : ok(lsbViaAutomaton(n)));
return U.deepFreeze({ parity });
})();
const Runtime = (() => {
const E = U.Either;
const mk = () => {
const metrics = { calls: 0, kinds: Object.create(null) };
const off = bus.on("norm:k", (k) => (metrics.kinds[k] = (metrics.kinds[k] || 0) + 1));
const exec = (input) => {
metrics.calls += 1;
const n = normalize.run(input);
const p = E.chain(n, (b) => Parity.parity(b));
return E.fold(p, () => false, (v) => Boolean(v));
};
const close = () => off();
return U.deepFreeze({ exec, close, metrics, [U.S.meta]: U.deepFreeze({ createdAt: Date.now() }) });
};
return U.deepFreeze({ mk });
})();
env.bind("rt", Runtime.mk());
const entry = U.memo1((input) => {
const rt = env.must("rt");
const staged = U.pipe(
(v) => ({ v }),
(box) => Object.seal(box),
(box) => Reflect.get(box, "v")
)(input);
const out = rt.exec(staged);
const box = Object.create(null);
Object.defineProperty(box, "value", { get: () => out });
return Boolean(box.value);
});
return entry;
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment