All files / packages/value/src tuple.ts

100% Statements 19/19
50% Branches 2/4
100% Functions 8/8
100% Lines 18/18

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                      7x       2x       1x 1x     2x         1x           5x       5x   5x 9x 9x     5x       1x 1x 2x       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'
 
export class TupleType implements Type {
	readonly elements: Type[]
	#typeInstance?: Ydb.Type
 
	constructor(elements: Type[]) {
		this.elements = elements
	}
 
	get kind(): TypeKind.TUPLE {
		return TypeKind.TUPLE
	}
 
	encode(): Ydb.Type {
		Eif (!this.#typeInstance) {
			this.#typeInstance = create(Ydb.TypeSchema, {
				type: {
					case: 'tupleType',
					value: { elements: this.elements.map((e) => e.encode()) },
				},
			})
		}
 
		return this.#typeInstance
	}
}
 
export class Tuple<T extends Value = Value> implements Value<TupleType> {
	readonly type: TupleType
	readonly items: T[] = []
	#valueInstance?: Ydb.Value
 
	constructor(...items: T[]) {
		let elements: Type[] = []
 
		for (let item of items) {
			this.items.push(item)
			elements.push(item.type)
		}
 
		this.type = new TupleType(elements)
	}
 
	encode(): Ydb.Value {
		Eif (!this.#valueInstance) {
			this.#valueInstance = create(Ydb.ValueSchema, {
				items: this.items.map((item) => item.encode()),
			})
		}
 
		return this.#valueInstance
	}
 
	*[Symbol.iterator](): Iterator<T> {
		for (let i = 0; i < this.items.length; i++) {
			yield this.items[i]!
		}
	}
}