@5app/memoize 中文文档教程

发布于 4年前 浏览 27 项目主页 更新于 3年前

Memoize

CircleCI

在计算中,memoization 或 memoisation 是一种优化技术,主要用于通过存储昂贵的函数调用的结果并在相同的输入再次出现时返回缓存的结果来加速计算机程序。 记忆化也被用在其他情况下(并且用于速度提升以外的目的),例如简单的相互递归下降解析。 [1] 尽管与缓存相关,但记忆化是指此优化的特定情况,将其与缓冲或页面替换等缓存形式区分开来。 在某些逻辑编程语言的上下文中,记忆也称为表格。 [2]

https://en.wikipedia.org/wiki/Memoization

Usage

!警告前面人为的例子......

const got = require('got'); // simple http requst library for the purpose of demonstration
const memoize = require('@5app/memoize');

// Let's say we're going to decorate an add function... it's
const memoGot = memoize(got);

// Simultaneously open two connections...
const link = 'https://github.com';
Promise.all([memoGot(link), memoGot(link)];

// only one request is actually made, the second will piggy back off the first.

Options memoize(handler, {...options})

  • option.useCache (Boolean|Function): A truthy/fasly or a function to decide whether to use the cached record or not. Default true
  • option.staleInMs Number: The number of milliseconds before the cache is deemed stale. Results will still be served from the cache whilst an attempt to refresh the cache is made separatly. Default 10000 ms.
  • option.getKey Function: A function to create a key based upon the input of the function being memoized. Default: a serialization of all the arguments.
  • option.cache Object: Instance of a Map like object to store the cache. Default new Map
  • options.cacheMaxSize Number: The maximum number of entries to store in the cache. Default 1000

option.useCache

是否使用缓存这可以是一个布尔值(在测试时禁用它很有用)。 或者一个函数,例如

这个片段在决定是否使用它之前检查缓存的值......

const memoize = require('@5app/memoize');
const memoGot = memoize(got, {
    /**
      * @param {object} cached_response - Cached Object
     * @param {number} cached_response.timestamp - Timestamp when request resolved
     * @param {string} cached_response.status - 'pending', 'fullfilled', 'rejected'
     * @param {Promise<*>} cached_response.value - Promise of the request
     * @returns {Boolean}
     */
    useCache({timestamp, status}) {
        // Set an expiry on the cache.
        // 2xx, 3xx response last for a full minute before being reused
        // 4xx, 5xx last only a second...
        const age = value.statusCode >= 400 ? 1000 : 60000;

        // Return true if the cache is un-expired, else false.
        return timestamp > Date.now() - AGE;
    }
}

// ...

// Use Memogot
// const req = memogot('link');
// ...

Globally Disable

在测试禁用可能导致问题的 memoize 缓存时,使用 MEMOIZE_DISABLE 环境变量,例如

MEMOIZE_DISABLE=1

当设置为真值时memoize 缓存将被规避。

Memoize

CircleCI

In computing, memoization or memoisation is an optimization technique used primarily to speed up computer programs by storing the results of expensive function calls and returning the cached result when the same inputs occur again. Memoization has also been used in other contexts (and for purposes other than speed gains), such as in simple mutually recursive descent parsing.[1] Although related to caching, memoization refers to a specific case of this optimization, distinguishing it from forms of caching such as buffering or page replacement. In the context of some logic programming languages, memoization is also known as tabling.[2]

https://en.wikipedia.org/wiki/Memoization

Usage

!Warning contrived example ahead…

const got = require('got'); // simple http requst library for the purpose of demonstration
const memoize = require('@5app/memoize');

// Let's say we're going to decorate an add function... it's
const memoGot = memoize(got);

// Simultaneously open two connections...
const link = 'https://github.com';
Promise.all([memoGot(link), memoGot(link)];

// only one request is actually made, the second will piggy back off the first.

Options memoize(handler, {...options})

  • option.useCache (Boolean|Function): A truthy/fasly or a function to decide whether to use the cached record or not. Default true
  • option.staleInMs Number: The number of milliseconds before the cache is deemed stale. Results will still be served from the cache whilst an attempt to refresh the cache is made separatly. Default 10000 ms.
  • option.getKey Function: A function to create a key based upon the input of the function being memoized. Default: a serialization of all the arguments.
  • option.cache Object: Instance of a Map like object to store the cache. Default new Map
  • options.cacheMaxSize Number: The maximum number of entries to store in the cache. Default 1000

option.useCache

Whether to use cache this can be a Boolean value (useful to disable it when testing). Or a function e.g.

This snippet checks the cached value before deciding whether to use it…

const memoize = require('@5app/memoize');
const memoGot = memoize(got, {
    /**
      * @param {object} cached_response - Cached Object
     * @param {number} cached_response.timestamp - Timestamp when request resolved
     * @param {string} cached_response.status - 'pending', 'fullfilled', 'rejected'
     * @param {Promise<*>} cached_response.value - Promise of the request
     * @returns {Boolean}
     */
    useCache({timestamp, status}) {
        // Set an expiry on the cache.
        // 2xx, 3xx response last for a full minute before being reused
        // 4xx, 5xx last only a second...
        const age = value.statusCode >= 400 ? 1000 : 60000;

        // Return true if the cache is un-expired, else false.
        return timestamp > Date.now() - AGE;
    }
}

// ...

// Use Memogot
// const req = memogot('link');
// ...

Globally Disable

In testing to disable the memoize cache which can cause issues, use the MEMOIZE_DISABLE environment variable, e.g.

MEMOIZE_DISABLE=1

When set to a truthy value the memoize cache will be circumvented.

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文