-
Notifications
You must be signed in to change notification settings - Fork 628
/
Copy pathpartitioner.js
68 lines (52 loc) · 1.84 KB
/
partitioner.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
'use strict';
var util = require('util');
var _ = require('lodash');
var Partitioner = function () {};
var DefaultPartitioner = function () {};
util.inherits(DefaultPartitioner, Partitioner);
DefaultPartitioner.prototype.getPartition = function (partitions) {
if (partitions && _.isArray(partitions) && partitions.length > 0) {
return partitions[0];
} else {
return 0;
}
};
var CyclicPartitioner = function () {
this.c = 0;
};
util.inherits(CyclicPartitioner, Partitioner);
CyclicPartitioner.prototype.getPartition = function (partitions) {
if (_.isEmpty(partitions)) return 0;
return partitions[ this.c++ % partitions.length ];
};
var RandomPartitioner = function () {};
util.inherits(RandomPartitioner, Partitioner);
RandomPartitioner.prototype.getPartition = function (partitions) {
return partitions[Math.floor(Math.random() * partitions.length)];
};
var KeyedPartitioner = function () {};
util.inherits(KeyedPartitioner, Partitioner);
// Taken from oid package (Dan Bornstein)
// Copyright The Obvious Corporation.
KeyedPartitioner.prototype.hashCode = function (string) {
var hash = 0;
var length = string.length;
for (var i = 0; i < length; i++) {
hash = ((hash * 31) + string.charCodeAt(i)) & 0x7fffffff;
}
return (hash === 0) ? 1 : hash;
};
KeyedPartitioner.prototype.getPartition = function (partitions, key) {
key = key || '';
var index = this.hashCode(key) % partitions.length;
return partitions[index];
};
var CustomPartitioner = function (partitioner) {
this.getPartition = partitioner;
};
util.inherits(CustomPartitioner, Partitioner);
module.exports.DefaultPartitioner = DefaultPartitioner;
module.exports.CyclicPartitioner = CyclicPartitioner;
module.exports.RandomPartitioner = RandomPartitioner;
module.exports.KeyedPartitioner = KeyedPartitioner;
module.exports.CustomPartitioner = CustomPartitioner;