diff --git a/package.json b/package.json index ad85a79..4d0c505 100644 --- a/package.json +++ b/package.json @@ -17,13 +17,13 @@ "callbag" ], "devDependencies": { + "callbag-for-each": "^1.0.1", + "callbag-from-iter": "^1.0.0", "callbag-mock": "^1.0.0", + "callbag-pipe": "^1.1.1", "tape": "^4.8.0", "ts-node": "^5.0.0", - "typescript": "^2.7.2", - "callbag-for-each": "^1.0.1", - "callbag-from-iter": "^1.0.0", - "callbag-pipe": "^1.1.1" + "typescript": "^2.7.2" }, "dependencies": {} } diff --git a/src/debounce.ts b/src/debounce.ts index 32ef19c..91ef453 100644 --- a/src/debounce.ts +++ b/src/debounce.ts @@ -7,8 +7,13 @@ export function debounce(wait: number): any { return (source: any) => (start: number, sink: any) => { if (start !== 0) return; + let ask: any; let timeout: number | undefined; source(0, (t: number, d: any) => { + if (t === 0) { + ask = d; + } + if (t === 1 || (t === 2 && d === undefined)) { // t === 1 means the source is emitting a value // t === 2 and d === undefined means the source emits a completion @@ -22,11 +27,12 @@ export function debounce(wait: number): any { sink(t, d); timeout = undefined; }, wait); + + if (t === 1) { + ask(1) + } } /* - * no need to handle the t === 0 case because - * the operator never needs to talkback to the source - * * nothing specific to do when the source * sends a t === 2 d !== undefined signal */ diff --git a/test.ts b/test.ts index 0b575d4..9a922c4 100644 --- a/test.ts +++ b/test.ts @@ -2,6 +2,7 @@ const test = require("tape"); const pipe = require("callbag-pipe"); const forEach = require("callbag-for-each"); +const fromIter = require("callbag-from-iter"); const mock = require("callbag-mock"); import { debounce } from "./src/debounce"; @@ -113,3 +114,31 @@ test("it should send completion after the last emission", t => { source.emit(2); }); + + +test("it should with pullable source", t => { + t.plan(2); + const actual = [] + + const timeStart = Date.now(); + const debounceValue = 1000; + + pipe( + fromIter([1, 2, 3]), + debounce(debounceValue), + s => (start, sink) => { + if (start !== 0) return; + s(0, (st, d) => { + if (st === 2) { + const exeTime = Date.now() - timeStart; + t.ok(exeTime >= debounceValue); + t.equals(actual.length, 0); + } + sink(st, d); + }); + }, + forEach((value) => { + actual.push(value); + }), + ); +});