lib/concurrent/Race.js   A
last analyzed

Complexity

Total Complexity 7
Complexity/F 1.4

Size

Lines of Code 29
Function Count 5

Duplication

Duplicated Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 0
c 1
b 0
f 0
nc 1
dl 0
loc 29
rs 10
wmc 7
mnd 1
bc 6
fnc 5
bpm 1.2
cpm 1.4
noi 0
1
/**
2
 * This simple class allows some other code to race in execution, executing at
3
 * most N times.
4
 *
5
 * @param {int} [places] Maximum amount of calls to be made, defaults to 1
6
 *
7
 * @class
8
 */
9
function Race (places) {
10
  places = typeof places === 'number' ? places : 1
11
  var winners = 0
12
13
  /**
14
   * Adds new racer by wrapping target function in a safety wrapper that will
15
   * control it's non-execution in case race has been already won. Wrapped
16
   * function will return original result if it has won the race or undefined
17
   * if race has been lost.
18
   *
19
   * @param {Function} f Function to wrap
20
   * @param {*} [that] Thing that will be injected as `this` during the call
21
   * @return {Function}
22
   */
23
  this.racer = function (f, that) {
24
    return function () {
25
      if (winners >= places) { return }
26
      winners++
27
      return f.apply(that, arguments)
28
    }
29
  }
30
31
  this.getWinners = function () { return winners }
32
  this.getPlaces = function () { return places }
33
}
34
35
module.exports = {
36
  Race: Race
37
}
38