• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1var wrappy = require('wrappy')
2module.exports = wrappy(once)
3module.exports.strict = wrappy(onceStrict)
4
5once.proto = once(function () {
6  Object.defineProperty(Function.prototype, 'once', {
7    value: function () {
8      return once(this)
9    },
10    configurable: true
11  })
12
13  Object.defineProperty(Function.prototype, 'onceStrict', {
14    value: function () {
15      return onceStrict(this)
16    },
17    configurable: true
18  })
19})
20
21function once (fn) {
22  var f = function () {
23    if (f.called) return f.value
24    f.called = true
25    return f.value = fn.apply(this, arguments)
26  }
27  f.called = false
28  return f
29}
30
31function onceStrict (fn) {
32  var f = function () {
33    if (f.called)
34      throw new Error(f.onceError)
35    f.called = true
36    return f.value = fn.apply(this, arguments)
37  }
38  var name = fn.name || 'Function wrapped with `once`'
39  f.onceError = name + " shouldn't be called more than once"
40  f.called = false
41  return f
42}
43