forked from draggor/node-ircbot
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutil.js
More file actions
129 lines (116 loc) · 2.4 KB
/
util.js
File metadata and controls
129 lines (116 loc) · 2.4 KB
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
/*
* Actions is an array of functions that accept a callback
* as an argument. Each of these functions should return
* some hook to the async action so that it may be cancelled
* at a later time.
*/
exports.latch = function (actions, callback) {
var cnt = actions.length;
var cb = function() {
if(--cnt != 0) {
return;
} else {
callback.apply(this, arguments);
}
};
return actions.map(function(f) {
f(cb);
});
};
exports.getUniqueId = (function() {
var id = 0;
return function(reset) {
if(reset) {
id = 1;
return 0;
} else {
return id++;
}
};
})();
exports.getUniquePrefixId = (function() {
var ids = {};
return function(prefix, reset) {
ids[prefix] = ids[prefix] || 0;
if(reset) {
ids[prefix] = 1;
return prefix + 0;
} else {
return prefix + ids[prefix]++;
}
};
})();
/*
* This is destructive!
* It returns the list as a convenience.
*/
exports.randomize = function(list) {
for(var i = 0; i < list.length; i++) {
var j = Math.floor(Math.random() * list.length);
var tempi = list[i];
list[i] = list[j];
list[j] = tempi;
}
return list;
};
/*
* This only makes a new list, the items in the list are shared between this and the old!
*/
exports.safeRandomize = function(list) {
return exports.randomize(list.concat([]));
};
exports.delayMap = function(items, callback, delay) {
var o = {};
var i = 0;
var f = function() {
if(i < items.length) {
callback(items[i++]);
return o.id = setTimeout(f, delay);
}
};
o.id = f();
return o;
};
exports.throttle = function (func, t, ctx) {
var timeout = false
, queue = []
, qf = function() {
var q = queue.shift();
if(q) { q(); timeout = setTimeout(qf, t); } else { timeout = false; }
}
;
var f = function() {
var args = arguments
, i = function() {
func.apply(ctx, args);
};
if(timeout && timeout._idleNext) {
queue.push(i);
} else {
i();
timeout = setTimeout(qf, t);
}
return timeout;
};
return f;
}
/*
var l = throttle(function(a, b) { console.log([a, b]); }, 1000);
l('a', 1);
l('b', 2);
l('c', 3);
setTimeout(function(){l('d', 4);}, 2000);
*/
exports.split = function(str, separator, limit) {
var isep = str.indexOf(separator)
, ilast = 0
, sp = []
;
while(isep >= 0 && sp.length < limit - 1) {
sp.push(str.substring(ilast, isep));
ilast = isep + 1;
isep = str.indexOf(separator, ilast);
}
sp.push(str.substring(ilast));
return sp;
};