Skip to content

Propose Keyv.prototype.memoize #34

@moeriki

Description

@moeriki

I'd like to propose a solution for a common pattern. At least for me.

Usage

const cachedRequest = keyv.memoize(request);

cachedRequest('http://example.com').then(() => { /* result */ });
// later
cachedRequest('http://example.com').then(() => { /* cached result */ });

Implementation

/**
 * @param {function}        func
 * @param {object}          [opts]
 * @param {function}        [opts.resolver=identity]
 * @param {function|number} [opts.ttl]
 * @return {Promise}
 */
Keyv.prototype.memoize = function memoize(func, { resolver, ttl }) {
  return (...args) => {
    const key = resolver ? resolver(...args) : args[0];
    return this.get(key).then((storedValue) => {
      if (storedValue !== undefined) {
        return storedValue;
      }
      return Promise.resolve(func(...args)).then((value) => {
        if (value !== undefined) {
          return this.set(key, value, typeof ttl === 'function' ? ttl(value) : value)
            .then(() => value)
          ;
        }
        return value;
      });
    });
  };
};

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions