Skip to content

gaslamp


Class: Counter

Named counter storage backed by JunkPocket.

Each instance holds any number of independent counters, identified by a string key. When no key is supplied, a built-in default counter is used.

Remarks

Used by AfterGlow to back its count(), countReset(), and getCount() methods. Can also be used standalone for tracking event frequencies or call counts in GAS scripts.

Since

0.20.0

Example

TypeScript
const counter = new Counter('app-metrics');
counter.increment('errors');
counter.increment('errors');
console.log(counter.getValue('errors')); // 2
counter.reset('errors');
console.log(counter.getValue('errors')); // 0

Constructors

Constructor

new Counter(options?): Counter

Creates a new Counter instance.

Parameters

options?

string | CounterOptions

Instance name as a string, or a CounterOptions object. Defaults to "Counter" when omitted.

Returns

Counter

Example

TypeScript
const c1 = new Counter('my-counter');
const c2 = new Counter({ name: 'metrics' });
const c3 = new Counter(); // name defaults to "Counter"

Gears

increment()

increment(key?): number

Increments a counter by 1 and returns the new value.

Parameters

key?

string

Counter key to increment. Uses the default counter when omitted.

Returns

number

New counter value after incrementing.

Example

TypeScript
counter.increment();           // 1  (default counter)
counter.increment('errors');   // 1  (named counter)
counter.increment('errors');   // 2

getValue()

getValue(key?): number

Returns the current value of a counter.

Parameters

key?

string

Counter key to read. Uses the default counter when omitted.

Returns

number

Current counter value, or 0 if the key has never been incremented.

Example

TypeScript
counter.increment('hits');
counter.increment('hits');
counter.getValue('hits'); // 2
counter.getValue('unknown'); // 0

reset()

reset(key?): void

Resets a counter to zero.

Parameters

key?

string

Counter key to reset. Uses the default counter when omitted.

Returns

void

Example

TypeScript
counter.increment('errors');
counter.increment('errors');
counter.reset('errors');
counter.getValue('errors'); // 0

getName()

getName(): string

Returns the name of this counter instance.

Returns

string

The name string passed at construction time.

Example

TypeScript
const counter = new Counter('api-calls');
counter.getName(); // "api-calls"

Other

defaultName

readonly static defaultName: "Counter" = "Counter"


defaultCounterKey

readonly static defaultCounterKey: "_default" = "_default"