1 | const hasOwnProperty = Object.prototype.hasOwnProperty;
|
2 | const EMPTY = { };
|
3 |
|
4 | module.exports = MUIDStore;
|
5 |
|
6 | function MUIDStore(toKey)
|
7 | {
|
8 | this.toKey = toKey;
|
9 | this.MUIDs = Object.create(null);
|
10 | this.future = key => get(key, this);
|
11 | }
|
12 |
|
13 | MUIDStore.prototype.for = function (value)
|
14 | {
|
15 | const muid = get(this.toKey(value), this);
|
16 |
|
17 | if (muid.value === EMPTY)
|
18 | muid.value = value;
|
19 |
|
20 | return muid;
|
21 | }
|
22 |
|
23 | function get(key, store)
|
24 | {
|
25 | const muid = store.MUIDs[key] || (store.MUIDs[key] = new MUID());
|
26 |
|
27 | ++muid.count;
|
28 |
|
29 | return muid;
|
30 | }
|
31 |
|
32 | MUIDStore.prototype.finalize = function ()
|
33 | {
|
34 | const MUIDs = this.MUIDs;
|
35 |
|
36 | return Object.keys(MUIDs)
|
37 | .sort((lhs, rhs) => MUIDs[rhs].count - MUIDs[lhs].count)
|
38 | .map(function (key, index)
|
39 | {
|
40 | MUIDs[key].position = index;
|
41 |
|
42 | return MUIDs[key].value;
|
43 | });
|
44 | }
|
45 |
|
46 | function MUID(value)
|
47 | {
|
48 | this.value = EMPTY;
|
49 | this.count = 0;
|
50 | this.position = -1;
|
51 | }
|
52 |
|
53 | MUID.prototype.toJSON = function()
|
54 | {
|
55 | return this.position;
|
56 | } |
\ | No newline at end of file |