项目作者: feross

项目描述 :
Memoize Node.js style callback-last functions, using an in-memory LRU store
高级语言: JavaScript
项目地址: git://github.com/feross/memo-async-lru.git
创建时间: 2017-02-17T09:14:09Z
项目社区:https://github.com/feross/memo-async-lru

开源协议:MIT License

下载


memo-async-lru travis npm downloads javascript style guide

Memoize Node.js style callback-last functions, using an in-memory LRU store

Also works in the browser with browserify!

install

  1. npm install memo-async-lru

usage

  1. const memo = require('memo-async-lru')
  2. function fn (arg, cb) {
  3. t.equal(arg, 'foo')
  4. cb(null, 'bar')
  5. }
  6. const memoFn = memo(fn)
  7. memoFn('foo', (err, result) => {
  8. console.log(result) // prints 'bar'
  9. memoFn('foo', (err, result) => {
  10. console.log(result) // prints 'bar', cached, does not call fn()
  11. })
  12. })

API

memo(fn, [opts])

Memoize the given function fn, using
async-lru, a simple async LRU cache supporting
O(1) set, get and eviction of old keys.

The function must be a Node.js style function, where the last argument is a callback.

function(key: Object, […], fetch: function(err: Error, value: Object))

So, if you were to do:

  1. const readFile = memo(fs.readFile)
  2. readFile('file.txt', fn)
  3. readFile('file.txt', fn) // <-- this uses the cache

The file would only be read from disk once, it’s value cached, and returned
anytime the first argument is ‘file.txt’.

Repeated calls to the function with the same first argument will return a
cached value, rather than re-fetch the data.

Optionally, an opts parameter can be specified with the following properties:
Optional options:

  1. {
  2. max: maxElementsToStore,
  3. maxAge: maxAgeInMilliseconds
  4. }

If you pass max, items will be evicted if the cache is storing more than max items.
If you pass maxAge, items will be evicted if they are older than maxAge when you access them.

license

MIT. Copyright (c) Feross Aboukhadijeh.