Skip to content

Commit

Permalink
feat(rstream): add debounce() sub & tests
Browse files Browse the repository at this point in the history
  • Loading branch information
postspectacular committed Jun 14, 2020
1 parent 1073735 commit 9c53bb4
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 0 deletions.
1 change: 1 addition & 0 deletions packages/rstream/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ export * from "./from/worker";

export * from "./subs/asidechain";
export * from "./subs/bisect";
export * from "./subs/debounce";
export * from "./subs/post-worker";
export * from "./subs/resolve";
export * from "./subs/sidechain-partition";
Expand Down
19 changes: 19 additions & 0 deletions packages/rstream/src/subs/debounce.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { fromIterable } from "../from/iterable";
import { metaStream, MetaStreamOpts } from "../metastream";

/**
* Returns a subscription which ignores any intermediate inputs arriving
* faster than given `delay` time period.
*
* @example
* ```ts
*
* ```
*
* @param delay
*/
export const debounce = <T>(delay: number, opts?: Partial<MetaStreamOpts>) =>
metaStream((x: T) => fromIterable([x], { delay }), {
emitLast: true,
...opts,
});
35 changes: 35 additions & 0 deletions packages/rstream/test/debounce.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import * as assert from "assert";
import { debounce, fromIterable } from "../src/index";
import { TIMEOUT } from "./config";

describe("debounce", () => {
it("basic", (done) => {
const acc: number[] = [];
fromIterable([1, 2, 3], { delay: TIMEOUT })
.subscribe(debounce(TIMEOUT * 1.5))
.subscribe({
next(x) {
acc.push(x);
},
});
setTimeout(() => {
assert.deepEqual(acc, [3]);
done();
}, TIMEOUT * 5);
});

it("no last", (done) => {
const acc: number[] = [];
fromIterable([1, 2, 3], { delay: TIMEOUT })
.subscribe(debounce(TIMEOUT * 1.5, { emitLast: false }))
.subscribe({
next(x) {
acc.push(x);
},
});
setTimeout(() => {
assert.deepEqual(acc, []);
done();
}, TIMEOUT * 5);
});
});

0 comments on commit 9c53bb4

Please sign in to comment.