UNPKG

@prezly/theme-kit-core

Version:

Data layer and utility library for developing Prezly themes with JavaScript

52 lines (49 loc) 2.11 kB
import { createSharedMemoryCache, RECORDS_LIMIT } from "./memory.mjs"; describe('createSharedMemoryCache', () => { it('should write and read keys', () => { var cache = createSharedMemoryCache(); expect(cache.get('hello', 0)).toBeUndefined(); cache.set('hello', 'world', 0); expect(cache.get('hello', 0)).toBe('world'); }); it('should delete accessed records if the current version is higher', () => { var cache = createSharedMemoryCache(); cache.set('hello', 'world', 0); expect(cache.get('hello', 0)).toBe('world'); expect(cache.get('hello', 1)).toBeUndefined(); expect(cache.get('hello', 0)).toBeUndefined(); }); it('should separate datasets by namespace', () => { var cache = createSharedMemoryCache(); var a = cache.namespace('a:'); var b = cache.namespace('b:'); a.set('hello', 'world', 0); b.set('hello', 'universe', 0); expect(cache.get('hello', 0)).toBeUndefined(); expect(a.get('hello', 0)).toBe('world'); expect(b.get('hello', 0)).toBe('universe'); }); it('should garbage-collect old cache records when threshold is reached (with a chance of 1/100)', () => { var cache = createSharedMemoryCache(); for (var i = 0; i < RECORDS_LIMIT; i += 1) { cache.set("record-".concat(i), "value-".concat(i), 0); } for (var _i = 0; _i < RECORDS_LIMIT; _i += 1) { expect(cache.get("record-".concat(_i), 0)).toBe("value-".concat(_i)); } // Write 10% more records, 10 times to trigger CG for (var repeat = 0; repeat < 100; repeat += 1) { for (var _i2 = RECORDS_LIMIT; _i2 < RECORDS_LIMIT * 1.1; _i2 += 1) { cache.set("record-".concat(_i2), "value-".concat(_i2), 0); } } // the oldest part of the cache should be removed already for (var _i3 = 0; _i3 < RECORDS_LIMIT * 0.09; _i3 += 1) { expect(cache.get("record-".concat(_i3), 0)).toBeUndefined(); } // and the rest kept for (var _i4 = RECORDS_LIMIT * 0.11; _i4 < RECORDS_LIMIT * 1.1; _i4 += 1) { expect(cache.get("record-".concat(_i4), 0)).toBe("value-".concat(_i4)); } }); });