diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 9ee85a38..6bba3118 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -3,15 +3,19 @@ name: Tests on: [push, pull_request] jobs: + tests: strategy: matrix: + # npm will not run under 10.x or earlier and so they cannot be tested node-version: - 12.x - 13.x - 14.x - 15.x - 16.x + - 18.x + - latest runs-on: ubuntu-latest diff --git a/CHANGELOG.md b/CHANGELOG.md index 95d47fcc..3b2a0c6b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,9 @@ # Changelog +## 0.40.0 + +* Adding `#isEqual` to Set helpers (@mrflip). (provisional) + ## 0.39.2 * Fixing typings of low-level structure consuming methods (@jerome-benoit). diff --git a/index.d.ts b/index.d.ts index abaef492..294d390f 100644 --- a/index.d.ts +++ b/index.d.ts @@ -27,6 +27,7 @@ export {default as KDTree} from './kd-tree'; export {default as LinkedList} from './linked-list'; export {default as LRUCache} from './lru-cache'; export {default as LRUCacheWithDelete} from './lru-cache-with-delete'; +export {default as LRUCacheWithExpiry} from './lru-cache-with-expiry'; export {default as LRUMap} from './lru-map'; export {default as LRUMapWithDelete} from './lru-map-with-delete'; export {default as MultiMap} from './multi-map'; diff --git a/index.js b/index.js index 75bf74e9..c2351bca 100644 --- a/index.js +++ b/index.js @@ -36,6 +36,7 @@ module.exports = { LinkedList: require('./linked-list.js'), LRUCache: require('./lru-cache.js'), LRUCacheWithDelete: require('./lru-cache-with-delete.js'), + LRUCacheWithExpiry: require('./lru-cache-with-expiry.js'), LRUMap: require('./lru-map.js'), LRUMapWithDelete: require('./lru-map-with-delete.js'), MultiMap: require('./multi-map.js'), diff --git a/lru-cache-with-delete.js b/lru-cache-with-delete.js index b0fd12e3..ad8d6896 100644 --- a/lru-cache-with-delete.js +++ b/lru-cache-with-delete.js @@ -35,8 +35,21 @@ function LRUCacheWithDelete(Keys, Values, capacity) { for (var k in LRUCache.prototype) LRUCacheWithDelete.prototype[k] = LRUCache.prototype[k]; -if (typeof Symbol !== 'undefined') + +/** + * If possible, attaching the + * * #.entries method to Symbol.iterator (allowing `for (const foo of cache) { ... }`) + * * the summaryString method to Symbol.toStringTag (allowing `\`${cache}\`` to work) + * * the inspect method to Symbol.for('nodejs.util.inspect.custom') (making `console.log(cache)` liveable) + */ +if (typeof Symbol !== 'undefined') { LRUCacheWithDelete.prototype[Symbol.iterator] = LRUCache.prototype[Symbol.iterator]; + Object.defineProperty(LRUCacheWithDelete.prototype, Symbol.toStringTag, { + get: function () { return `${this.constructor.name}:${this.size}/${this.capacity}`; }, + }); + LRUCacheWithDelete.prototype[Symbol.for('nodejs.util.inspect.custom')] = LRUCache.prototype.inspect; +} +Object.defineProperty(LRUCacheWithDelete.prototype, 'summary', Object.getOwnPropertyDescriptor(LRUCache.prototype, 'summary')); /** * Method used to clear the structure. diff --git a/lru-cache-with-expiry.d.ts b/lru-cache-with-expiry.d.ts new file mode 100644 index 00000000..4b1c95e5 --- /dev/null +++ b/lru-cache-with-expiry.d.ts @@ -0,0 +1,24 @@ +/** + * Mnemonist LRUCacheWithExpiry Typings + * ===================================== + */ +import LRUCacheWithDelete from './lru-cache-with-delete'; + +export interface Logger { + trace(message: string, story: any): void + debug(message: string, story: any): void + info(message: string, story: any): void + warn(message: string, story: any): void + error(message: string, story: any): void +} + +export default class LRUCacheWithExpiry extends LRUCacheWithDelete { + + expire(): void; + + monitor(interval: number, options: { + logger: Logger, + didError: (err: Error, inst: LRUCacheWithExpiry) => boolean, + didExpire: (inst: LRUCacheWithExpiry, begT: number) => void, + }): void; +} diff --git a/lru-cache-with-expiry.js b/lru-cache-with-expiry.js new file mode 100644 index 00000000..b391eb9f --- /dev/null +++ b/lru-cache-with-expiry.js @@ -0,0 +1,365 @@ +/** + * Mnemonist LRUCacheWithExpiry + * ============================= + * + * An extension of LRUCache with time expiry + */ + +var LRUCacheWithDelete = require('./lru-cache-with-delete.js'), + forEach = require('obliterator/foreach'), + // typed = require('./utils/typed-arrays.js'), + iterables = require('./utils/iterables.js'); + +// +// This adds time-to-keep expiration to the LRUCacheWithDelete. +// +// Besides the other ledgers of the backing cache, on every write +// operation the update time is saved in a fixed-sized array. No other +// speed or memory overhead is required for regular operations: most +// importantly, that means there is no age verification on +// read. Customer must periodically call the expire method, which +// evicts items older than the time-to-keep. +// +// The target use case is a 15-minute time-to-keep on caches of 64k +// capacity, where we can tolerate a modest slop in expiration and +// small periodic expiry sweeps. The benchmark script demonstrates a +// 1M-element cache with a 10s ttk being expired every 2 seconds, +// spending 50-60ms on each expiry sweep. I don't know what use case +// would need those extremes but there you go. +// +// Limitations: +// +// * The time-to-live (maximum age of any record returned in a read +// operation) has only the weak guarantee of `(time-to-keep + +// maximum-delay-between-expires)`. +// +// * The expire operation must be done as a whole, and this does not +// offer to do it in a separate thread or make any attempt to be +// thread safe. However, the benchmarks in `benchmark/lru-cache` +// show that a full delete of every item in a 30,000 element cache +// runs in less than 10ms on a 2019 Macbook Pro. +// +// * Having two expire operations scheduled in the same +// thread should be harmless but would give no speedup, so if you +// found yourself in a situation where the expire was taking +// significant time it could be big trouble. +// +// * Due to floating-point shenanigans a custom clock returning +// fractional times may behave unexpectedly. +// +// Alternatives considered and discarded: +// +// * Rather than walking the full length of the age ledger (or linked +// list), keep a data structure (heap?) to reveal only the expirable +// records. This could shorten expiry times in general but I'd worry +// that if there was a large batch to expire the time spent grooming +// the heap could swamp the typical-case savings. +// +// * Maintain two or more generations of cached items, rotating then +// at ttl/2. (write to both, read from the new generation falling +// back to the old generation, and on each expire discard the oldest +// generation and add a new empty cache). This would make expiry +// O(1), with low impact on individual operations but a notable +// tradeoff in cache efficiency. +// +// * Checking the age on read would significantly impact the read performance. +// +// Potential Opportunities for improvement: +// +// * Reduce the memory footprint of the age ledger by chunking the +// timestamps to bytes or words. In the case of byte (256 age +// bins), a 10-minute ttk, and otherwise default parameters, an +// expire operation would discard everything older than (ttk - +// ttk/64) (guaranteeing the ttk but reaping an additional 1.5% of +// records). Expire must be called at least once every `2 * ttk` (20 +// minutes) or the newest records would be indistinguishable from +// the oldest records. (Everything would work but it would be a damn +// shame for cache efficiency). A word-sized (64k bins) ledger makes +// the tradeoffs minimal, but offering both choices shouldn't be a +// problem. +// +// * For every record it expires we independently call delete, which +// doctors the read-age linked list. It may make more sense to walk +// the linked list. +// + +/** + * + * LRU cache with time-to-keep expiration + * + * Trades fast read/writes for guarantees on timely expiration or fast + * expiration loops. + * + * @param {Iterable} iterable - Target iterable. + * @param {function} Keys - Array class for storing keys. + * @param {function} Values - Array class for storing values. + * @param {number} capacity - Cache's capacity. + * @param {object} capacity - Configuration + * @param {function} [options.getTime = Date.now] - replaces the meaning of time (for mocking and to allow eg a vector clock). Will be called with the object and action as parameters. + * @param {number} [options.ttk = 15 minutes] - when expire is called all items whose update time is older than ttk milliseconds will be deleted. Other items may be as well, depending on implementation. + * + * @return {LRUCacheWithExpiry} + */ +function LRUCacheWithExpiry(Keys, Values, capacity, options = {}) { + if (arguments.length <= 1) { + options = {}; capacity = Keys; + LRUCacheWithDelete.call(this, capacity); + } + else if (arguments.length <= 2) { + options = Values; capacity = Keys; + LRUCacheWithDelete.call(this, capacity); + } + else { + LRUCacheWithDelete.call(this, Keys, Values, capacity); + } + if (options.ttl || options.ttl === 0) { + throw new Error('Please supply options.ttk (time-to-**keep**), not ttl (and understand the difference)'); + } + this.getTime = options.getTime || Date.now; + this.ttk = options.ttk || LRUCacheWithExpiry.minutes(15); + this.ages = new Float64Array(this.capacity); + // + this.initT = this.getTime('init', this); + this.lastT = this.initT; +} + +// FIXME: remove? +LRUCacheWithExpiry.prototype.investigate = function(...args) { + // eslint-disable-next-line no-console + console.log(this.inspect({all: true}), ...args); +}; + +/** + * LRUCacheWithExpiry inherits from LRUCacheWithDelete + */ + +for (var k in LRUCacheWithDelete.prototype) + LRUCacheWithExpiry.prototype[k] = LRUCacheWithDelete.prototype[k]; + +/** + * If possible, attaching the + * * #.entries method to Symbol.iterator (allowing `for (const foo of cache) { ... }`) + * * the summaryString method to Symbol.toStringTag (allowing `\`${cache}\`` to work) + */ +if (typeof Symbol !== 'undefined') { + LRUCacheWithExpiry.prototype[Symbol.iterator] = LRUCacheWithDelete.prototype[Symbol.iterator]; + Object.defineProperty(LRUCacheWithExpiry.prototype, Symbol.toStringTag, { + get: function () { return `${this.constructor.name}:${this.size}/${this.capacity}`; }, + }); +} +Object.defineProperty(LRUCacheWithExpiry.prototype, 'summary', Object.getOwnPropertyDescriptor(LRUCacheWithDelete.prototype, 'summary')); + +/** + * Method used to set the value for the given key in the cache. + * + * @param {any} key - Key. + * @param {any} value - Value. + * @return {undefined} + */ +LRUCacheWithExpiry.prototype.set = function(key, value) { + LRUCacheWithDelete.prototype.set.call(this, key, value); + var pointer = this.items[key]; + this.ages[pointer] = this.getTime('set', this); +}; + +/** + * Method used to set the value for the given key in the cache + * + * @param {any} key - Key. + * @param {any} value - Value. + * @return {{evicted: boolean, key: any, value: any}} An object containing the + * key and value of an item that was overwritten or evicted in the set + * operation, as well as a boolean indicating whether it was evicted due to + * limited capacity. Return value is null if nothing was evicted or overwritten + * during the set operation. + */ +LRUCacheWithExpiry.prototype.setpop = function(key, value) { + var result = LRUCacheWithDelete.prototype.setpop.call(this, key, value); + var pointer = this.items[key]; + this.ages[pointer] = this.getTime('set', this); + return result; +}; + +/** + * All items written before curfew time are due for expiry + */ +Object.defineProperty(LRUCacheWithExpiry.prototype, 'curfew', { + get() { return this.getTime('check', this) - this.ttk; } +}); + +/** + * Duration of time since last expiration + */ +Object.defineProperty(LRUCacheWithExpiry.prototype, 'sinceExpiry', { + get() { return this.getTime('check', this) - this.lastT; } +}); + +/** + * Delete all cached items older than this.ttk + */ +LRUCacheWithExpiry.prototype.expire = function() { + this.getTime('startExpire', this); + var curfew = this.curfew; + var ii; + for (ii = 0; ii < this.capacity; ii++) { + if (this.ages[ii] <= curfew) { + this.delete(this.K[ii]); + } + } + this.lastT = this.getTime('doneExpire', this); +}; + +// /** +// * Delete all cached items older than this.ttk +// */ +// LRUCacheWithExpiry.prototype.expireUsingLinkedList = function() { +// var currT = this.getTime('startExpire', this); +// var curfew = this.curfew +// // TODO: are there savings from unwinding the delete op into this? +// var pointer = this.head; +// while ((pointer !== this.tail) && (this.size > 1)) { +// if (this.ages[pointer] < curfew) { +// console.log('del', pointer, this.V[pointer], this.ages[pointer]); +// this.delete(this.K[pointer]); +// } else { +// this.pointer = this.backward[pointer] +// } +// } +// }; + +/** + * + * Method used to start an asynchronous monitor that calls #expire() + * on the given milliseconds interval. Supply an optional didError to + * receive any errors thrown during expiry. Unless you supply that + * callback and it returns true, the error will be re-thrown. + * + * Repeated calls to monitor will clear any previous timers. + * + * @param {number} interval - milliseconds between expire() calls + * @param {object} options - configuration + * @param {function} [options.didExpire] - will be invoked as didExpire(this, begT) with the millis timestamp immediately before calling expire. By default logs the duration of expire. + * @param {function} [options.didError] - will be invoked as didError(error, this) on any error. + * @param {function} [options.logger = console] - used to emit log messages. + * + * The return value of this method is unspecified. Use .stopMonitor to + * remove the monitor. + */ +LRUCacheWithExpiry.prototype.monitor = function(interval, options = {}) { + var self = this; + var logger = options.logger || console; + var name = options.name || this.constructor.name; + var begT; + var didError = options.didError || function(err, inst) { + logger.error(`Error in ${name}.expire: ${err}`, {err, cache: inst.inspect()}); + return false; + }; + var didExpire = options.didExpire || function(inst, facts) { + var endT = Date.now(); + logger.debug(`${name}.expire: ${endT - facts.begT} ${facts.begDeletedSize} ${self.deletedSize}`); + }; + // set up a very paranoid method to run in the background, presumably forever. + var doExpire = function () { + try { + begT = Date.now(); + var {deletedSize: begDeletedSize, lastT: begLastT} = self; + self.expire(); + didExpire(self, {begT, begDeletedSize, begLastT}); + } catch (err) { + try { + var handled = didError(err, self); + if (handled) { return; } + } catch (errInHandler) { logger.error(`Double error ${errInHandler} in handler for ${self}`, errInHandler); } // eslint-disable-line no-console + try { + self.stopMonitor('error'); + } catch (errStoppingMonitor) { console.error('Cascading error in expiration monitor', errStoppingMonitor); } // eslint-disable-line no-console + throw err; + } + }; + // kill any previous monitors and start the new one running on given interval. + this.stopMonitor('starting'); + this.timer = setInterval(doExpire, interval); + return this.timer; // lets tests cancel the timer directly; you should use stopMonitor() +}; + +/** + * Provide a reasonably-sized view of the object. + * + * @param {number} [depth] - When < 0, only the toString() summary is returned + * @param {object} [options = {}] - settings for output + * @param {boolean} [options.all = false] - When true, returns the object with all properties, ignoring limits + * @param {number} [options.maxToDump = 20] - When size > maxToDump, lists only the + * youngest `maxToDump - 2`, a placeholder with the number + * omitted, and the single oldest item. The secret variable + * LRUCache.defaultMaxToDump determines the default limit. + * @return {Map} + * + */ +LRUCacheWithExpiry.prototype.inspect = function(depth, options = {}) { + if (arguments.length <= 1) { options = depth || {}; depth = 2; } + var inspected = LRUCacheWithDelete.prototype.inspect.call(this, depth, options); + if (options.all) { return inspected; } + const {ttk, initT, lastT, deletedSize, curfew, sinceExpiry} = this; + Object.assign(inspected, {ttk, initT, lastT, deletedSize, curfew, sinceExpiry}); + return inspected; +}; + +if (typeof Symbol !== 'undefined') + LRUCacheWithExpiry.prototype[Symbol.for('nodejs.util.inspect.custom')] = LRUCacheWithExpiry.prototype.inspect; + +/* + * Helper to convert given number of minutes to milliseconds + */ +LRUCacheWithExpiry.minutes = function(mins) { return 1000 * 60 * mins; }; + +/** + * + * Method used to stop the monitor, if any. + * NOTE: you must ensure that this method is not stripped of its this: + * setTimeout(cache.stopMonitor, 100000) // WILL THROW + * setTimeout(() => cache.stopMonitor, 100000) // WILL WORK + */ +LRUCacheWithExpiry.prototype.stopMonitor = function() { + if (! (/LRU/.test(this.constructor.name))) { + throw new Error('cache.stopMonitor called with this-less bindings'); + } + if (this.timer) { + clearInterval(this.timer); + this.timer = null; + } +}; + +/** + * Static @.from function taking an arbitrary iterable & converting it into + * a structure. + * + * @param {Iterable} iterable - Target iterable. + * @param {function} Keys - Array class for storing keys. + * @param {function} Values - Array class for storing values. + * @param {number} capacity - Cache's capacity. + * @return {LRUCacheWithExpiry} + */ +LRUCacheWithExpiry.from = function(iterable, Keys, Values, capacity, options) { + if (arguments.length < 2) { + capacity = iterables.guessLength(iterable); + + if (typeof capacity !== 'number') + throw new Error('mnemonist/lru-cache.from: could not guess iterable length. Please provide desired capacity as last argument.'); + } + else if (arguments.length === 2) { + capacity = Keys; + Keys = null; + Values = null; + options = {}; + } + + var cache = new LRUCacheWithExpiry(Keys, Values, capacity, options); + + forEach(iterable, function(value, key) { + cache.set(key, value); + }); + + return cache; +}; + +module.exports = LRUCacheWithExpiry; diff --git a/lru-cache.js b/lru-cache.js index d87a4d4e..860d65f1 100644 --- a/lru-cache.js +++ b/lru-cache.js @@ -18,7 +18,8 @@ var Iterator = require('obliterator/iterator'), forEach = require('obliterator/foreach'), typed = require('./utils/typed-arrays.js'), - iterables = require('./utils/iterables.js'); + iterables = require('./utils/iterables.js'), + {snipToLast} = require('./utils/snip.js'); /** * LRUCache. @@ -368,29 +369,64 @@ LRUCache.prototype.entries = function() { }); }; +/** + * No-op for compatibility with time-expirable caches + */ +LRUCache.prototype.expire = function () { /**/ }; + +/** + * Return a short string for interpolation: `LRUCache:size/capacity` + */ +Object.defineProperty(LRUCache.prototype, 'summary', { + get: function() { return `${this.constructor.name}:${this.size}/${this.capacity}`; }, +}); + /** * Attaching the #.entries method to Symbol.iterator if possible. */ -if (typeof Symbol !== 'undefined') +if (typeof Symbol !== 'undefined') { LRUCache.prototype[Symbol.iterator] = LRUCache.prototype.entries; + Object.defineProperty(LRUCache.prototype, Symbol.toStringTag, { + get: function () { return this.summary; }, + }); +} + +LRUCache.defaultMaxToDump = 20; /** - * Convenience known methods. + * Provide a reasonably-sized view of the object. + * + * @param {number} [depth] - When < 0, only the toString() summary is returned + * @param {object} [options = {}] - settings for output + * @param {boolean} [options.all = false] - When true, returns the object with all properties, ignoring limits + * @param {number} [options.maxToDump = 20] - When size > maxToDump, lists only the + * youngest `maxToDump - 2`, a placeholder with the number + * omitted, and the single oldest item. The secret variable + * LRUCache.defaultMaxToDump determines the default limit. + * @return {Map} + * */ -LRUCache.prototype.inspect = function() { +LRUCache.prototype.inspect = function(depth, options = {}) { + if (arguments.length <= 1) { options = depth || {}; depth = 2; } + if (options.all) { var ret = {}; Object.assign(ret, this); return ret; } + if (depth < 0) { return this.toString(); } + var maxToDump = options.maxToDump || LRUCache.defaultMaxToDump; var proxy = new Map(); - var iterator = this.entries(), - step; - - while ((step = iterator.next(), !step.done)) - proxy.set(step.value[0], step.value[1]); + var last = [this.K[this.tail], this.V[this.tail]]; + snipToLast(this.entries(), proxy, {maxToDump, size: this.size, last}); - // Trick so that node displays the name of the constructor + // Trick so that node displays the name of the constructor (does not work in modern node) Object.defineProperty(proxy, 'constructor', { value: LRUCache, enumerable: false }); + if (typeof Symbol !== 'undefined') { + var self = this; + Object.defineProperty(proxy, Symbol.toStringTag, { + get: function () { return `${self.constructor.name}:${self.size}/${self.capacity}`; }, + }); + } return proxy; }; diff --git a/lru-map-with-delete.js b/lru-map-with-delete.js index 0e58fa76..4d9397bc 100644 --- a/lru-map-with-delete.js +++ b/lru-map-with-delete.js @@ -35,8 +35,21 @@ function LRUMapWithDelete(Keys, Values, capacity) { for (var k in LRUMap.prototype) LRUMapWithDelete.prototype[k] = LRUMap.prototype[k]; -if (typeof Symbol !== 'undefined') + +/** + * If possible, attaching the + * * #.entries method to Symbol.iterator (allowing `for (const foo of cache) { ... }`) + * * the summaryString method to Symbol.toStringTag (allowing `\`${cache}\`` to work) + * * the inspect method to Symbol.for('nodejs.util.inspect.custom') (making `console.log(cache)` liveable) + */ +if (typeof Symbol !== 'undefined') { LRUMapWithDelete.prototype[Symbol.iterator] = LRUMap.prototype[Symbol.iterator]; + Object.defineProperty(LRUMapWithDelete.prototype, Symbol.toStringTag, { + get: function () { return `${this.constructor.name}:${this.size}/${this.capacity}`; }, + }); + LRUMapWithDelete.prototype[Symbol.for('nodejs.util.inspect.custom')] = LRUMap.prototype.inspect; +} +Object.defineProperty(LRUMapWithDelete.prototype, 'summary', Object.getOwnPropertyDescriptor(LRUMap.prototype, 'summary')); /** * Method used to clear the structure. diff --git a/lru-map.js b/lru-map.js index 87f7aa38..0c4fac62 100644 --- a/lru-map.js +++ b/lru-map.js @@ -211,17 +211,29 @@ LRUMap.prototype.forEach = LRUCache.prototype.forEach; LRUMap.prototype.keys = LRUCache.prototype.keys; LRUMap.prototype.values = LRUCache.prototype.values; LRUMap.prototype.entries = LRUCache.prototype.entries; +LRUMap.prototype.summaryString = LRUCache.prototype.summaryString; +LRUMap.prototype.expire = LRUCache.prototype.expire; +LRUMap.prototype.investigate = LRUCache.prototype.investigate; /** - * Attaching the #.entries method to Symbol.iterator if possible. + * Inherit methods */ -if (typeof Symbol !== 'undefined') - LRUMap.prototype[Symbol.iterator] = LRUMap.prototype.entries; +LRUMap.prototype.inspect = LRUCache.prototype.inspect; /** - * Convenience known methods. + * If possible, attaching the + * * #.entries method to Symbol.iterator (allowing `for (const foo of cache) { ... }`) + * * the summaryString method to Symbol.toStringTag (allowing `\`${cache}\`` to work) + * * the inspect method to Symbol.for('nodejs.util.inspect.custom') (making `console.log(cache)` liveable) */ -LRUMap.prototype.inspect = LRUCache.prototype.inspect; +if (typeof Symbol !== 'undefined') { + LRUMap.prototype[Symbol.iterator] = LRUMap.prototype.entries; + Object.defineProperty(LRUMap.prototype, Symbol.toStringTag, { + get: function () { return `${this.constructor.name}:${this.size}/${this.capacity}`; }, + }); + LRUMap.prototype[Symbol.for('nodejs.util.inspect.custom')] = LRUCache.prototype.inspect; +} +Object.defineProperty(LRUMap.prototype, 'summary', Object.getOwnPropertyDescriptor(LRUCache.prototype, 'summary')); /** * Static @.from function taking an arbitrary iterable & converting it into diff --git a/package-lock.json b/package-lock.json index 821609e9..c6995a47 100644 --- a/package-lock.json +++ b/package-lock.json @@ -16,6 +16,7 @@ "asciitree": "^1.0.2", "damerau-levenshtein": "^1.0.7", "eslint": "^8.2.0", + "eslint-plugin-mocha": "^10.1.0", "leven": "^3.1.0", "lodash": "^4.17.21", "matcha": "^0.7.0", @@ -537,6 +538,22 @@ "url": "https://opencollective.com/eslint" } }, + "node_modules/eslint-plugin-mocha": { + "version": "10.1.0", + "resolved": "https://registry.npmjs.org/eslint-plugin-mocha/-/eslint-plugin-mocha-10.1.0.tgz", + "integrity": "sha512-xLqqWUF17llsogVOC+8C6/jvQ+4IoOREbN7ZCHuOHuD6cT5cDD4h7f2LgsZuzMAiwswWE21tO7ExaknHVDrSkw==", + "dev": true, + "dependencies": { + "eslint-utils": "^3.0.0", + "rambda": "^7.1.0" + }, + "engines": { + "node": ">=14.0.0" + }, + "peerDependencies": { + "eslint": ">=7.0.0" + } + }, "node_modules/eslint-scope": { "version": "6.0.0", "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-6.0.0.tgz", @@ -1410,6 +1427,12 @@ "node": ">=6" } }, + "node_modules/rambda": { + "version": "7.2.1", + "resolved": "https://registry.npmjs.org/rambda/-/rambda-7.2.1.tgz", + "integrity": "sha512-Wswj8ZvzdI3VhaGPkZAxaCTwuMmGtgWt7Zxsgyo4P+iTmVnkojvyWaOep5q3ZjMIecW0wtQa66GWxaKkZ24RAA==", + "dev": true + }, "node_modules/randombytes": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/randombytes/-/randombytes-2.1.0.tgz", @@ -2238,6 +2261,16 @@ "v8-compile-cache": "^2.0.3" } }, + "eslint-plugin-mocha": { + "version": "10.1.0", + "resolved": "https://registry.npmjs.org/eslint-plugin-mocha/-/eslint-plugin-mocha-10.1.0.tgz", + "integrity": "sha512-xLqqWUF17llsogVOC+8C6/jvQ+4IoOREbN7ZCHuOHuD6cT5cDD4h7f2LgsZuzMAiwswWE21tO7ExaknHVDrSkw==", + "dev": true, + "requires": { + "eslint-utils": "^3.0.0", + "rambda": "^7.1.0" + } + }, "eslint-scope": { "version": "6.0.0", "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-6.0.0.tgz", @@ -2894,6 +2927,12 @@ "integrity": "sha512-XRsRjdf+j5ml+y/6GKHPZbrF/8p2Yga0JPtdqTIY2Xe5ohJPD9saDJJLPvp9+NSBprVvevdXZybnj2cv8OEd0A==", "dev": true }, + "rambda": { + "version": "7.2.1", + "resolved": "https://registry.npmjs.org/rambda/-/rambda-7.2.1.tgz", + "integrity": "sha512-Wswj8ZvzdI3VhaGPkZAxaCTwuMmGtgWt7Zxsgyo4P+iTmVnkojvyWaOep5q3ZjMIecW0wtQa66GWxaKkZ24RAA==", + "dev": true + }, "randombytes": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/randombytes/-/randombytes-2.1.0.tgz", diff --git a/package.json b/package.json index 4efe74d4..150dfb9e 100644 --- a/package.json +++ b/package.json @@ -5,7 +5,7 @@ "scripts": { "lint": "eslint --cache ./*.js ./utils ./test", "lint:fix": "eslint --cache --fix ./*.js ./utils ./test", - "prepublishOnly": "npm run lint && npm test && npm run test:types", + "prepublishOnly": "npm run lint && npm test && npm run test:types && echo 'Success! All checks passed!'", "test": "mocha", "test:types": "tsc --target es2015 --noEmit --noImplicitAny --noImplicitReturns ./test/types.ts" }, @@ -80,6 +80,7 @@ "asciitree": "^1.0.2", "damerau-levenshtein": "^1.0.7", "eslint": "^8.2.0", + "eslint-plugin-mocha": "^10.1.0", "leven": "^3.1.0", "lodash": "^4.17.21", "matcha": "^0.7.0", @@ -90,7 +91,10 @@ "typescript": "^4.5.2" }, "eslintConfig": { - "extends": "@yomguithereal/eslint-config", + "extends": [ + "plugin:mocha/recommended", + "@yomguithereal/eslint-config" + ], "parserOptions": { "ecmaVersion": 6, "ecmaFeatures": { @@ -98,6 +102,8 @@ } }, "rules": { + "mocha/no-identical-title": 0, + "mocha/no-setup-in-describe": 0, "no-new": 0 } } diff --git a/set.js b/set.js index e0d020bb..8188e01c 100644 --- a/set.js +++ b/set.js @@ -181,6 +181,33 @@ exports.isSubset = function(A, B) { return true; }; + +/** + * Function returning whether A equals B (same size and B has all elements of A) + * + * @param {Set} A - First set. + * @param {Set} B - Second set. + * @return {boolean} + */ +exports.isEqual = function(A, B) { + var iterator = A.values(), + step; + + // Shortcuts + if (A === B) + return true; + + if (A.size !== B.size) + return false; + + while ((step = iterator.next(), !step.done)) { + if (!B.has(step.value)) + return false; + } + + return true; +}; + /** * Function returning whether A is a superset of B. * diff --git a/test/_utils.js b/test/_utils.js index 7e93043b..75d9ed19 100644 --- a/test/_utils.js +++ b/test/_utils.js @@ -14,14 +14,14 @@ describe('utils', function() { describe('typed-arrays', function() { describe('#.getPointerArray', function() { - var validatePointerArrayConstructor = function (min, max, expectedCtor) { - it(`returns ${expectedCtor} for ${min}`, () => { + var validatePointerArrayConstructor = function(min, max, expectedCtor) { + it(`returns ${expectedCtor} for ${min}`, function() { assert.strictEqual(typed.getPointerArray(min), expectedCtor); }); - it(`returns ${expectedCtor} for ${(max - min) / 2}`, () => { + it(`returns ${expectedCtor} for ${(max - min) / 2}`, function() { assert.strictEqual(typed.getPointerArray((max - min) / 2), expectedCtor); }); - it(`returns ${expectedCtor} for ${max}`, () => { + it(`returns ${expectedCtor} for ${max}`, function() { assert.strictEqual(typed.getPointerArray(max), expectedCtor); }); }; diff --git a/test/helpers.js b/test/helpers.js new file mode 100644 index 00000000..6ae1aee0 --- /dev/null +++ b/test/helpers.js @@ -0,0 +1,48 @@ +// + +// mock logger that swallows all informational messages. +// error-level messages are presumably unexpected so they are also sent to the console. +function dummyLogger() { + var logger = { + traces: [], debugs: [], infos: [], warns: [], errors: [], + }; + logger.trace = function(...args) { logger.traces.push(args); }; + logger.debug = function(...args) { logger.debugs.push(args); }; + logger.info = function(...args) { logger.info.push(args); }; + logger.warn = function(...args) { logger.warns.push(args); }; + logger.error = function(...args) { console.error(...args); logger.errors.push(args); }; // eslint-disable-line no-console + return logger; +} + +// mock logger that swallows all messages, including error-level messages. +function captureLogger() { + var logger = captureLogger; + logger.error = function(...args) { logger.errors.push(args); }; + return logger; +} + +function testNear(actual, expected, deltaLo = null, deltaHi = null) { + if (deltaLo === null) { deltaLo = 0.001 * expected; } + if (deltaHi === null) { deltaHi = deltaLo; } + try { + if ((actual >= (expected - deltaLo)) && (actual <= (expected + deltaHi))) { + return true; + } + } catch (err) { console.error('error in testNear', err); } // eslint-disable-line no-console + console.error('actual should be near expected', actual, expected, actual - expected, deltaLo, deltaHi); // eslint-disable-line no-console + return false; +} + +function testMatches(actual, expected) { + try { + if (expected.test(actual)) { + return true; + } + } catch (err) { console.error('error in testMatches', err); } // eslint-disable-line no-console + console.error('actual should match expected', actual, expected); // eslint-disable-line no-console + return false; +} + +module.exports = { + dummyLogger, captureLogger, testNear, testMatches, +}; diff --git a/test/lru-cache-with-expiry.js b/test/lru-cache-with-expiry.js new file mode 100644 index 00000000..942ed07d --- /dev/null +++ b/test/lru-cache-with-expiry.js @@ -0,0 +1,425 @@ +/** + * Mnemonist LRUCache Unit Tests + * ============================== + */ +var assert = require('assert'), + TestHelpers = require('./helpers.js'), + LRUCacheWithExpiry = require('../lru-cache-with-expiry.js'); + +/* eslint-disable no-multi-spaces */ + +function timeFaker({initT, units = 60 * 1000}) { + var fakeClock = { + initT, + units, + currT: initT, + advance(val) { this.currT += (val * this.units); }, + setTo(val) { this.currT = initT + (val * this.units); }, + get since() { return (this.currT - this.initT) / this.units; }, + }; + // make getTime method detachable from fakeClock without missing its `this` + fakeClock.getTime = () => fakeClock.currT; + return fakeClock; +} + +function episode14(fakeClock, cache) { + fakeClock.setTo(0); cache.set(1, 't00'); + fakeClock.setTo(2); cache.set(20, 't002'); + fakeClock.setTo(3); cache.set(30, 't003'); cache.set(31, 't003'); +} +function episode5(fakeClock, cache) { + fakeClock.setTo(5); cache.set(50, 't05'); +} +function episode68(fakeClock, cache) { + fakeClock.setTo(6); + cache.set(61, 'evictme'); cache.set(62, 't06OftenRead'); cache.set(63, 't06SooneGone'); + cache.get(1); cache.get(20); cache.get(30); cache.get(50); cache.get(31); + fakeClock.setTo(8); + cache.set(81, 't08'); cache.get(62); +} +function episode89(fakeClock, cache) { + fakeClock.setTo(8); + cache.delete(30); cache.get(20); cache.delete(81); cache.set(82, 't08'); cache.get(62); cache.delete(61); + // now it has holes, but nothing should change + fakeClock.setTo(9.5); +} + +function makeTests(Cache, name) { + describe(name, function() { + // + describe('construction', function() { + it('uses pleasant defaults', function () { + var initT = Date.now(); + var cache = new Cache(6); + assert.strictEqual(cache.capacity, 6); + assert.strictEqual(cache.ttk, 15 * 60 * 1000); + assert.strictEqual(cache.ages.length, cache.capacity); + assert.strictEqual(TestHelpers.testNear(cache.initT, initT, 0, 5000), true); + assert.strictEqual(cache.lastT, cache.initT); + }); + + it('allows reasonable configurability', function () { + var fakeClock = timeFaker({initT: 0, units: 1}); + var initT = fakeClock.getTime(); + var cache = new Cache(null, null, 8, { + getTime: fakeClock.getTime, ttk: Cache.minutes(10), + }); + assert.strictEqual(cache.capacity, 8); + assert.strictEqual(cache.ttk, 10 * 60 * 1000); + assert.strictEqual(cache.ages.length, cache.capacity); + assert.strictEqual(cache.initT, initT); + assert.strictEqual(cache.lastT, cache.initT); + }); + + it('accepts (capacity, options) as constructor signature', function () { + var fakeClock = timeFaker({initT: 100}); + var initT = fakeClock.getTime(); + var cache = new Cache(8, {getTime: fakeClock.getTime, ttk: Cache.minutes(10)}); + assert.strictEqual(cache.capacity, 8); + assert.strictEqual(cache.ttk, 10 * 60 * 1000); + assert.strictEqual(cache.ages.length, cache.capacity); + assert.strictEqual(cache.initT, initT); + assert.strictEqual(cache.lastT, cache.initT); + }); + + it('validates inputs', function () { + var fakeClock = timeFaker({initT: 100}); + let err, cache; + try { + cache = new Cache(8, {getTime: fakeClock.getTime, ttl: Cache.minutes(10)}); + } catch (errorThrown) { + err = errorThrown; + } + assert.strictEqual(cache, undefined); + assert.strictEqual(TestHelpers.testMatches(err, /Please supply options.ttk.*keep.*difference/), true); + }); + }); + + describe('time expiration', function () { + + it('works on an empty cache', function () { + var fakeClock = timeFaker({initT: 0, units: 1}); + var cache = new Cache(null, null, 6, {getTime: fakeClock.getTime, ttk: 10}); + // empty + assert.deepStrictEqual(Array.from(cache.keys()), []); + assert.deepStrictEqual(Array.from(cache.K), [undefined, undefined, undefined, undefined, undefined, undefined]); + assert.deepStrictEqual(Array.from(cache.ages), [0, 0, 0, 0, 0, 0]); + cache.expire(); + assert.deepStrictEqual(Array.from(cache.keys()), []); + assert.deepStrictEqual(Array.from(cache.K), [undefined, undefined, undefined, undefined, undefined, undefined]); + assert.deepStrictEqual(Array.from(cache.ages), [0, 0, 0, 0, 0, 0]); + fakeClock.setTo(9.999); + cache.expire(); + assert.deepStrictEqual(Array.from(cache.keys()), []); + assert.deepStrictEqual(Array.from(cache.K), [undefined, undefined, undefined, undefined, undefined, undefined]); + assert.deepStrictEqual(Array.from(cache.ages), [0, 0, 0, 0, 0, 0]); + fakeClock.setTo(10); + cache.expire(); + assert.deepStrictEqual(Array.from(cache.keys()), []); + assert.deepStrictEqual(Array.from(cache.K), [undefined, undefined, undefined, undefined, undefined, undefined]); + assert.deepStrictEqual(Array.from(cache.ages), [0, 0, 0, 0, 0, 0]); + fakeClock.setTo(987654); + cache.expire(); + assert.deepStrictEqual(Array.from(cache.keys()), []); + assert.deepStrictEqual(Array.from(cache.K), [undefined, undefined, undefined, undefined, undefined, undefined]); + assert.deepStrictEqual(Array.from(cache.ages), [0, 0, 0, 0, 0, 0]); + }); + + it('does not expire things that are within the ttk', function () { + var fakeClock = timeFaker({initT: 0, units: 1}); + var cache = new Cache(null, null, 8, {getTime: fakeClock.getTime, ttk: 10}); + // + episode14(fakeClock, cache); + episode5(fakeClock, cache); + // partially full, nothing should expire + cache.expire(); + assert.deepStrictEqual(Array.from(cache.keys()), [50, 31, 30, 20, 1]); + assert.deepStrictEqual(Array.from(cache.K), [1, 20, 30, 31, 50, undefined, undefined, undefined]); + assert.deepStrictEqual(Array.from(cache.ages), [0, 2, 3, 3, 5, 0, 0, 0]); + // + // fill the cache + episode68(fakeClock, cache); + assert.deepStrictEqual(Array.from(cache.keys()), [62, 81, 31, 50, 30, 20, 1, 63]); + assert.deepStrictEqual(Array.from(cache.K), [1, 20, 30, 31, 50, 81, 62, 63]); + assert.deepStrictEqual(Array.from(cache.ages), [0, 2, 3, 3, 5, 8, 6, 6]); + // full, nothing should expire + cache.expire(); + assert.deepStrictEqual(Array.from(cache.keys()), [62, 81, 31, 50, 30, 20, 1, 63]); + assert.deepStrictEqual(Array.from(cache.K), [1, 20, 30, 31, 50, 81, 62, 63]); + assert.deepStrictEqual(Array.from(cache.ages), [0, 2, 3, 3, 5, 8, 6, 6]); + // + // delete some stuff + episode89(fakeClock, cache); + fakeClock.setTo(9.5); + cache.expire(); + assert.deepStrictEqual(Array.from(cache.keys()), [62, 82, 20, 31, 50, 1, 63]); + assert.deepStrictEqual(Array.from(cache.K), [1, 20, 30, 31, 50, 82, 62, 63]); + assert.deepStrictEqual(Array.from(cache.ages), [0, 2, 3, 3, 5, 8, 6, 6]); + }); + // + + it('Expires things that are at or after the ttk (partial cache)', function () { + var fakeClock = timeFaker({initT: 0, units: 1}); + var cache = new Cache(null, null, 8, {getTime: fakeClock.getTime, ttk: 10}); + episode14(fakeClock, cache); + episode5(fakeClock, cache); + fakeClock.setTo(9.5); + cache.expire(); + assert.deepStrictEqual(Array.from(cache.keys()), [50, 31, 30, 20, 1]); + assert.deepStrictEqual(Array.from(cache.K), [1, 20, 30, 31, 50, undefined, undefined, undefined]); + assert.deepStrictEqual(Array.from(cache.ages), [0, 2, 3, 3, 5, 0, 0, 0]); + assert.deepStrictEqual(cache.deletedSize, 0); + // + // The item written at t=0 will expire but 2 and 3 will not. + fakeClock.setTo(10); + cache.expire(); + assert.deepStrictEqual(Array.from(cache.keys()), [50, 31, 30, 20]); + assert.deepStrictEqual(Array.from(cache.K), [1, 20, 30, 31, 50, undefined, undefined, undefined]); + assert.deepStrictEqual(Array.from(cache.ages), [0, 2, 3, 3, 5, 0, 0, 0]); + assert.deepStrictEqual(cache.deletedSize, 1); + // It's idempotent (but with no performance gains) + cache.expire(); + assert.deepStrictEqual(Array.from(cache.keys()), [50, 31, 30, 20]); + assert.deepStrictEqual(Array.from(cache.K), [1, 20, 30, 31, 50, undefined, undefined, undefined]); + assert.deepStrictEqual(Array.from(cache.ages), [0, 2, 3, 3, 5, 0, 0, 0]); + assert.deepStrictEqual(cache.deletedSize, 1); + // + // We can keep expiring... the item written at t=2 will expire but 3 will not. + fakeClock.setTo(12); + cache.expire(); + // + // Everything but one item will be expired + fakeClock.setTo(14); + cache.expire(); + assert.deepStrictEqual(Array.from(cache.keys()), [50]); + assert.deepStrictEqual(Array.from(cache.K), [1, 20, 30, 31, 50, undefined, undefined, undefined]); + assert.deepStrictEqual(Array.from(cache.ages), [0, 2, 3, 3, 5, 0, 0, 0]); + assert.deepStrictEqual(cache.deletedSize, 4); + // + // Everything will be expired + fakeClock.setTo(9999); + cache.expire(); + }); + + it('Expires things that are at or after the ttk (full cache)', function () { + var fakeClock = timeFaker({initT: 0, units: 1}); + var cache = new Cache(null, null, 8, {getTime: fakeClock.getTime, ttk: 10}); + episode14(fakeClock, cache); + episode5(fakeClock, cache); + episode68(fakeClock, cache); + fakeClock.setTo(9.5); + cache.expire(); + assert.deepStrictEqual(Array.from(cache.keys()), [62, 81, 31, 50, 30, 20, 1, 63]); + assert.deepStrictEqual(Array.from(cache.K), [1, 20, 30, 31, 50, 81, 62, 63]); + assert.deepStrictEqual(Array.from(cache.ages), [0, 2, 3, 3, 5, 8, 6, 6]); + assert.deepStrictEqual(cache.deletedSize, 0); + // + fakeClock.setTo(10); + // The item written at t=0 will expire but 2 and 3 will not. + cache.expire(); + assert.deepStrictEqual(Array.from(cache.keys()), [62, 81, 31, 50, 30, 20, 63]); + assert.deepStrictEqual(Array.from(cache.K), [1, 20, 30, 31, 50, 81, 62, 63]); + assert.deepStrictEqual(Array.from(cache.ages), [0, 2, 3, 3, 5, 8, 6, 6]); + assert.deepStrictEqual(cache.deletedSize, 1); + // It's idempotent (but with no performance gains) + cache.expire(); + assert.deepStrictEqual(Array.from(cache.keys()), [62, 81, 31, 50, 30, 20, 63]); + assert.deepStrictEqual(Array.from(cache.K), [1, 20, 30, 31, 50, 81, 62, 63]); + assert.deepStrictEqual(Array.from(cache.ages), [0, 2, 3, 3, 5, 8, 6, 6]); + assert.deepStrictEqual(cache.deletedSize, 1); + // + // We can keep expiring... the item written at t=2 will expire but 3 will not. + fakeClock.setTo(12); + cache.expire(); + assert.deepStrictEqual(Array.from(cache.keys()), [62, 81, 31, 50, 30, 63]); + assert.deepStrictEqual(Array.from(cache.K), [1, 20, 30, 31, 50, 81, 62, 63]); + assert.deepStrictEqual(Array.from(cache.ages), [0, 2, 3, 3, 5, 8, 6, 6]); + assert.deepStrictEqual(cache.deletedSize, 2); + // + // Everything but one item will be expired + fakeClock.setTo(17); + cache.expire(); + assert.deepStrictEqual(Array.from(cache.keys()), [81]); + assert.deepStrictEqual(Array.from(cache.K), [1, 20, 30, 31, 50, 81, 62, 63]); + assert.deepStrictEqual(Array.from(cache.ages), [0, 2, 3, 3, 5, 8, 6, 6]); + assert.deepStrictEqual(cache.deletedSize, 7); + // + // Everything will be expired + fakeClock.setTo(9999); + cache.expire(); + assert.deepStrictEqual(Array.from(cache.keys()), []); + assert.deepStrictEqual(Array.from(cache.K), [1, 20, 30, 31, 50, 81, 62, 63]); + assert.deepStrictEqual(Array.from(cache.ages), [0, 2, 3, 3, 5, 8, 6, 6]); + assert.deepStrictEqual(cache.deletedSize, 0); + }); + + it('Expires things that are at or after the ttk (full cache with holes)', function () { + var fakeClock = timeFaker({initT: 0, units: 1}); + var cache = new Cache(null, null, 8, {getTime: fakeClock.getTime, ttk: 10}); + episode14(fakeClock, cache); + episode5(fakeClock, cache); + episode68(fakeClock, cache); + episode89(fakeClock, cache); + fakeClock.setTo(9.5); + cache.expire(); + assert.deepStrictEqual(Array.from(cache.keys()), [62, 82, 20, 31, 50, 1, 63]); + assert.deepStrictEqual(Array.from(cache.K), [1, 20, 30, 31, 50, 82, 62, 63]); + assert.deepStrictEqual(Array.from(cache.ages), [0, 2, 3, 3, 5, 8, 6, 6]); + assert.deepStrictEqual(cache.deletedSize, 1); + // + fakeClock.setTo(10); + // The item written at t=0 will expire but 2 and 3 will not. + cache.expire(); + assert.deepStrictEqual(Array.from(cache.keys()), [62, 82, 20, 31, 50, 63]); + assert.deepStrictEqual(Array.from(cache.K), [1, 20, 30, 31, 50, 82, 62, 63]); + assert.deepStrictEqual(Array.from(cache.ages), [0, 2, 3, 3, 5, 8, 6, 6]); + assert.deepStrictEqual(cache.deletedSize, 2); + // It's idempotent (but with no performance gains) + cache.expire(); + assert.deepStrictEqual(Array.from(cache.keys()), [62, 82, 20, 31, 50, 63]); + assert.deepStrictEqual(Array.from(cache.K), [1, 20, 30, 31, 50, 82, 62, 63]); + assert.deepStrictEqual(Array.from(cache.ages), [0, 2, 3, 3, 5, 8, 6, 6]); + assert.deepStrictEqual(cache.deletedSize, 2); + // + // We can keep expiring... the item written at t=2 will expire but 3 will not. + fakeClock.setTo(12); + cache.expire(); + assert.deepStrictEqual(Array.from(cache.keys()), [62, 82, 31, 50, 63]); + assert.deepStrictEqual(Array.from(cache.K), [1, 20, 30, 31, 50, 82, 62, 63]); + assert.deepStrictEqual(Array.from(cache.ages), [0, 2, 3, 3, 5, 8, 6, 6]); + assert.deepStrictEqual(cache.deletedSize, 3); + // + // Everything but one item will be expired + fakeClock.setTo(17); + cache.expire(); + assert.deepStrictEqual(Array.from(cache.keys()), [82]); + assert.deepStrictEqual(Array.from(cache.K), [1, 20, 30, 31, 50, 82, 62, 63]); + assert.deepStrictEqual(Array.from(cache.ages), [0, 2, 3, 3, 5, 8, 6, 6]); + assert.deepStrictEqual(cache.deletedSize, 7); + // + // Everything will be expired + fakeClock.setTo(9999); + cache.expire(); + assert.deepStrictEqual(Array.from(cache.keys()), []); + assert.deepStrictEqual(Array.from(cache.K), [1, 20, 30, 31, 50, 82, 62, 63]); + assert.deepStrictEqual(Array.from(cache.ages), [0, 2, 3, 3, 5, 8, 6, 6]); + assert.deepStrictEqual(cache.deletedSize, 0); + }); + + it('Enjoys a good workout', function () { + var fakeClock = timeFaker({initT: 0, units: 1}); + var cache = new Cache(null, null, 8, {getTime: fakeClock.getTime, ttk: 10}); + episode14(fakeClock, cache); + episode5(fakeClock, cache); + episode68(fakeClock, cache); + episode89(fakeClock, cache); + fakeClock.setTo(9.5); + cache.expire(); + assert.deepStrictEqual(Array.from(cache.keys()), [62, 82, 20, 31, 50, 1, 63]); + assert.deepStrictEqual(Array.from(cache.K), [1, 20, 30, 31, 50, 82, 62, 63]); + assert.deepStrictEqual(Array.from(cache.ages), [0, 2, 3, 3, 5, 8, 6, 6]); + assert.deepStrictEqual(cache.deletedSize, 1); + // + fakeClock.setTo(10); + // The item written at t=0 will expire but 2 and 3 will not. + cache.expire(); + assert.deepStrictEqual(Array.from(cache.keys()), [62, 82, 20, 31, 50, 63]); + assert.deepStrictEqual(Array.from(cache.K), [1, 20, 30, 31, 50, 82, 62, 63]); + assert.deepStrictEqual(Array.from(cache.ages), [0, 2, 3, 3, 5, 8, 6, 6]); + assert.deepStrictEqual(cache.deletedSize, 2); + // clock still at 10 + cache.set(101, 't100'); cache.get(50); cache.delete(63); cache.set(102, 't100'); + cache.expire(); + assert.deepStrictEqual(Array.from(cache.keys()), [102, 50, 101, 62, 82, 20, 31]); + assert.deepStrictEqual(Array.from(cache.K), [101, 20, 30, 31, 50, 82, 62, 102]); + assert.deepStrictEqual(Array.from(cache.ages), [10, 2, 3, 3, 5, 8, 6, 10]); + assert.deepStrictEqual(cache.deletedSize, 1); + // + // We can keep expiring... the item written at t=2 will expire but 3 will not. + fakeClock.setTo(12); + cache.get(20); + assert.deepStrictEqual(Array.from(cache.keys()), [20, 102, 50, 101, 62, 82, 31]); + cache.expire(); + assert.deepStrictEqual(Array.from(cache.keys()), [102, 50, 101, 62, 82, 102]); + assert.deepStrictEqual(Array.from(cache.K), [101, 20, 30, 31, 50, 82, 62, 102]); + assert.deepStrictEqual(Array.from(cache.ages), [10, 2, 3, 3, 5, 8, 6, 10]); + assert.deepStrictEqual(cache.deletedSize, 2); + // + // Everything but one item will be expired + fakeClock.setTo(19); + cache.expire(); + assert.deepStrictEqual(Array.from(cache.keys()), [102, 101]); + assert.deepStrictEqual(Array.from(cache.K), [101, 20, 30, 31, 50, 82, 62, 102]); + assert.deepStrictEqual(Array.from(cache.ages), [10, 2, 3, 3, 5, 8, 6, 10]); + assert.deepStrictEqual(cache.deletedSize, 6); + // + // Everything will be expired + fakeClock.setTo(9999); + cache.expire(); + assert.deepStrictEqual(Array.from(cache.keys()), []); + assert.deepStrictEqual(Array.from(cache.K), [101, 20, 30, 31, 50, 82, 62, 102]); + assert.deepStrictEqual(Array.from(cache.ages), [10, 2, 3, 3, 5, 8, 6, 10]); + assert.deepStrictEqual(cache.deletedSize, 0); + }); + }); + + describe('self-monitoring', function () { + it('calls #expire on a regular interval, emitting log messages', function(done) { + // + // get ready to sleep while the monitor call expire ~ nloops times + var cache = new Cache(4); + // clobber this cache's expire method with a spy + var expireWasCalled = 0; + cache.expire = function() { expireWasCalled++; }; + // + var monitorT = 50, nloops = 4, timer, logger = TestHelpers.dummyLogger(); + var assessOutcome = function() { + cache.stopMonitor(); + try { + assert.strictEqual((expireWasCalled === nloops), true); + assert.strictEqual(logger.debugs.length, nloops); + done(); + } catch (err) { done(err); } finally { clearInterval(timer); } + }; + // start the monitor + timer = cache.monitor(monitorT, {logger}); + // wake up after the n'th loop has run to stop the monitor and check the results + setTimeout(assessOutcome, (monitorT * (nloops + 0.8))); + }); + + it('accepts callbacks for metrics and error handling', function(done) { + // + // get ready to sleep while the monitor call expire ~ nloops times + var cache = new Cache(4); + var monitorT = 50, nloops = 4, timer, logger = TestHelpers.dummyLogger(); + // + var didErrorCalls = [], didExpireCalls = []; + var didError = function(err, inst) { + didErrorCalls.push([err, inst]); + return true; + }; + var didExpire = function(inst, begT) { + didExpireCalls.push([inst, begT]); + if (didExpireCalls.length > 2) { throw new Error('catch me please'); } + }; + var assessOutcome = function() { + cache.stopMonitor(); + try { + assert.strictEqual(logger.debugs.length, 0); // not called, because we gave didExpire + assert.strictEqual(logger.errors.length, 0); // not called, because we gave didError + assert.strictEqual(didExpireCalls.length, 4); + assert.strictEqual(didErrorCalls.length, 2); + done(); + } catch (err) { done(err); } finally { clearInterval(timer); } + }; + // start the monitor + timer = cache.monitor(monitorT, {logger, didError, didExpire}); + // wake up after the n'th loop has run to stop the monitor and check the results + global.setTimeout(assessOutcome, monitorT * (nloops + 0.8)); + }); + + }); + }); +} + +makeTests(LRUCacheWithExpiry, 'LRUCacheWithExpiry'); diff --git a/test/lru-cache.js b/test/lru-cache.js index 2cfc6afa..7b618d14 100644 --- a/test/lru-cache.js +++ b/test/lru-cache.js @@ -6,7 +6,10 @@ var assert = require('assert'), LRUCache = require('../lru-cache.js'), LRUMap = require('../lru-map.js'), LRUCacheWithDelete = require('../lru-cache-with-delete.js'), - LRUMapWithDelete = require('../lru-map-with-delete.js'); + LRUMapWithDelete = require('../lru-map-with-delete.js'), + LRUCacheWithExpiry = require('../lru-cache-with-expiry.js'); +// +var NodeUtil = require('util'); function makeTests(Cache, name) { describe(name, function() { @@ -62,7 +65,7 @@ function makeTests(Cache, name) { assert.strictEqual(cache.peek('two'), 5); assert.deepStrictEqual(Array.from(cache.entries()), [['three', 3], ['four', 4], ['two', 5]]); - if (name === 'LRUCache' || name === 'LRUCacheWithDelete') + if (/LRUCache/.test(name)) assert.strictEqual(Object.keys(cache.items).length, 3); else assert.strictEqual(cache.items.size, 3); @@ -222,7 +225,7 @@ function makeTests(Cache, name) { assert.deepStrictEqual(entries, Array.from(cache.entries())); }); - if ((name === 'LRUCacheWithDelete') || (name === 'LRUMapWithDelete')) { + if (/With/.test(name)) { it('should be possible to delete keys from a LRU cache.', function() { var cache = new Cache(3); @@ -302,6 +305,7 @@ function makeTests(Cache, name) { assert.equal(dead, missingMarker); cache.set('one', 'uno'); + cache.set('two', 'dos'); cache.set('three', 'tres'); @@ -488,6 +492,121 @@ function makeTests(Cache, name) { }); } + + describe('inspection', function() { + function makeExercisedCache(capacity) { + var cache = new Cache(capacity), ii; + cache.set(1, 'a'); cache.set(2, 'b'); cache.set('too old', 'c'); cache.set('oldest', 'd'); + for (ii = 0; ii < capacity - 3; ii++) { cache.set(ii * 2, ii * 2); } + cache.set(4, 'D'); cache.set(2, 'B'); cache.get(1); + cache.set(5, 'e'); cache.set(6, 'f'); + return cache; + } + + it('toString() states the name size and capacity', function () { + var cache = new Cache(null, null, 200, {ttk: 900000}); + cache.set(0, 'cero'); cache.set(1, 'uno'); + assert.deepStrictEqual(cache.toString(), `[object ${name}:2/200]`); + if (typeof Symbol !== 'undefined') { + assert.deepStrictEqual(cache[Symbol.toStringTag], `${name}:2/200`); + } + assert.deepStrictEqual(cache.summary, `${name}:2/200`); + cache.set(2, 'dos'); cache.set(3, 'tres'); + assert.deepStrictEqual(cache.toString(), `[object ${name}:4/200]`); + cache = makeExercisedCache(200); + assert.deepStrictEqual(cache.toString(), `[object ${name}:200/200]`); + }); + + if (typeof Symbol !== 'undefined') { + it('registers its inspect method for the console.log and friends to use', function () { + var cache = makeExercisedCache(7); + assert.deepStrictEqual(cache[Symbol.for('nodejs.util.inspect.custom')], cache.inspect); + }); + + it('attaches the summary getter to the magic [Symbol.toStringTag] property', function () { + var cache = makeExercisedCache(7); + assert.deepStrictEqual(cache[Symbol.toStringTag], cache.summary); + }); + } + + it('accepts limits on what inspect returns', function () { + var cache = new Cache(15), inspectedItems; + // empty + inspectedItems = Array.from(cache.inspect({maxToDump: 5}).entries()); + assert.deepStrictEqual(inspectedItems, []); + // + cache.set(1, 'a'); + inspectedItems = Array.from(cache.inspect({maxToDump: 5}).entries()); + assert.deepStrictEqual(inspectedItems, [[1, 'a']]); + // + cache.set(2, 'b'); + inspectedItems = Array.from(cache.inspect({maxToDump: 5}).entries()); + assert.deepStrictEqual(inspectedItems, [[2, 'b'], [1, 'a']]); + // + cache.set(3, 'c'); + inspectedItems = Array.from(cache.inspect({maxToDump: 5}).entries()); + assert.deepStrictEqual(inspectedItems, [[3, 'c'], [2, 'b'], [1, 'a']]); + // + cache.set(4, 'd'); + inspectedItems = Array.from(cache.inspect({maxToDump: 5}).entries()); + assert.deepStrictEqual(inspectedItems, [[4, 'd'], [3, 'c'], [2, 'b'], [1, 'a']]); + // + cache.set(5, 'e'); + inspectedItems = Array.from(cache.inspect({maxToDump: 5}).entries()); + assert.deepStrictEqual(inspectedItems, [[5, 'e'], [4, 'd'], [3, 'c'], [2, 'b'], [1, 'a']]); + // + cache.set(6, 'f'); + inspectedItems = Array.from(cache.inspect({maxToDump: 5}).entries()); + assert.deepStrictEqual(inspectedItems, [[6, 'f'], [5, 'e'], [4, 'd'], ['_...', 2], [1, 'a']]); + // + var ii; + for (ii = 0; ii < 20; ii++) { cache.set(ii * 2, ii * 2); } + inspectedItems = Array.from(cache.inspect({maxToDump: 5}).entries()); + assert.deepStrictEqual(inspectedItems, [[38, 38], [36, 36], [34, 34], ['_...', 11], [10, 10]]); + }); + + it('puts a reasonable limit on what the console will show (large)', function () { + var cache = makeExercisedCache(600); + var asSeenInConsole = NodeUtil.inspect(cache); + // we're trying not to depend on what a given version of node actually serializes + var itemsDumped = /6 => 'f',\s*5 => 'e',\s*1 => 'a',(.|\n)+1168 => 1168,\s*'_\.\.\.' => 581,\s*'oldest' => 'd'/; + assert.deepStrictEqual(itemsDumped.test(asSeenInConsole), true); + assert.deepStrictEqual(new RegExp(`${name}:\[600/600\]`).test(asSeenInConsole), true); + assert.deepStrictEqual(asSeenInConsole.length < 800, true); + }); + + it('puts a reasonable limit on what the console will show (small)', function () { + var cache = makeExercisedCache(7); + var asSeenInConsole = NodeUtil.inspect(cache); + var itemsDumped = /6 => 'f',\s*5 => 'e',\s*1 => 'a',\s*2 => 'B',\s*4 => 'D',\s*0 => 0,\s*'oldest' => 'd'/; + assert.deepStrictEqual(itemsDumped.test(asSeenInConsole), true); + assert.deepStrictEqual(new RegExp(`${name}:7/7`).test(asSeenInConsole), true); + }); + + it('listens to advice about maximum inspection depth', function () { + var cache = makeExercisedCache(7); + var asSeenInConsole = NodeUtil.inspect({foo: {bar: cache}}); + var itemsDumped = /6 => 'f',\s*5 => 'e',\s*1 => 'a',\s*2 => 'B',\s*4 => 'D',\s*0 => 0,\s*'oldest' => 'd'/; + assert.deepStrictEqual(itemsDumped.test(asSeenInConsole), true); + assert.deepStrictEqual(asSeenInConsole.length > 150, true); + // Cannot depend on this existing in older versions. + // asSeenInConsole = NodeUtil.inspect({foo: {bar: [cache]}}); + // deepStrictEqual(asSeenInConsole.length < 70, true); + // deepStrictEqual(new RegExp(`\\[ \\[object ${name}:7/7\\] \\]`).test(asSeenInConsole), true); + }); + + it('allows inspection of the raw item if "all" is given', function () { + var cache = makeExercisedCache(250); + var inspected = cache.inspect({maxToDump: 8, all: true}); + var kk; + for (kk of ['items', 'K', 'V', 'size', 'capacity']) { + assert.deepStrictEqual(inspected[kk] === cache[kk], true); + } + assert.deepStrictEqual(Object.keys(cache), Object.keys(inspected)); + }); + + }); + }); } @@ -495,3 +614,4 @@ makeTests(LRUCache, 'LRUCache'); makeTests(LRUMap, 'LRUMap'); makeTests(LRUCacheWithDelete, 'LRUCacheWithDelete'); makeTests(LRUMapWithDelete, 'LRUMapWithDelete'); +makeTests(LRUCacheWithExpiry, 'LRUCacheWithExpiry'); diff --git a/test/set.js b/test/set.js index 8624e2cb..fbeea76b 100644 --- a/test/set.js +++ b/test/set.js @@ -11,168 +11,322 @@ describe('Set functions', function() { describe('#.intersection', function() { it('should properly compute the intersection of two sets.', function() { - var A = new Set([1, 2, 3]), - B = new Set([2, 3, 4]); + var exemplar = new Set([2, 3, 1]); + var equiv = new Set([1, 2, 3]); + var missing1 = new Set([2, 3]); + var extra45 = new Set([1, 2, 3, 4, 5]); + var disjoint = new Set([7, 8, 9]); + var empty = new Set([]) + // + var withItself = functions.intersection(exemplar, exemplar); + assert.deepStrictEqual(Array.from(withItself), [2, 3, 1]); + var withEquiv = functions.intersection(exemplar, equiv); + assert.deepStrictEqual(Array.from(withEquiv), [2, 3, 1]); + var withSubset = functions.intersection(exemplar, missing1); + assert.deepStrictEqual(Array.from(withSubset), [2, 3]); + var withExtras = functions.intersection(exemplar, extra45); + assert.deepStrictEqual(Array.from(withExtras), [2, 3, 1]); + var withDisjoint = functions.intersection(exemplar, disjoint); + assert.deepStrictEqual(Array.from(withDisjoint), []); + var withEmpty = functions.intersection(exemplar, empty); + assert.deepStrictEqual(Array.from(withEmpty), []); + }); - var I = functions.intersection(A, B); + it('makes no guarantees for element ordering.', function() { + // To be clear: it *currently* preserves the order of the earliest of + // sets with the smallest size, but do not depend on this behavior. + // + var exemplar = new Set([2, 3, 99, 1, 10]); + var equiv = new Set([1, 2, 3, 10, 99]); + var subsetA = new Set([99, 3, 2]); + var subsetB = new Set([3, 99, 2]); + // + var r1 = functions.intersection(exemplar, equiv); + assert.deepStrictEqual(Array.from(r1), [2, 3, 99, 1, 10]); + // + var r2 = functions.intersection(equiv, exemplar); + assert.deepStrictEqual(Array.from(r2), [1, 2, 3, 10, 99]); + // + var r3 = functions.intersection(exemplar, equiv, subsetA); + assert.deepStrictEqual(Array.from(r3), [99, 3, 2]); + // + var r4 = functions.intersection(exemplar, subsetB, equiv, subsetA); + assert.deepStrictEqual(Array.from(r4), [3, 99, 2]); + }); - assert.deepStrictEqual(Array.from(I), [2, 3]); + it('compares identity, not equivalence.', function() { + var arrE1 = [] + var arrE2 = [] + var arrN1 = [1] + var arrN2 = [1] + var exemplar = new Set([1, 2, 3, 'same', arrE1, arrN1]); + var noneIdentical = new Set([2, 3, 'same', arrE2, arrN2]); + var someIdentical = new Set([arrN2, 2, 3, 'same', arrE1]); + // + var withNoneI = functions.intersection(exemplar, noneIdentical); + assert.deepStrictEqual(Array.from(withNoneI), [2, 3, 'same']); + var withSomeI = functions.intersection(exemplar, someIdentical); + assert.deepStrictEqual(Array.from(withSomeI), [2, 3, 'same', arrE1]); }); - it('should be variadic.', function() { - var A = new Set([1, 2, 3, 4]), - B = new Set([2, 3, 4]), - C = new Set([1, 4]), - D = new Set([4, 5, 6]); + it('returns a new set, modifying none', function() { + var exemplar = new Set([1, 2, 3]); + var missing1 = new Set([2, 3]); + var extra45 = new Set([1, 2, 3, 4, 5]); + var disjoint = new Set([7, 8, 9]); + // + functions.intersection(exemplar, missing1, extra45, disjoint); + // + assert.deepStrictEqual(Array.from(exemplar), [1, 2, 3]); + assert.deepStrictEqual(Array.from(missing1), [2, 3]); + assert.deepStrictEqual(Array.from(extra45), [1, 2, 3, 4, 5]); + assert.deepStrictEqual(Array.from(disjoint), [7, 8, 9]); + }); + + it('should be variadic (work with multiple sets).', function() { + var exemplar = new Set([1, 2, 3]); + var equiv = new Set([1, 2, 3]); + var missing1 = new Set([2, 3]); + var extra45 = new Set([1, 2, 3, 4, 5]); + var disjoint = new Set([7, 8, 9]); + var empty = new Set([]) - var I = functions.intersection(A, B, C, D); + var intersectioned1 = functions.intersection(exemplar, missing1, extra45); - assert.deepStrictEqual(Array.from(I), [4]); + assert.deepStrictEqual(Array.from(intersectioned1), [2, 3]); + + var intersectioned2 = functions.intersection(exemplar, missing1, extra45, disjoint); + + assert.deepStrictEqual(Array.from(intersectioned2), []); }); }); describe('#.union', function() { it('should properly compute the union of two sets.', function() { - var A = new Set([1, 2, 3]), - B = new Set([2, 3, 4]); + var setA = new Set([1, 2, 3]), + setB = new Set([2, 3, 4]); - var U = functions.union(A, B); + var unioned = functions.union(setA, setB); - assert.deepStrictEqual(Array.from(U), [1, 2, 3, 4]); + assert.deepStrictEqual(Array.from(unioned), [1, 2, 3, 4]); }); it('should be variadic.', function() { - var A = new Set([1, 2, 3, 4]), - B = new Set([2, 3, 4]), - C = new Set([1, 4]), - D = new Set([4, 5, 6]); + var setA = new Set([1, 2, 3, 4]), + setB = new Set([2, 3, 4]), + setC = new Set([1, 4]), + setD = new Set([4, 5, 6]); - var U = functions.union(A, B, C, D); + var unioned = functions.union(setA, setB, setC, setD); - assert.deepStrictEqual(Array.from(U), [1, 2, 3, 4, 5, 6]); + assert.deepStrictEqual(Array.from(unioned), [1, 2, 3, 4, 5, 6]); }); }); describe('#.difference', function() { it('should properly compute the difference of two sets.', function() { - var A = new Set([1, 2, 3, 4, 5]), - B = new Set([2, 3]); + var setA = new Set([1, 2, 3, 4, 5]), + setB = new Set([2, 3]); - var D = functions.difference(A, B); + var differenced = functions.difference(setA, setB); - assert.deepStrictEqual(Array.from(D), [1, 4, 5]); + assert.deepStrictEqual(Array.from(differenced), [1, 4, 5]); }); }); describe('#.symmetricDifference', function() { it('should properly compute the symmetric difference of two sets.', function() { - var A = new Set([1, 2, 3]), - B = new Set([3, 4, 5]); + var setA = new Set([1, 2, 3]), + setB = new Set([3, 4, 5]); - var S = functions.symmetricDifference(A, B); + var symDiffed = functions.symmetricDifference(setA, setB); - assert.deepStrictEqual(Array.from(S), [1, 2, 4, 5]); + assert.deepStrictEqual(Array.from(symDiffed), [1, 2, 4, 5]); }); }); describe('#.isSubset', function() { it('should properly return if the first set is a subset of the second.', function() { - var A = new Set([1, 2]), - B = new Set([1, 2, 3]), - C = new Set([2, 4]); + var setA = new Set([1, 2]), + setB = new Set([1, 2, 3]), + setC = new Set([2, 4]), + empty = new Set([]); + + assert.strictEqual(functions.isSubset(setA, setB), true); + assert.strictEqual(functions.isSubset(setC, setB), false); + assert.strictEqual(functions.isSubset(empty, setB), true); + assert.strictEqual(functions.isSubset(setB, empty), false); + assert.strictEqual(functions.isSubset(empty, empty), true); + }); + }); - assert.strictEqual(functions.isSubset(A, B), true); - assert.strictEqual(functions.isSubset(C, B), false); + describe('#.isEqual', function() { + it('should properly return if the first set is equal to the second set.', function() { + var exemplar = new Set([1, 2, 3]), + sameObj = exemplar, + yepEqualsTo = new Set([1, 2, 3]), + moreEls = new Set([1, 2, 3, 4]), + fewerEls = new Set([1]), + differentEls = new Set([1, 2, 4]), + empty = new Set([]); + + assert.strictEqual(functions.isEqual(exemplar, exemplar), true); + assert.strictEqual(functions.isEqual(sameObj, exemplar), true); + assert.strictEqual(functions.isEqual(yepEqualsTo, exemplar), true); + assert.strictEqual(functions.isEqual(empty, empty), true); + // + assert.strictEqual(functions.isEqual(moreEls, exemplar), false); + assert.strictEqual(functions.isEqual(fewerEls, exemplar), false); + assert.strictEqual(functions.isEqual(differentEls, exemplar), false); + assert.strictEqual(functions.isEqual(empty, exemplar), false); + assert.strictEqual(functions.isEqual(exemplar, empty), false); }); }); describe('#.isSuperset', function() { - it('should properly return if the first set is a subset of the second.', function() { - var A = new Set([1, 2]), - B = new Set([1, 2, 3]), - C = new Set([2, 4]); - - assert.strictEqual(functions.isSuperset(B, A), true); - assert.strictEqual(functions.isSuperset(B, C), false); + it('should properly return if the first set is a superset of the second.', function() { + var setA = new Set([1, 2]), + setB = new Set([1, 2, 3]), + setC = new Set([2, 4]), + empty = new Set([]); + + assert.strictEqual(functions.isSuperset(setB, setA), true); + assert.strictEqual(functions.isSuperset(setB, setC), false); + assert.strictEqual(functions.isSuperset(setB, empty), true); + assert.strictEqual(functions.isSuperset(empty, setB), false); + assert.strictEqual(functions.isSuperset(empty, empty), true); }); }); describe('#.add', function() { it('should properly add the second set to the first.', function() { - var A = new Set([1, 2]); + var setA = new Set([1, 2]); + + functions.add(setA, new Set([2, 3])); + + assert.deepStrictEqual(Array.from(setA), [1, 2, 3]); - functions.add(A, new Set([2, 3])); + functions.add(setA, new Set()); - assert.deepStrictEqual(Array.from(A), [1, 2, 3]); + assert.deepStrictEqual(Array.from(setA), [1, 2, 3]); }); }); describe('#.subtract', function() { it('should properly subtract the second set to the first.', function() { - var A = new Set([1, 2]); + var setA = new Set([1, 2]); - functions.subtract(A, new Set([2, 3])); + functions.subtract(setA, new Set([2, 3])); - assert.deepStrictEqual(Array.from(A), [1]); + assert.deepStrictEqual(Array.from(setA), [1]); + + functions.subtract(setA, new Set()); + + assert.deepStrictEqual(Array.from(setA), [1]); + }); + + it('should properly subtract sets from an empty set.', function() { + var empty = new Set([]); + + functions.subtract(empty, new Set([2, 3])); + + assert.deepStrictEqual(Array.from(empty), []); + + functions.subtract(empty, new Set()); + + assert.deepStrictEqual(Array.from(empty), []); }); }); describe('#.intersect', function() { - it('should properly intersect the second set to the first.', function() { - var A = new Set([1, 2]); + var equiv = new Set([1, 2, 3]); + var missing1 = new Set([2, 3]); + var disjoint = new Set([7, 8, 9]); + var empty = new Set([]) + + it('should properly intersect overlapping sets.', function() { + var exemplar = new Set([1, 2, 3]); + functions.intersect(exemplar, missing1) + + assert.deepStrictEqual(Array.from(exemplar), [2, 3]); + assert.deepStrictEqual(Array.from(missing1), [2, 3]); + }); + + it('should properly intersect equivalent sets.', function() { + var exemplar = new Set([1, 2, 3]); + functions.intersect(exemplar, exemplar) + + assert.deepStrictEqual(Array.from(exemplar), [1, 2, 3]); + + functions.intersect(exemplar, equiv) + + assert.deepStrictEqual(Array.from(exemplar), [1, 2, 3]); + assert.deepStrictEqual(Array.from(equiv), [1, 2, 3]); + }); + + it('should properly intersect disjoint sets.', function() { + var exemplar = new Set([1, 2, 3]); + + functions.intersect(exemplar, disjoint); + + assert.deepStrictEqual(Array.from(exemplar), []); + assert.deepStrictEqual(Array.from(disjoint), [7, 8, 9]); + + exemplar = new Set([1, 2, 3]); - functions.intersect(A, new Set([2, 3])); + functions.intersect(exemplar, empty); - assert.deepStrictEqual(Array.from(A), [2]); + assert.deepStrictEqual(Array.from(exemplar), []); + assert.deepStrictEqual(Array.from(empty), []); }); }); describe('#.disjunct', function() { it('should properly disjunct the second set to the first.', function() { - var A = new Set([1, 2]); + var setA = new Set([1, 2]); - functions.disjunct(A, new Set([2, 3])); + functions.disjunct(setA, new Set([2, 3])); - assert.deepStrictEqual(Array.from(A), [1, 3]); + assert.deepStrictEqual(Array.from(setA), [1, 3]); }); }); describe('#.intersectionSize', function() { it('should properly return the size of the intersection.', function() { - var A = new Set([1, 2, 3]), - B = new Set([2, 3, 4]); + var setA = new Set([1, 2, 3]), + setB = new Set([2, 3, 4]); - var N = new Set([]); + var emptySet = new Set([]); - assert.strictEqual(functions.intersectionSize(A, B), 2); - assert.strictEqual(functions.intersectionSize(A, N), 0); + assert.strictEqual(functions.intersectionSize(setA, setB), 2); + assert.strictEqual(functions.intersectionSize(setA, emptySet), 0); }); }); describe('#.unionSize', function() { it('should properly return the size of the union.', function() { - var A = new Set([1, 2, 3]), - B = new Set([2, 3, 4]); + var setA = new Set([1, 2, 3]), + setB = new Set([2, 3, 4]); - var N = new Set([]); + var emptySet = new Set([]); - assert.strictEqual(functions.unionSize(A, B), 4); - assert.strictEqual(functions.unionSize(A, N), 3); + assert.strictEqual(functions.unionSize(setA, setB), 4); + assert.strictEqual(functions.unionSize(setA, emptySet), 3); }); }); describe('#.jaccard', function() { it('should properly return the Jaccard similarity between two sets.', function() { - var A = new Set([1, 2, 3]), - B = new Set([2, 3, 4]); + var setA = new Set([1, 2, 3]), + setB = new Set([2, 3, 4]); - var N = new Set([]); + var emptySet = new Set([]); - assert.strictEqual(functions.jaccard(A, B), 2 / 4); - assert.strictEqual(functions.jaccard(A, N), 0); + assert.strictEqual(functions.jaccard(setA, setB), 2 / 4); + assert.strictEqual(functions.jaccard(setA, emptySet), 0); assert.strictEqual(functions.jaccard(new Set('contact'), new Set('context')), 4 / 7); }); @@ -180,13 +334,13 @@ describe('Set functions', function() { describe('#.overlap', function() { it('should properly return the overlap coefficient between two sets.', function() { - var A = new Set([1, 2, 3]), - B = new Set([2, 3, 4]); + var setA = new Set([1, 2, 3]), + setB = new Set([2, 3, 4]); - var N = new Set([]); + var emptySet = new Set([]); - assert.strictEqual(functions.overlap(A, B), 2 / 3); - assert.strictEqual(functions.overlap(A, N), 0); + assert.strictEqual(functions.overlap(setA, setB), 2 / 3); + assert.strictEqual(functions.overlap(setA, emptySet), 0); assert.strictEqual(functions.overlap(new Set('contact'), new Set('context')), 4 / 5); }); diff --git a/test/types.ts b/test/types.ts index bb9db9ea..feb0cfee 100644 --- a/test/types.ts +++ b/test/types.ts @@ -21,6 +21,7 @@ import { LinkedList, LRUCache, LRUCacheWithDelete, + LRUCacheWithExpiry, LRUMap, LRUMapWithDelete, MultiSet, @@ -167,6 +168,17 @@ lrucwdItem = lrucwd.remove('one'); let lrucwdDead: string | null = lrucwd.remove('one', null); let lrucwdWasRemoved: boolean = lrucwd.delete('one'); +/** + * LRUCacheWithExpiry + */ +let lrucwe: LRUCacheWithExpiry = new LRUCacheWithExpiry(10); +lrucwe.set('one', 'uno'); +let lrucweItem: string = lrucwe.get('one'); +lrucweItem = lrucwe.remove('one'); +let lrucweDead: string | null = lrucwe.remove('one', null); +let lrucweWasRemoved: boolean = lrucwe.delete('one'); +lrucwe.expire(); + /** * LRUMap. */ diff --git a/utils/snip.js b/utils/snip.js new file mode 100644 index 00000000..776dfab8 --- /dev/null +++ b/utils/snip.js @@ -0,0 +1,25 @@ +// +function snipToLast(iterator, proxy, {maxToDump = 20, size = Infinity, last = []}) { + var step; + + var ii = 0; + while ((step = iterator.next(), !step.done)) { + if (ii >= maxToDump - 2) { + if (ii >= size - 1) { + proxy.set(step.value[0], step.value[1]); + } else if (ii === size - 2) { + proxy.set(step.value[0], step.value[1]); + proxy.set(last[0], last[1]); + } else { + proxy.set('_...', size - ii - 1); + proxy.set(last[0], last[1]); + } + break; + } + proxy.set(step.value[0], step.value[1]); + ii += 1; + } + return proxy; +} + +module.exports.snipToLast = snipToLast;