How to use lru-cache - 10 common examples

To help you get started, we’ve selected a few lru-cache examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github DevExpress / testcafe-hammerhead / src / request-pipeline / destination-request / agent.ts View on Github external
import https from 'https';
import LRUCache from 'lru-cache';
// @ts-ignore
import tunnel from 'tunnel-agent';

const SSL3_HOST_CACHE_SIZE = 1000;

/* eslint-disable no-unused-vars */
enum TYPE {
    SSL3 = 'SSL3',
    TLS = 'TLS',
    HTTP = 'HTTP'
}
/* eslint-enable no-unused-vars */

const ssl3HostCache = new LRUCache({ max: SSL3_HOST_CACHE_SIZE });

const agents = {
    [TYPE.SSL3]: {
        instance:       null,
        Ctor:           https.Agent,
        secureProtocol: 'SSLv3_method'
    },

    [TYPE.TLS]: {
        instance: null,
        Ctor:     https.Agent
    },

    [TYPE.HTTP]: {
        instance: null,
        Ctor:     http.Agent
github facebookarchive / atom-ide-ui / modules / nuclide-commons / ConfigCache.js View on Github external
constructor(
    configPatterns: Array,
    searchStrategy?: SearchStrategy = 'nearest',
  ) {
    this._configPatterns = configPatterns;
    this._searchStrategy = searchStrategy;
    this._configCache = LRU({
      max: 200, // Want this to exceed the maximum expected number of open files + dirs.
      maxAge: 1000 * 30, // 30 seconds
    });
  }
github LedgerHQ / ledger-live-desktop / src / components / SelectExchange.js View on Github external
// @flow
import React, { Fragment, Component } from 'react'
import { translate } from 'react-i18next'
import LRU from 'lru-cache'
import type { Currency } from '@ledgerhq/live-common/lib/types'
import type { Exchange } from '@ledgerhq/live-common/lib/countervalues/types'
import logger from 'logger'

import Track from 'analytics/Track'
import Select from 'components/base/Select'
import Box from 'components/base/Box'
import TranslatedError from 'components/TranslatedError'
import CounterValues from 'helpers/countervalues'
import type { T } from 'types/common'

const cache = LRU({ max: 100 })

const getExchanges = (from: Currency, to: Currency) => {
  const key = `${from.ticker}_${to.ticker}`
  let promise = cache.get(key)
  if (promise) return promise
  promise = CounterValues.fetchExchangesForPair(from, to)
  promise.catch(() => cache.del(key)) // if it's a failure, we don't want to keep the cache
  cache.set(key, promise)
  return promise
}

class SelectExchange extends Component<
  {
    from: Currency,
    to: Currency,
    exchangeId: ?string,
github JounQin / react-hackernews / src / api / create-api-server.js View on Github external
export function createAPI({ config, version }) {
  let api
  // this piece of code may run multiple times in development mode,
  // so we attach the instantiated API to `process` to avoid duplications
  if (process.__API__) {
    api = process.__API__
  } else {
    Firebase.initializeApp(config)
    api = process.__API__ = Firebase.database().ref(version)

    api.onServer = true

    // fetched item cache
    api.cachedItems = new LRU({
      max: 1000,
      maxAge: 1000 * 60 * 15, // 15 min cache
    })

    // cache the latest story ids
    api.cachedIds = {}
    ;['top', 'new', 'show', 'ask', 'job'].forEach(type => {
      api.child(`${type}stories`).on('value', snapshot => {
        api.cachedIds[type] = snapshot.val()
      })
    })
  }
  return api
}
github mjackson / unpkg / modules / utils / getNpmPackageInfo.js View on Github external
import LRUCache from 'lru-cache';

import fetchNpmPackageInfo from './fetchNpmPackageInfo';

const maxMegabytes = 40; // Cap the cache at 40 MB
const maxLength = maxMegabytes * 1024 * 1024;
const oneSecond = 1000;
const oneMinute = 60 * oneSecond;

const cache = new LRUCache({
  max: maxLength,
  maxAge: oneMinute,
  length: Buffer.byteLength
});

const notFound = '';

export default function getNpmPackageInfo(packageName) {
  return new Promise((resolve, reject) => {
    const key = `npmPackageInfo-${packageName}`;
    const value = cache.get(key);

    if (value != null) {
      resolve(value === notFound ? null : JSON.parse(value));
    } else {
      fetchNpmPackageInfo(packageName).then(info => {
github youzan / zan-proxy / src / core / ProxyServer / index.ts View on Github external
private async init() {
    this.forwarder = new Forwarder();
    this.cache = new LRU({
      max: 500,
      maxAge: 1000 * 60 * 60,
    });
    const certStorage = new CertificateStorage(
      path.join(os.homedir(), '.front-end-proxy/certificate'),
    );
    const certService = new CertificateService(certStorage, this.cache);
    this.cert = {
      service: certService,
      storage: certStorage,
    };
    this.httpsPort = await getPort({ port: 8989 });

    this.handlers = {
      connect: new ConnectHandler(this.httpsPort, this.cache),
      http: new HttpHandler(),
github kayteh / roleypoly / packages / roleypoly-server / services / discord / restFetcher.js View on Github external
constructor (ctx: DiscordSvc) {
    this.ctx = ctx
    this.client = ctx.client
    this.cache = new LRU({
      max: 50,
      maxAge: 1000 * 60 * 10
    })
  }
github dagster-io / dagster / js_modules / dagit / src / Util.tsx View on Github external
export function asyncMemoize(
  fn: (arg: T, ...rest: any[]) => PromiseLike,
  hashFn?: (arg: T, ...rest: any[]) => any,
  hashSize?: number
): (arg: T, ...rest: any[]) => Promise {
  const cache = new LRU(hashSize || 50);
  return async (arg: T, ...rest: any[]) => {
    const key = hashFn ? hashFn(arg, ...rest) : arg;
    if (cache.has(key)) {
      return Promise.resolve(cache.get(key) as R);
    }
    const r = (await fn(arg, ...rest)) as R;
    cache.set(key, r);
    return r;
  };
}
github treasure-data / digdag / digdag-ui / model.js View on Github external
constructor (config: ModelConfig) {
    this.config = config
    this.workflowCache = LRU({ max: 10000 })
    this.queriesCache = LRU({ max: 10000 })
  }
github Irrational-Encoding-Wizardry / yuuno / yuuno-jupyter / src / utils / frameCache.js View on Github external
constructor(options) {
        this._lru = new LRU(options);
        this._active = {};
    }

lru-cache

A cache object that deletes the least-recently-used items.

ISC
Latest version published 3 months ago

Package Health Score

86 / 100
Full package analysis

Popular lru-cache functions