Skip to content

Commit

Permalink
feat(debounce): emit pending value on completion
Browse files Browse the repository at this point in the history
Emit any pending value, then complete, if a source stream completes
before a debounce interval closes. Clear pending value upon
completion. Support falsy emission values such as `false` and 0.

Resolve #257.
  • Loading branch information
xtianjohns authored and staltz committed Jul 22, 2018
1 parent 0c0cf40 commit 7ab4b17
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 1 deletion.
7 changes: 6 additions & 1 deletion src/extra/debounce.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import {Operator, Stream} from '../index';
import {Operator, Stream, NO} from '../index';

class DebounceOperator<T> implements Operator<T, T> {
public type = 'debounce';
public out: Stream<T> = null as any;
private id: any = null;
private t: any = NO;

constructor(public dt: number,
public ins: Stream<T>) {
Expand Down Expand Up @@ -32,9 +33,11 @@ class DebounceOperator<T> implements Operator<T, T> {
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);
}

Expand All @@ -49,6 +52,8 @@ class DebounceOperator<T> implements Operator<T, T> {
const u = this.out;
if (!u) return;
this.clearInterval();
if (this.t != NO) u._n(this.t);
this.t = NO;
u._c();
}
}
Expand Down
31 changes: 31 additions & 0 deletions tests/extra/debounce.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
/// <reference types="node" />
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)', () => {
Expand Down Expand Up @@ -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();
},
});
});
});

0 comments on commit 7ab4b17

Please sign in to comment.