UNPKG

@electric-sql/d2ts

Version:

D2TS is a TypeScript implementation of Differential Dataflow.

38 lines 1.52 kB
import { StreamBuilder } from '../../d2.js'; import { DifferenceStreamWriter } from '../../graph.js'; import { ReduceOperatorSQLite } from './reduce.js'; import { SQLiteContext } from '../context.js'; export class CountOperatorSQLite extends ReduceOperatorSQLite { constructor(id, inputA, output, initialFrontier, db) { const countInner = (vals) => { let count = 0; for (const [_, diff] of vals) { count += diff; } return [[count, 1]]; }; super(id, inputA, output, countInner, initialFrontier, db); } } /** * Counts the number of elements by key * Persists state to SQLite * * @param db - Optional SQLite database (can be injected via context) */ export function count(db) { return (stream) => { // Get database from context if not provided explicitly const database = db || SQLiteContext.getDb(); if (!database) { throw new Error('SQLite database is required for count operator. ' + 'Provide it as a parameter or use withSQLite() to inject it.'); } const output = new StreamBuilder(stream.graph, new DifferenceStreamWriter()); const operator = new CountOperatorSQLite(stream.graph.getNextOperatorId(), stream.connectReader(), output.writer, stream.graph.frontier(), database); stream.graph.addOperator(operator); stream.graph.addStream(output.connectReader()); return output; }; } //# sourceMappingURL=count.js.map