UNPKG

fugue

Version:

Fractional indexing without conflicts.

259 lines (258 loc) 7.85 kB
// src/strings.ts var FIRST = ""; var LAST = "~"; var Fugue = class _Fugue { /** * A string that is less than all positions. */ static FIRST = FIRST; /** * A string that is greater than all positions. */ static LAST = LAST; /** * The unique ID for this client. */ clientID; /** * The waypoints' long name: `,${clientID}.`. */ longName; /** * Variant of longName used for a position's first ID: `${clientID}.`. * (Otherwise every position would start with a redundant ','.) */ firstName; /** * For each waypoint that we created, maps a prefix (see getPrefix) * for that waypoint to its last (most recent) valueSeq. * We always store the right-side version (odd valueSeq). */ lastValueSeqs = /* @__PURE__ */ new Map(); maxCachedPrefixes = 1e3; constructor(clientID) { const clientIDSanitized = sanitizeClientID(clientID); this.longName = `,${clientIDSanitized}.`; this.firstName = `${clientIDSanitized}.`; this.clientID = clientIDSanitized; } /** * Creates a new position between two existing positions. * The new position will be greater than `a` and less than `b`. * * @param a - An existing position to insert after, or null to insert at the beginning * @param b - An existing position to insert before, or null to insert at the end * @returns A new position that satisfies `a < new < b` * * @example * ```typescript * const fugue = new Fugue("client1"); * const pos1 = fugue.between(null, null); // First position * const pos2 = fugue.between(pos1, null); // Insert after pos1 * const pos3 = fugue.between(pos1, pos2); // Insert between pos1 and pos2 * // pos1 < pos3 < pos2 * ``` * * @throws Will warn and adjust inputs if: * - `a >= b` (when both are non-null) * - `b > Fugue.LAST` */ between(a, b) { let left = a; let right = b; if (left !== null && right !== null && left >= right) { console.warn( `left must be less than right: ${left} < ${right} - using ${_Fugue.FIRST} instead` ); left = _Fugue.FIRST; } if (right !== null && right > _Fugue.LAST) { console.warn( `right must be less than or equal to LAST: ${right} > ${_Fugue.LAST} - using ${_Fugue.LAST} instead` ); right = _Fugue.LAST; } let ans; if (right !== null && (left === null || right.startsWith(left))) { const ancestor = leftVersion(right); ans = this.appendWaypoint(ancestor); } else { if (left === null) { ans = this.appendWaypoint(""); } else { const prefix = getPrefix(left); const lastValueSeq = prefix ? this.lastValueSeqs.get(prefix) ?? null : null; if (prefix !== null && lastValueSeq !== null && !(right !== null && right.startsWith(prefix))) { const valueSeq = nextOddValueSeq(lastValueSeq); ans = prefix + stringifyBase52(valueSeq); this.lastValueSeqs.set(prefix, valueSeq); } else { ans = this.appendWaypoint(left); } } } return ans; } /** * Creates a new position immediately after the given position. * This is equivalent to calling `between(position, null)`. * * @param position - The existing position to insert after * @returns A new position that is greater than the given position * * @example * ```typescript * const fugue = new Fugue("client1"); * const pos1 = fugue.between(null, null); // First position * const pos2 = fugue.after(pos1); // Insert after pos1 * // pos1 < pos2 * ``` */ after(position) { return this.between(position, null); } /** * Creates a new position immediately before the given position. * This is equivalent to calling `between(null, position)`. * * @param position - The existing position to insert before * @returns A new position that is less than the given position * * @example * ```typescript * const fugue = new Fugue("client1"); * const pos1 = fugue.between(null, null); // First position * const pos2 = fugue.before(pos1); // Insert before pos1 * // pos2 < pos1 * ``` */ before(position) { return this.between(null, position); } /** * Creates the first position in a sequence. * This is equivalent to calling `between(null, null)`. * * @returns A new position that is greater than all existing positions * * @example * ```typescript * const fugue = new Fugue("client1"); * const pos1 = fugue.first(); // First position * const pos2 = fugue.after(pos1); // Insert after pos1 * // pos1 < pos2 * ``` */ first() { return this.between(null, null); } /** * Appends a waypoint to the ancestor. */ appendWaypoint(ancestor) { let waypointName = ancestor === "" ? this.firstName : this.longName; let existing = ancestor.lastIndexOf(this.longName); if (ancestor.startsWith(this.firstName)) existing = 0; if (existing !== -1) { let index = -1; for (let i = existing; i < ancestor.length; i++) { if (ancestor[i] === ".") index++; } waypointName = stringifyShortName(index); } const prefix = ancestor + waypointName; const lastValueSeq = this.lastValueSeqs.get(prefix); const valueSeq = lastValueSeq === void 0 ? 1 : nextOddValueSeq(lastValueSeq); this.lastValueSeqs.set(prefix, valueSeq); this.cleanupLastValueSeqs(); return prefix + stringifyBase52(valueSeq); } /** * The number of prefixes in the cache. */ get cacheSize() { return this.lastValueSeqs.size; } /** * Cleans up the cache of last value sequences. */ cleanupLastValueSeqs() { if (this.lastValueSeqs.size > this.maxCachedPrefixes) { const entries = Array.from(this.lastValueSeqs.entries()).sort(([, a], [, b]) => b - a).slice(0, this.maxCachedPrefixes); this.lastValueSeqs = new Map(entries); } } }; function getPrefix(position) { for (let i = position.length - 2; i >= 0; i--) { const char = position[i]; if (char !== void 0 && (char === "." || "0" <= char && char <= "9")) { return position.slice(0, i + 1); } } return null; } function leftVersion(position) { const lastWaypointChar = position[position.length - 1]; if (lastWaypointChar === void 0) { return ""; } const last = parseBase52(lastWaypointChar); return position.slice(0, -1) + stringifyBase52(last - 1); } function stringifyShortName(n) { if (n < 0) { return "A"; } else if (n < 10) { return String.fromCharCode(48 + n); } else { return stringifyBase52(Math.floor(n / 10)) + String.fromCharCode(48 + n % 10); } } function stringifyBase52(n) { if (n === 0) { return "A"; } const codes = []; while (n > 0) { const digit = n % 52; codes.unshift((digit >= 26 ? 71 : 65) + digit); n = Math.floor(n / 52); } return String.fromCharCode(...codes); } function parseBase52(s) { let n = 0; for (let i = 0; i < s.length; i++) { const code = s.charCodeAt(i); const digit = code - (code >= 97 ? 71 : 65); n = 52 * n + digit; } return n; } var log52 = Math.log(52); function nextOddValueSeq(n) { const d = n === 0 ? 1 : Math.floor(Math.log(n) / log52) + 1; if (n === Math.pow(52, d) - Math.pow(26, d) - 1) { return (n + 1) * 52 + 1; } else { return n + 2; } } function sanitizeClientID(clientID) { let sanitized = clientID.replace(/[.,]/g, ""); if (sanitized.length !== clientID.length) { console.warn("clientID contains invalid characters"); } while (sanitized >= Fugue.LAST) { console.warn(`clientID must be less than ${Fugue.LAST}: ${sanitized}`); sanitized = sanitized.slice(0, -1); } if (sanitized.length === 0) { throw new Error("clientID cannot be empty"); } return sanitized; } export { Fugue };