Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

limit-once

Package Overview
Dependencies
Maintainers
1
Versions
15
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

limit-once

Remember the first result of a function call

  • 0.2.0
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
0
decreased by-100%
Maintainers
1
Weekly downloads
 
Created
Source

limit-once

Create a function that caches the result of the first function call. limit-once let's you lazily evaluate a value (using a function), and then hold onto the value forever.

import { once } from 'limit-once';

function sayHello(name: string): string {
  return `Hello ${name}`;
}
const cached = once(sayHello);

cached('Alex');
// sayHello called and "Hello Alex" is returned
// "Hello Alex" is put into the cache.
// returns "Hello Alex"

cached('Sam');
// sayHello is not called
// "Hello Alex" is returned from the cache.

cached('Greg');
// sayHello is not called
// "Hello Alex" is returned from the cache.
// is-safari.ts

import { once } from 'limit-once';

// We are caching the result of our 'isSafari()' function as the result
// of `isSafari()` won't change.
export const isSafari = once(function isSafari(): boolean {
  const { userAgent } = navigator;
  return userAgent.includes('AppleWebKit') && !userAgent.includes('Chrome');
});

// app.ts
if (isSafari()) {
  applySafariFix();
}

Installation

# yarn
yarn add limit-once

# npm
npm install limit-once

# bun
bun add limit-once

Cache clearing (.clear())

You can clear the cache of a memoized function by using a .clear() function that is on your cached function.

import { once } from 'limit-once';

function sayHello(name: string): string {
  return `Hello ${name}`;
}
const cached = once(sayHello);

cached('Alex');
// sayHello called and "Hello Alex" is returned.
// "Hello Alex" is put into the cache
// cached function returns "Hello Alex"

cached('Sam');
// sayHello is not called
// "Hello Alex" is returned from cache

cached.clear();

cached('Greg');
// sayHello is called and "Hello Greg" is returned.
// "Hello Greg" is put into the cache
// "Hello Greg" is returned.

Keywords

FAQs

Package last updated on 21 May 2024

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc