pattern/data-structures/persistent-trie
- Bun
- TypeScript
Nunca muda no lugar: cada escrita devolve versão nova e reaproveita por referência o que não mudou (structural sharing); a versão anterior segue válida.
pattern/data-structures/persistent-trie
Cenário
Rebalanceamento de carteira de 16 posições comprando PETR4; o gestor desfaz e compara sem copiar a carteira.
Planta
Fluxo8 passos — reproduza para seguir o fluxo
Como funciona
4passos
Trie que nunca muda no lugar: cada escrita devolve versão nova e reaproveita o que não mudou
Esconde cada passo: lembre antes de tocar para revelar.
Posições num trie de 4 vias, filho por grupos de 2 bits do índice
trieSet clona só o caminho até a folha: altura + 1 nós
Nós fora do caminho são os mesmos objetos
Desfazer = usar a raiz antiga
Trade-offs
O que se ganha, o que se paga
Vantagens
Versões antigas válidas sem recomputar
Escrita clona O(log n) nós
Custos
Leitura O(log n) contra O(1)
Implementação maior que mutação
Código
pattern/data-structures/persistent-trie
4 arquivos./
src/
Executar só Bun
bun run demo# roda o cenárioSaída: v1 com 200 ações de PETR4, 2 nós novos (raiz e folha) e 3 folhas compartilhadas com v0; v0 continua com 100 ações.
Código
src/demo.ts// Demo: a portfolio of 16 positions is rebalanced into a new version; only the path to the changed position is copied, the rest is shared.
const TRIE_BITS = 2;
const TRIE_MASK = (1 << TRIE_BITS) - 1; // 4 children per branch
type PortfolioPosition = { readonly symbol: string; readonly quantity: number; readonly averagePriceCents: number };
type TrieNode = { readonly children: readonly (TrieNode | undefined)[] } | { readonly values: readonly PortfolioPosition[] };
// Path copying, as in Clojure's PersistentVector: clones only the nodes on the path; the other children keep the same reference.
function trieSet(node: TrieNode | undefined, shift: number, index: number, value: PortfolioPosition): TrieNode {
if (shift === 0) {
const values = node && "values" in node ? node.values.slice() : [];
values[index & TRIE_MASK] = value;
return { values };
}
const children = node && "children" in node ? node.children.slice() : [];
children[(index >>> shift) & TRIE_MASK] = trieSet(children[(index >>> shift) & TRIE_MASK], shift - TRIE_BITS, index, value);
return { children };
}
function trieGet(node: TrieNode, shift: number, index: number): PortfolioPosition {
return "values" in node ? node.values[index & TRIE_MASK]! : trieGet(node.children[(index >>> shift) & TRIE_MASK]!, shift - TRIE_BITS, index);
}
// Every node reachable from a root: comparing two sets by reference measures the sharing.
function trieNodes(node: TrieNode | undefined, into = new Set<TrieNode>()): Set<TrieNode> {
if (!node) return into;
into.add(node);
if ("children" in node) for (const child of node.children) trieNodes(child, into);
return into;
}
// 16 positions fit a trie of height 1 (root + 4 leaves): shift 2 at the root, 0 at the leaves.
const ROOT_SHIFT = TRIE_BITS;
const symbols = ["PETR4", "VALE3", "ITUB4", "BBDC4", "BOVA11", "WEGE3", "ABEV3", "B3SA3", "MXRF11", "HGLG11", "KNRI11", "ITSA4", "RENT3", "SUZB3", "GGBR4", "PRIO3"];
const v0 = symbols.reduce<TrieNode | undefined>((root, symbol, index) => trieSet(root, ROOT_SHIFT, index, { symbol, quantity: 100, averagePriceCents: 3_000 }), undefined)!;
// Rebalance: buy 100 more PETR4. v0 is never touched; v1 is a new root.
const petr4 = trieGet(v0, ROOT_SHIFT, 0);
const v1 = trieSet(v0, ROOT_SHIFT, 0, { ...petr4, quantity: petr4.quantity + 100 });
const shared = trieNodes(v0);
const created = [...trieNodes(v1)].filter((node) => !shared.has(node)).length;
console.log(` [v1] PETR4 ${trieGet(v1, ROOT_SHIFT, 0).quantity} shares; ${created} nodes new, ${trieNodes(v1).size - created} shared with v0`);
// Undo is just using the old root again: nothing is recomputed.
console.log(` [UNDO] v0 still answers PETR4 ${trieGet(v0, ROOT_SHIFT, 0).quantity} shares`);
Nível
introdutório
1/13
Domínio financeiro
Padrões do catálogo que implementa
Por que se relacionam
Teste rápido
Qual destes combina com Persistent Data Structure?
Versões imutáveis do estado. Abrir Snapshot
Seu progresso
0/157 estudados
Fica salvo só neste navegador.