diff --git a/src/extra/debounce.ts b/src/extra/debounce.ts index dcc4707..4e46ae2 100644 --- a/src/extra/debounce.ts +++ b/src/extra/debounce.ts @@ -1,9 +1,10 @@ -import {Operator, Stream} from '../index'; +import {Operator, Stream, NO} from '../index'; class DebounceOperator implements Operator { public type = 'debounce'; public out: Stream = null as any; private id: any = null; + private t: any = NO; constructor(public dt: number, public ins: Stream) { @@ -32,9 +33,11 @@ class DebounceOperator implements Operator { const u = this.out; if (!u) return; this.clearInterval(); + this.t = t; this.id = setInterval(() => { this.clearInterval(); u._n(t); + this.t = NO; }, this.dt); } @@ -49,6 +52,8 @@ class DebounceOperator implements Operator { const u = this.out; if (!u) return; this.clearInterval(); + if (this.t != NO) u._n(this.t); + this.t = NO; u._c(); } } diff --git a/tests/extra/debounce.ts b/tests/extra/debounce.ts index 922ae4e..68dd9f0 100644 --- a/tests/extra/debounce.ts +++ b/tests/extra/debounce.ts @@ -2,6 +2,7 @@ /// import xs, {Listener, Producer} from '../../src/index'; import debounce from '../../src/extra/debounce'; +import fromDiagram from '../../src/extra/fromDiagram'; import * as assert from 'assert'; describe('debounce (extra)', () => { @@ -29,4 +30,34 @@ describe('debounce (extra)', () => { }; stream.addListener(listener); }); + + it('should emit any pending value upon completion', (done: any) => { + const stream = fromDiagram('-1----2-|').compose(debounce(50)); + const expected = [1, 2]; + stream.addListener({ + next: (x: number) => { + assert.equal(x, expected.shift()); + }, + error: (err: Error) => done(err), + complete: () => { + assert.strictEqual(expected.length, 0); + done(); + }, + }); + }); + + it('should not emit value upon completion if no pending value', (done: any) => { + const stream = fromDiagram('-1----2-------|').compose(debounce(50)); + const expected = [1, 2]; + stream.addListener({ + next: (x: number) => { + assert.equal(x, expected.shift()); + }, + error: (err: Error) => done(err), + complete: () => { + assert.strictEqual(expected.length, 0); + done(); + }, + }); + }); });