-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
77 lines (60 loc) · 1.5 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
'use strict';
var through = require('through');
function debounceHashed(fn, hashingFn, interval, immediate) {
var calls = {}
function ap(f, d) {
return f.apply(d.context, d.args);
}
function debounced() {
var hash = hashingFn.apply(this, arguments);
var prevCall = calls[hash];
var callNow = immediate && !prevCall;
if (prevCall) {
clearTimeout(prevCall.timeout);
}
function later() {
var data = calls[hash];
delete calls[hash];
if (!immediate) ap(fn, data);
}
calls[hash] = {
context: this,
args: arguments,
timeout: setTimeout(later, interval)
};
if (callNow) ap(fn, calls[hash]);
}
debounced.flush = function() {
Object.keys(calls).forEach(function(hash) {
var call = calls[hash];
delete calls[hash];
clearTimeout(call.timeout);
ap(fn, call);
});
};
return debounced;
}
var defaultOptions = {
hashingFn: function (data) {
return data.path;
},
wait: 1000,
immediate: false
};
function gulpDebounce(opts) {
Object.keys(defaultOptions).forEach(function (key) {
if (opts.hasOwnProperty(key)) return;
opts[key] = defaultOptions[key];
});
var debouncedPassthrough =
debounceHashed(passthrough, opts.hashingFn, opts.wait, opts.immediate);
return through(debouncedPassthrough, flush);
function passthrough(data) {
this.queue(data);
}
function flush() {
debouncedPassthrough.flush();
this.queue(null);
}
}
module.exports = gulpDebounce;