Skip to content

Instantly share code, notes, and snippets.

@conartist6
Last active March 18, 2025 18:36
Show Gist options
  • Save conartist6/4ecfd1414efb98f5c8407be377432a4c to your computer and use it in GitHub Desktop.
Save conartist6/4ecfd1414efb98f5c8407be377432a4c to your computer and use it in GitHub Desktop.
Text-only sumtree
import { buildModule, defaultNodeSize } from '@bablr/btree/enhanceable';
const { isArray } = Array;
const { freeze } = Object;
const LiteralTag = Symbol.for('LiteralTag');
export { defaultNodeSize };
export const {
treeFrom,
treeFromValues,
pop,
push,
addAt,
isValidNode,
assertValidNode,
getValues,
getSums,
setValues,
isLeafNode,
traverse,
getSize,
findPath,
getAt,
replaceAt,
} = buildModule(
defaultNodeSize,
(acc, val) => {
const { references } = acc;
if (isArray(val)) {
acc.lineBreaks += val[2].lineBreaks;
} else {
if (val.type === LiteralTag) {
let text = val.value;
let idx = 0;
while ((idx = text.indexOf('\n', idx + 1)) >= 0) {
acc.lineBreaks++;
}
} else {
throw new Error('unimplemented');
}
}
return acc;
},
() => ({
lineBreaks: 0,
}),
(stats) => {
freeze(stats);
},
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment