// SPDX-License-Identifier: CC0-1.0 // Teaching illustration adapted from Shapiro et al., RR7506 section 3.1.2. // Two fixed, distinct replica identities; no reset, persistence or networking. function validate(state) { if (!Array.isArray(state) || state.length !== 2) throw new TypeError("Expected two replica components"); for (let i = 0; i < 2; i++) { if (!Number.isSafeInteger(state[i]) || state[i] < 0) throw new RangeError("Expected nonnegative safe integers"); } } export function increment(state, actor) { validate(state); if (actor !== 0 && actor !== 1) throw new RangeError("Unknown replica"); if (state[actor] === Number.MAX_SAFE_INTEGER) throw new RangeError("Counter overflow"); const next = [...state]; next[actor]++; return next; } export function merge(left, right) { validate(left); validate(right); return left.map((count, i) => Math.max(count, right[i])); } export function value(state) { validate(state); const total = state[0] + state[1]; if (!Number.isSafeInteger(total)) throw new RangeError("Total overflow"); return total; } export function examples() { const left = increment([0, 0], 0), right = increment([0, 0], 1); const joined = merge(left, right); return [ { strategy: "Maximum of scalar totals", first: Math.max(value(left), value(right)), replay: Math.max(value(left), value(right), value(right)) }, { strategy: "Sum of scalar totals", first: value(left) + value(right), replay: value(left) + 2 * value(right) }, { strategy: "Componentwise maximum, then sum", first: value(joined), replay: value(merge(joined, right)) }, ]; }