1.0.4 • Published 8 years ago
limited-use v1.0.4
limited-use
A lightweight abstraction for functions that should only be invoked a limited number of times.
Usage
import {LimitedUse} from 'limited-use'
const usable = new LimitedUse(() => console.log('take a nap'), 1)
usable.use() // 'take a nap'
usable.use() // no effectWith multiple LimitedUses, use them as a single group with CollectiveUse:
import {LimitedUse, CollectiveUse} from 'limited-use'
const usables = new CollectiveUse()
usables.add(
new LimitedUse(() => console.log('eat a donut')),
new LimitedUse(x => console.log(`think about her ${x}`), 365)
)
usables.use('smile') // 'eat a donut', 'think about her smile'
usables.use('touch') // 'think about her touch'
usables.disuse()
usables.use('desperately') // no effectInstallation
Install using yarn:
$ yarn add limited-useInstall using npm:
$ npm i limited-useAPI
LimitedUse
constructor(callback, limit)callback- The function to limit in use. Any arguments passed touse()will be passed to this function.limit- The maximum number of times the call can be called. Optional, default 1.
.use(...args)- Calls
callback(...args)and returns an immediately resolved promise of its return value.
- Calls
.disuse()- After this function is called, any future calls to
use()will have no effect.
- After this function is called, any future calls to
.isUsable- True if the number of uses so far is less than
limit.
- True if the number of uses so far is less than
.isDisused- True if the number of uses so far is at least equal to
limit.
- True if the number of uses so far is at least equal to
CollectiveUse
constructor(...usables)usables- Any number of objects that have.use()and.disuse()methods.
.use(...args)- Calls
use(...args)(to be executed asynchronously) on allusablesadded to this collection. Returns a promise that resolves to an array of each call's return value.
- Calls
.useSync(...args)- Calls
use(...args)synchronously on allusablesadded to this collection. Returns an array of each call's return value.
- Calls
.disuse()- After this function is called, this collection is marked as disused and
disuse()is called on allusablesthat had been added.
- After this function is called, this collection is marked as disused and
.isUsable- True if
disuse()has not yet been called on this collection and if at least one member is usable.
- True if
.isDisused- True if
disuse()has been called on this collection.
- True if
.add(...usables)- Adds
usables(Any number of objects with.use()and.disuse()) to the collection.
- Adds
.remove(usable)- Removes
usablefrom the collection. Returns true upon success.
- Removes
.clear()- Empties the collection.