All files / packages/value/src dict.ts

100% Statements 23/23
50% Branches 2/4
100% Functions 6/6
100% Lines 22/22

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78                          8x 8x       3x       1x 1x                     1x           5x       5x 5x   5x 6x 6x   6x     5x       1x 1x   1x 1x     1x     1x       1x 2x        
import { create } from '@bufbuild/protobuf'
import * as Ydb from '@ydbjs/api/value'
 
import { type Type, TypeKind } from './type.js'
import type { Value } from './value.js'
import { NullType } from './null.js'
 
export class DictType implements Type {
	readonly key: Type
	readonly value: Type
	#typeInstance?: Ydb.Type
 
	constructor(keyType: Type, valueType: Type) {
		this.key = keyType
		this.value = valueType
	}
 
	get kind(): TypeKind.DICT {
		return TypeKind.DICT
	}
 
	encode(): Ydb.Type {
		Eif (!this.#typeInstance) {
			this.#typeInstance = create(Ydb.TypeSchema, {
				type: {
					case: 'dictType',
					value: {
						key: this.key.encode(),
						payload: this.value.encode(),
					},
				},
			})
		}
 
		return this.#typeInstance
	}
}
 
export class Dict<K extends Value = Value, V extends Value = Value> implements Value<DictType> {
	readonly type: DictType
	readonly pairs: [K, V][] = []
	#valueInstance?: Ydb.Value
 
	constructor(...items: [K, V][]) {
		let keyType: Type = new NullType()
		let valueType: Type = new NullType()
 
		for (let [k, v] of items) {
			keyType = k.type
			valueType = v.type
 
			this.pairs.push([k, v])
		}
 
		this.type = new DictType(keyType, valueType)
	}
 
	encode(): Ydb.Value {
		Eif (!this.#valueInstance) {
			let pairs: { key: Ydb.Value; payload: Ydb.Value }[] = []
 
			for (let [k, v] of this.pairs) {
				pairs.push({ key: k.encode(), payload: v.encode() })
			}
 
			this.#valueInstance = create(Ydb.ValueSchema, { pairs })
		}
 
		return this.#valueInstance
	}
 
	*[Symbol.iterator](): Iterator<[K, V]> {
		for (let i = 0; i < this.pairs.length; i++) {
			yield this.pairs[i]!
		}
	}
}