You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

index.js 1.3KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. 'use strict';
  2. var assert = require('assert');
  3. var WM = require('es6-weak-map');
  4. var hasNativeWeakMap = require('es6-weak-map/is-native-implemented');
  5. var defaultResolution = require('default-resolution');
  6. var runtimes = new WM();
  7. function isFunction(fn) {
  8. return (typeof fn === 'function');
  9. }
  10. function isExtensible(fn) {
  11. if (hasNativeWeakMap) {
  12. // Native weakmap doesn't care about extensible
  13. return true;
  14. }
  15. return Object.isExtensible(fn);
  16. }
  17. function lastRun(fn, timeResolution) {
  18. assert(isFunction(fn), 'Only functions can check lastRun');
  19. assert(isExtensible(fn), 'Only extensible functions can check lastRun');
  20. var time = runtimes.get(fn);
  21. if (time == null) {
  22. return;
  23. }
  24. var resolution = defaultResolution(timeResolution);
  25. return time - (time % resolution);
  26. }
  27. function capture(fn, timestamp) {
  28. assert(isFunction(fn), 'Only functions can be captured');
  29. assert(isExtensible(fn), 'Only extensible functions can be captured');
  30. timestamp = timestamp || Date.now();
  31. runtimes.set(fn, timestamp);
  32. }
  33. function release(fn) {
  34. assert(isFunction(fn), 'Only functions can be captured');
  35. assert(isExtensible(fn), 'Only extensible functions can be captured');
  36. runtimes.delete(fn);
  37. }
  38. lastRun.capture = capture;
  39. lastRun.release = release;
  40. module.exports = lastRun;