Yomguithereal / mnemonist

Curated collection of data structures for the JavaScript/TypeScript language.
https://yomguithereal.github.io/mnemonist
MIT License
2.26k stars 92 forks source link

LRUCache throws "Invalid array length" as an error if float value is passed to it #165

Closed trivikr closed 3 years ago

trivikr commented 3 years ago

Describe the issue

LRUCache throws "Invalid array length" as an error if float value is passed to it.

Steps to reproduce

Run the following code with mnemonist@0.38.3

const LRUCache = require("mnemonist/lru-cache");
const cache = new LRUCache(1.01);

Observed behavior

The following error is thrown:

  this.K = typeof Keys === 'function' ? new Keys(capacity) : new Array(capacity);
                                                             ^

RangeError: Invalid array length
    at new LRUCache (/Users/trivikr/workspace/lru-cache/node_modules/mnemonist/lru-cache.js:47:62)
    at Object.<anonymous> (/Users/trivikr/workspace/lru-cache/index.js:3:15)
    at Module._compile (internal/modules/cjs/loader.js:1068:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1097:10)
    at Module.load (internal/modules/cjs/loader.js:933:32)
    at Function.Module._load (internal/modules/cjs/loader.js:774:14)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)
    at internal/main/run_main_module.js:17:47

Expected behavior

A custom error can be thrown on this line instead after adding a check for integer: https://github.com/Yomguithereal/mnemonist/blob/825538adaf1daee4b9ce3f6c073956ed4211ea1e/lru-cache.js#L40-L41

trivikr commented 3 years ago

Example fix without changing the prior error:

  if (typeof this.capacity !== 'number' || this.capacity <= 0)
    if (!isFinite(this.capacity) || Math.floor(this.capacity) !== this.capacity)
      throw new Error('mnemonist/lru-cache: capacity should be a finite positive integer.');
    throw new Error('mnemonist/lru-cache: capacity should be positive number.');
Yomguithereal commented 3 years ago

Hello @trivikr. Looks good to me. Do you want to open a PR with this change?

trivikr commented 3 years ago

Do you want to open a PR with this change?

PR posted at https://github.com/Yomguithereal/mnemonist/pull/166