Skip to content

Commit

Permalink
feat(filters): choose filter in one-hit-wonder decorator
Browse files Browse the repository at this point in the history
  • Loading branch information
zhibirc committed Dec 13, 2023
1 parent 2d27b08 commit 26a42fd
Show file tree
Hide file tree
Showing 3 changed files with 62 additions and 4 deletions.
34 changes: 30 additions & 4 deletions libs/decorators/detect-one-hit-wonder.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,36 @@
/**
* Detect one-hit-wonder objects.
*/

import BloomFilter from '../filters/bloom';
import CuckooFilter from '../filters/cuckoo';

const TYPE_FILTER_MAP = Symbol('TYPE_FILTER_MAP');
const TYPE_FILTER_BLOOM = Symbol('TYPE_FILTER_BLOOM');
const TYPE_FILTER_CUCKOO = Symbol('TYPE_FILTER_CUCKOO');

const detectOneHitWonder = (() => {
const hitCount = new Map();
let filter;

return (threshold: number = 1) => {
return (threshold: number = 1, filterType: symbol = TYPE_FILTER_MAP) => {
return function (originalMethod: any, _context: ClassMethodDecoratorContext) {
function replacementMethod(this: any, key: any, value?: any) {
let n = hitCount.get(key) ?? 0;
const { capacity } = this.stats;

switch (filterType) {
case TYPE_FILTER_MAP:
filter = new Map();
break;
case TYPE_FILTER_BLOOM:
filter = new BloomFilter(capacity);
break;
case TYPE_FILTER_CUCKOO:
filter = new CuckooFilter(capacity);
break;
}
let n = filter.get(key) ?? 0;

hitCount.set(key, ++n);
filter.set(key, ++n);

switch (originalMethod.name) {
case 'read':
Expand All @@ -27,4 +48,9 @@ const detectOneHitWonder = (() => {
})();


export {
TYPE_FILTER_MAP,
TYPE_FILTER_BLOOM,
TYPE_FILTER_CUCKOO
};
export default detectOneHitWonder;
18 changes: 18 additions & 0 deletions libs/filters/bloom/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
class BloomFilter {
#store;

constructor(capacity: number) {
if (!Number.isInteger(capacity) || capacity <= 0) {
throw new Error('invalid "capacity": positive integer expected');
}

this.#store = new Uint8Array(capacity);
}

set(key: string) {}

get(key: string) {}
}


export default BloomFilter;
14 changes: 14 additions & 0 deletions libs/filters/cuckoo/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
class CuckooFilter {
constructor(capacity: number) {
if (!Number.isInteger(capacity) || capacity <= 0) {
throw new Error('invalid "capacity": positive integer expected');
}
}

set(key: string) {}

get(key: string) {}
}


export default CuckooFilter;

0 comments on commit 26a42fd

Please sign in to comment.