Skip to content

Commit

Permalink
Add method for getting call count of a function (#5)
Browse files Browse the repository at this point in the history
Fixes #4
  • Loading branch information
kevva authored and sindresorhus committed Jan 20, 2019
1 parent 32bca38 commit 1e9bbae
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 0 deletions.
8 changes: 8 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
'use strict';
const mimicFn = require('mimic-fn');

const calledFns = new WeakMap();

module.exports = (fn, opts) => {
// TODO: Remove this in v3
if (opts === true) {
Expand All @@ -15,9 +17,12 @@ module.exports = (fn, opts) => {

let ret;
let called = false;
let count = 0;
const fnName = fn.displayName || fn.name || '<anonymous>';

const onetime = function () {
calledFns.set(onetime, count++);

if (called) {
if (opts.throw === true) {
throw new Error(`Function \`${fnName}\` can only be called once`);
Expand All @@ -34,6 +39,9 @@ module.exports = (fn, opts) => {
};

mimicFn(onetime, fn);
calledFns.set(onetime, count++);

return onetime;
};

module.exports.callCount = fn => calledFns.get(fn);
12 changes: 12 additions & 0 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ const foo = onetime(() => i++);
foo(); //=> 0
foo(); //=> 0
foo(); //=> 0

onetime.callCount(foo); //=> 3
```

```js
Expand Down Expand Up @@ -59,6 +61,16 @@ Default: `false`

Throw an error when called more than once.

## onetime.callCount(fn)

Returns a number representing how many times `fn` is called.

#### fn

Type: `Function`

Function to get call count from.


## License

Expand Down
8 changes: 8 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,3 +14,11 @@ test('option to throw is called more than once', t => {
f();
t.throws(f, /Function .* can only be called once/);
});

test('`callCount` method', t => {
const f = m(() => {});
f();
f();
f();
t.is(m.callCount(f), 3);
});

0 comments on commit 1e9bbae

Please sign in to comment.