Syntax previewClick to edit
12345
export default function createTtlStorage(storage, now = () => Date.now()) {
// TODO: return { set, get, remove } with TTL behavior
throw new Error('Not implemented');
}
Syntax previewClick to edit
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
import createTtlStorage from './createTtlStorage';
function makeStorage() {
const map = new Map();
return {
getItem: (k) => (map.has(k) ? map.get(k) : null),
setItem: (k, v) => { map.set(k, String(v)); },
removeItem: (k) => { map.delete(k); },
_map: map
};
}
describe('createTtlStorage', () => {
test('stores and retrieves values without ttl', () => {
const store = makeStorage();
const cache = createTtlStorage(store, () => 0);
cache.set('a', { x: 1 });
expect(cache.get('a')).toEqual({ x: 1 });
});
test('expires values after ttl', () => {
const store = makeStorage();
let t = 0;
const cache = createTtlStorage(store, () => t);
cache.set('a', 'ok', 10);
expect(cache.get('a')).toBe('ok');
t = 10;
expect(cache.get('a')).toBe(null);
});
test('removes corrupted JSON entries', () => {
const store = makeStorage();
store.setItem('bad', '{not json');
const cache = createTtlStorage(store, () => 0);
expect(cache.get('bad')).toBe(null);
expect(store.getItem('bad')).toBe(null);
});
test('remove deletes key', () => {
const store = makeStorage();
const cache = createTtlStorage(store, () => 0);
cache.set('x', 1);
cache.remove('x');
expect(cache.get('x')).toBe(null);
});
});
Run tests to see results.