import type { ArrayNonEmpty } from '@rimbu/common'; import { Reducer, type StreamSource } from '@rimbu/stream'; import { isEmptyStreamSourceInstance } from '@rimbu/stream/custom'; import type { ValuedGraphBase } from '@rimbu/graph/custom'; import type { ValuedGraphElement, WithGraphValues, } from '../../common/index.mjs'; import { ValuedGraphBuilder, ValuedGraphEmpty, ValuedGraphNonEmpty, } from '@rimbu/graph/custom'; export interface ValuedGraphTypesContextImpl extends ValuedGraphBase.Types { readonly context: ValuedGraphContext; } export class ValuedGraphContext< UN, TT extends string, Tp extends ValuedGraphTypesContextImpl = ValuedGraphTypesContextImpl, > implements ValuedGraphBase.Context { readonly _fixedType!: UN; readonly _empty: any; constructor( readonly isDirected: boolean, readonly typeTag: TT, readonly linkMapContext: WithGraphValues['linkMapContext'], readonly linkConnectionsContext: WithGraphValues< Tp, UN, any >['linkConnectionsContext'] ) { this._empty = Object.freeze(new ValuedGraphEmpty(isDirected, this)); } isNonEmptyInstance( source: any ): source is WithGraphValues['nonEmpty'] { return source instanceof ValuedGraphNonEmpty; } readonly empty = (): any => { return this._empty; }; readonly from: any = ( ...sources: ArrayNonEmpty>> ): any => { let builder = this.builder(); let i = -1; const length = sources.length; while (++i < length) { const source = sources[i]; if (isEmptyStreamSourceInstance(source)) continue; if ( builder.isEmpty && this.isNonEmptyInstance(source) && source.context === this ) { if (i === length - 1) return source; builder = source.toBuilder(); continue; } builder.addGraphElements(source); } return builder.build(); }; readonly of: any = ( ...values: ArrayNonEmpty> ): any => { return this.from(values).assumeNonEmpty(); }; readonly builder = (): any => { return new ValuedGraphBuilder(this.isDirected, this); }; readonly reducer = ( source?: StreamSource> ): any => { return Reducer.create( () => undefined === source ? this.builder() : this.from(source).toBuilder(), (builder, entry) => { builder.addGraphElement(entry); return builder; }, (builder) => builder.build() ); }; createBuilder( source?: WithGraphValues['nonEmpty'] ): WithGraphValues['builder'] { return new ValuedGraphBuilder( this.isDirected, this, source ) as any; } createNonEmpty( linkMap: WithGraphValues['linkMapNonEmpty'], connectionSize: number ): WithGraphValues['nonEmpty'] { return new ValuedGraphNonEmpty( this.isDirected, this, linkMap, connectionSize ) as any; } }