Skip to content

Commit 4aea4b9

Browse files
committed
range-list: balance most under-represented level first
1 parent 5bec3b0 commit 4aea4b9

File tree

2 files changed

+25
-6
lines changed

2 files changed

+25
-6
lines changed

ds/range-list.js

+23-4
Original file line numberDiff line numberDiff line change
@@ -225,15 +225,34 @@ export class RangeList {
225225
return level;
226226
}
227227

228+
// selects level which is max way off from what is expected
228229
levelup() {
230+
// max-diff between no. of nodes at expected at a level vs current
231+
let maxdiff = 0;
232+
// level i where max-diff is
233+
let maxi = -1;
234+
// tracks total no. of nodes across levels, from higher levels to lower
229235
let sum = 0;
236+
237+
// levels are 1 indexed, the array is 0 index, that is,
238+
// level[0] => L1, level[1] => L2, level[7] => L8, and so on
230239
for (let i = this.levelhisto.length; i > 0; i--) {
231-
const l = this.levelhisto[i - 1] - sum;
240+
// number of nodes that level i
241+
const n = this.levelhisto[i - 1] - sum;
242+
// expected number of nodes at level i, given len of the skip-list
232243
const exl = Math.round(2 ** -i * this.length);
233-
if (exl > l) return i - 1;
234-
sum += l;
244+
const diff = exl - n;
245+
if (diff > maxdiff) {
246+
maxdiff = diff;
247+
maxi = i - 1;
248+
}
249+
// a node which is on level[9] (L10) also exists at all other levels,
250+
// from 0..9 (L1..L10); that is, to get a count of nodes only on
251+
// level[0] (L1) but not on other levels, substract out the sum of
252+
// nodes on all other levels, 1..9 (L2..L10)
253+
sum += n;
235254
}
236-
return -1;
255+
return maxi;
237256
}
238257
}
239258

package.json

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
{
22
"name": "@serverless-dns/lfu-cache",
3-
"version": "3.3.3",
4-
"description": "Lfu Cache using a variant of the Clock algorithm",
3+
"version": "3.4.0",
4+
"description": "Various LFU cache implementations",
55
"main": "lfu.js",
66
"type": "module",
77
"scripts": {

0 commit comments

Comments
 (0)