MCPcopy Index your code
hub / github.com/TanStack/db / set

Method set

packages/db/src/utils/btree.ts:777–836  ·  view source on GitHub ↗
(
    key: K,
    value: V,
    overwrite: boolean | undefined,
    tree: BTree<K, V>,
  )

Source from the content-addressed store, hash-verified

775 // Internal Node: set & node splitting //////////////////////////////////////
776
777 set(
778 key: K,
779 value: V,
780 overwrite: boolean | undefined,
781 tree: BTree<K, V>,
782 ): boolean | BNodeInternal<K, V> {
783 const c = this.children,
784 max = tree._maxNodeSize,
785 cmp = tree._compare
786 let i = Math.min(this.indexOf(key, 0, cmp), c.length - 1),
787 child = c[i]!
788
789 if (child.isShared) c[i] = child = child.clone()
790 if (child.keys.length >= max) {
791 // child is full; inserting anything else will cause a split.
792 // Shifting an item to the left or right sibling may avoid a split.
793 // We can do a shift if the adjacent node is not full and if the
794 // current key can still be placed in the same node after the shift.
795 let other: BNode<K, V> | undefined
796 if (
797 i > 0 &&
798 (other = c[i - 1]!).keys.length < max &&
799 cmp(child.keys[0]!, key) < 0
800 ) {
801 if (other.isShared) c[i - 1] = other = other.clone()
802 other.takeFromRight(child)
803 this.keys[i - 1] = other.maxKey()!
804 } else if (
805 (other = c[i + 1]) !== undefined &&
806 other.keys.length < max &&
807 cmp(child.maxKey()!, key) < 0
808 ) {
809 if (other.isShared) c[i + 1] = other = other.clone()
810 other.takeFromLeft(child)
811 this.keys[i] = c[i]!.maxKey()!
812 }
813 }
814
815 const result = child.set(key, value, overwrite, tree)
816 if (result === false) return false
817 this.keys[i] = child.maxKey()!
818 if (result === true) return true
819
820 // The child has split and `result` is a new right child... does it fit?
821 if (this.keys.length < max) {
822 // yes
823 this.insert(i + 1, result)
824 return true
825 } else {
826 // no, we must split also
827 const newRightSibling = this.splitOffRightSide()
828 let target: BNodeInternal<K, V> = this
829 if (cmp(result.maxKey()!, this.maxKey()!) > 0) {
830 target = newRightSibling
831 i -= this.keys.length
832 }
833 target.insert(i + 1, result)
834 return newRightSibling

Callers

nothing calls this directly

Calls 8

insertMethod · 0.95
splitOffRightSideMethod · 0.95
cloneMethod · 0.80
indexOfMethod · 0.45
takeFromRightMethod · 0.45
maxKeyMethod · 0.45
takeFromLeftMethod · 0.45
setMethod · 0.45

Tested by

no test coverage detected