/
SortedSet.js
575 lines (518 loc) · 14.6 KB
/
SortedSet.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
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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
/*!
* Redback
* Copyright(c) 2011 Chris O'Hara <cohara87@gmail.com>
* MIT Licensed
*/
/**
* Module dependencies.
*/
var Structure = require('../Structure');
/**
* A wrapper for the Redis sorted set (zset) type. Each element has a
* score which is used to rank and order all elements in the set. Elements
* are ranked from lowest score to highest (the lowest score has
* a rank of 0)
*
* Usage:
* `redback.createSortedSet(key);`
*
* Reference:
* http://redis.io/topics/data-types#sorted-sets
*
* Redis Structure:
* `(namespace:)key = zset(score => element)`
*/
var SortedSet = exports.SortedSet = Structure.new();
/**
* Add one or more elements to the set.
*
* To add a single element and score:
* set.add(12, 'foo', callback);
*
* To add multiple elements/scores:
* set.add({foo:12, bar:3}, callback);
*
* @param {string|Object} element(s)
* @param {Function} callback
* @return this
* @api public
*/
SortedSet.prototype.add = function (score, element, callback) {
if (typeof score === 'object') {
callback = element;
element = score;
return this.addAll(element, callback);
}
this.client.zadd(this.key, score, element, callback);
return this;
}
/**
* Remove one or more elements from the set.
*
* @param {string|Array} element(s)
* @param {Function} callback
* @return this
* @api public
*/
SortedSet.prototype.remove = function (element, callback) {
if (Array.isArray(element)) {
return this.removeAll(element, callback);
}
this.client.zrem(this.key, element, callback);
return this;
}
/**
* Get the number of elements in the set.
*
* @param {Function} callback
* @return this
* @api public
*/
SortedSet.prototype.length = function (callback) {
this.client.zcard(this.key, callback);
return this;
}
/**
* Check whether an element exists in the set.
*
* @param {string} element
* @param {Function} callback
* @return this
* @api public
*/
SortedSet.prototype.exists = SortedSet.prototype.contains = function (element, callback) {
this.client.zscore(this.key, element, function (err, score) {
callback(err, score != null);
});
return this;
}
/**
* Get the rank of the specified element.
*
* @param {string} element
* @param {Function} callback
* @return this
* @api public
*/
SortedSet.prototype.rank = function (element, callback) {
this.client.zrank(this.key, element, callback)
return this;
}
/**
* Get the score of the specified element.
*
* @param {string} element
* @param {Function} callback
* @return this
* @api public
*/
SortedSet.prototype.score = function (element, callback) {
this.client.zscore(this.key, element, callback)
return this;
}
/**
* Increment the specified element's score.
*
* @param {string} element
* @param {int} amount (optional - default is 1)
* @param {Function} callback
* @return this;
* @api public
*/
SortedSet.prototype.increment = SortedSet.prototype.incrBy = function (element, amount, callback) {
if (typeof amount === 'function') {
callback = amount;
amount = 1;
}
this.client.zincrby(this.key, amount, element, callback);
return this;
}
/**
* Decrement the specified element's score.
*
* @param {string} element
* @param {int} amount (optional - default is 1)
* @param {Function} callback
* @return this;
* @api public
*/
SortedSet.prototype.decrement = SortedSet.prototype.decrBy = function (element, amount, callback) {
if (typeof amount === 'function') {
callback = amount;
amount = 1;
}
this.client.zincrby(this.key, -1 * amount, element, callback);
return this;
}
/**
* Add multiple elements to the set. See `add()`.
*
* @param {Object} elements
* @param {Function} callback
* @return this
* @api private
*/
SortedSet.prototype.addAll = function (elements, callback) {
var self = this, i,
remaining = 0,
failed = false,
add_count = 0;
for (i in elements) {
remaining++;
this.client.zadd(this.key, elements[i], i, function (err, added) {
if (failed) {
return;
} else if (err) {
failed = true;
return callback(err);
} else {
if (added) add_count++;
if (!--remaining) {
callback(null, add_count);
}
}
});
}
return this;
}
/**
* Remove multiple elements from the set. See `remove()`
*
* @param {Array} elements
* @param {Function} callback
* @return this
* @api private
*/
SortedSet.prototype.removeAll = function (elements, callback) {
var self = this,
remaining = elements.length,
failed = false,
rem_count = 0;
elements.forEach(function (element) {
self.client.zrem(self.key, element, function (err, added) {
if (failed) {
return;
} else if (err) {
failed = true;
return callback(err);
} else {
if (added) rem_count++;
if (!--remaining) callback(null, rem_count);
}
});
});
return this;
}
/**
* Get all elements in the set as an object `{element: score, ...}`.
* If `without_scores` is true then just an array of elements is returned.
*
* @param {bool} without_scores (optional - scores are included by default)
* @param {Function} callback
* @return this
* @api public
*/
SortedSet.prototype.get = function (without_scores, callback) {
if (typeof without_scores === 'function') {
callback = without_scores;
this.client.zrange(this.key, 0, -1, 'WITHSCORES', this.parseScores(callback));
} else {
this.client.zrange(this.key, 0, -1, callback);
}
return this;
}
/**
* Return a callback that parses a WITHSCORES result:
* ['foo','1','bar','2'] => {foo:1, bar:2}
*
* @param {Function} callback
* @api private
*/
SortedSet.prototype.parseScores = function (callback) {
return function (err, results) {
if (err) return callback(err, null);
if (!results || results.length < 2) return callback(null, null);
var len = results.length, i = 0, ret = {}, key, value;
while (true) {
key = results[i++];
value = results[i++];
ret[key] = value;
if (i >= len) break;
}
callback(null, ret);
}
}
/**
* Get elements with scores between the specified range. Elements are returned
* as an object `{element: score, ...}` and ordered from highest score to lowest.
*
* Note that the `start` and `end` range is inclusive and can be an integer or
* the constants `redback.INF` to represent infinity, or `redback.NINF` to
* represent negative infinity. `start` must be <= `end`.
*
* @param {int} start
* @param {int} end
* @param {int} count (optional) - the maximum number of elements to return
* @param {int} offset (optional) - if using count, start at this offset
* @param {Function} callback
* @return this
* @api public
*/
SortedSet.prototype.getScores = function (start, end, count, offset, callback) {
if (null === start) start = '-inf';
if (null === end) end = '+inf';
if (typeof count === 'function') {
callback = count;
this.client.zrangebyscore(this.key, start, end,
'WITHSCORES', this.parseScores(callback));
return this;
} else if (typeof offset === 'function') {
callback = offset;
offset = 0;
}
this.client.zrangebyscore(this.key, start, end, 'WITHSCORES',
'LIMIT', offset, count, this.parseScores(callback));
return this;
}
/**
* The same as `getScores()` but elements are ordered from lowest score to highest.
*
* Note that `end` must be <= `start`.
*
* @param {int} start
* @param {int} end
* @param {int} count (optional) - the maximum number of elements to return
* @param {int} offset (optional) - if using count, start at this offset
* @param {Function} callback
* @return this
* @api public
*/
SortedSet.prototype.getScoresReverse = function (start, end, count, offset, callback) {
if (null === start) start = '+inf';
if (null === end) end = '-inf';
if (typeof count === 'function') {
callback = count;
this.client.zrevrangebyscore(this.key, start, end,
'WITHSCORES', this.parseScores(callback));
return this;
} else if (typeof offset === 'function') {
callback = offset;
offset = 0;
}
this.client.zrevrangebyscore(this.key, start, end, 'WITHSCORES',
'LIMIT', offset, count, this.parseScores(callback));
return this;
}
/**
* Remove elements with scores between the specified range (inclusive).
*
* @param {int} start
* @param {int} end
* @param {Function} callback
* @return this
* @api public
*/
SortedSet.prototype.removeScores = function (start, end, callback) {
if (null === start) start = '-inf';
if (null === end) end = '+inf';
this.client.zremrangebyscore(this.key, start, end, callback);
return this;
}
/**
* Count the number of elements with scores between the specified
* range (inclusive).
*
* @param {int} start
* @param {int} end
* @param {Function} callback
* @return this
* @api public
*/
SortedSet.prototype.countScores = function (start, end, callback) {
if (null === start) start = '-inf';
if (null === end) end = '+inf';
this.client.zcount(this.key, start, end, callback);
return this;
}
/**
* Get elements with ranks between the specified range (inclusive).
*
* To get the first 3 elements in the set (with the highest scores):
* set.getRanks(0, 2, callback);
*
* To get the last 3 elements in the set (lowest scores):
* set.getRanks(-3, -1, callback);
*
* @param {int} start
* @param {int} end
* @param {Function} callback
* @return this
* @api public
*/
SortedSet.prototype.getRanks = function (start, end, callback) {
if (null === start) start = 0;
if (null === end) end = -1;
this.client.zrange(this.key, start, end,
'WITHSCORES', this.parseScores(callback));
return this;
}
/**
* The same as `getRanks()` but elements are ordered from lowest score
* to the highest.
*
* Note: start and end have been deliberately switched for consistency.
* getScoresReverse(arg1, arg2, ..) expects arg1 >= arg2 and so does this
* method.
*
* @param {int} end
* @param {int} start
* @param {Function} callback
* @return this
* @api public
*/
SortedSet.prototype.getRanksReverse = function (end, start, callback) {
if (null === start) start = -1;
if (null === end) end = 0;
this.client.zrevrange(this.key, start, end,
'WITHSCORES', this.parseScores(callback));
return this;
}
/**
* Remove elements with ranks between the specified range (inclusive).
*
* @param {int} start
* @param {int} end
* @param {Function} callback
* @return this
* @api public
*/
SortedSet.prototype.removeRanks = function (start, end, callback) {
if (null === start) start = -1;
if (null === end) end = 0;
this.client.zremrangebyrank(this.key, start, end, callback);
return this;
}
/**
* Get `count` elements with the highest scores.
*
* @param {int} count
* @param {Function} callback
* @return this
* @api public
*/
SortedSet.prototype.highestScores = function (count, callback) {
this.getRanks(-1 * count, -1, callback);
return this;
}
/**
* Get `count` elements with the lowest scores.
*
* @param {int} count
* @param {Function} callback
* @return this
* @api public
*/
SortedSet.prototype.lowestScores = function (count, callback) {
this.getRanks(0, count - 1, callback);
return this;
}
/**
* Get the intersection of one or more sets. For more information on weights,
* aggregate functions, etc. see: http://redis.io/commands/zinterstore
*
* @param {int} dest
* @param {string|Set|Array} set(s)
* @param {int|Array} weights (optional)
* @param {string} aggregate (optional) - either SUM, MIN or MAX
* @param {Function} callback
* @return this
* @api public
*/
SortedSet.prototype.inter = SortedSet.prototype.intersect = function (dest, sets, weights, aggregate, callback) {
var args = [], self = this;
args.push(this.getKey(dest));
//weights/aggregate are optional
if (typeof weights === 'function') {
callback = weights;
weights = aggregate = false;
} else if (typeof aggregate === 'function') {
callback = aggregate;
aggregate = false;
}
//ZINTERSTORE destination numkeys key [key ...]
// [WEIGHTS weight [weight ...]] [AGGREGATE SUM|MIN|MAX]
if (Array.isArray(sets)) {
args.push(sets.length);
sets.forEach(function (set) {
args.push(self.getKey(set));
});
} else {
args.push(1, this.getKey(sets));
}
if (weights) {
args.push('WEIGHTS');
if (Array.isArray(weights)) {
weights.forEach(function (weight) {
args.push(weight);
});
} else {
args.push(weights);
}
}
if (aggregate) {
args.push('AGGREGATE', aggregate);
}
args.push(callback);
this.client.zinterstore.apply(this.client, args);
return this;
}
/**
* Get the union of one or more sets. For more information on weights,
* aggregate functions, etc. see: http://redis.io/commands/zunionstore
*
* @param {int} dest
* @param {string|Set|Array} set(s)
* @param {int|Array} weights (optional)
* @param {string} aggregate (optional) - either SUM, MIN or MAX
* @param {Function} callback
* @return this
* @api public
*/
SortedSet.prototype.union = function (dest, sets, weights, aggregate, callback) {
var args = [], self = this;
args.push(this.getKey(dest));
//weights/aggregate are optional
if (typeof weights === 'function') {
callback = weights;
weights = aggregate = false;
} else if (typeof aggregate === 'function') {
callback = aggregate;
aggregate = false;
}
//ZUNIONSTORE destination numkeys key [key ...]
// [WEIGHTS weight [weight ...]] [AGGREGATE SUM|MIN|MAX]
if (Array.isArray(sets)) {
args.push(sets.length);
sets.forEach(function (set) {
args.push(self.getKey(set));
});
} else {
args.push(1, this.getKey(sets));
}
if (weights) {
args.push('WEIGHTS');
if (Array.isArray(weights)) {
weights.forEach(function (weight) {
args.push(weight);
});
} else {
args.push(weights);
}
}
if (aggregate) {
args.push('AGGREGATE', aggregate);
}
args.push(callback);
this.client.zunionstore.apply(this.client, args);
return this;
}