1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
function IRRCC(ar) {
  var have_pos = false, have_neg = false, iterations = 100, epsilon = 1.0e-8, result;

  for (i = 0; i < ar.length; i++) {
    if (ar[i][0] > 0.0) {
      have_pos = true;
      if (have_neg) {
        break;
      }
    } else if (ar[i][0] < 0.0) {
      have_neg = true;
      if (have_pos) {
        break;
      }
    }
  }
  if (have_neg && have_pos){
    var u = 0.0, converged = false;
    var base_time = new Date(ar[0][1]).getTime(), this_time;
    
    const years = [];
    for (j = 0; j < ar.length; j++) {
      this_time = new Date(ar[j][1]).getTime();
      years[j] = (this_time - base_time) / (365.25 * 24 * 3600 * 1000);
    }

    for (i = 0; i < iterations; i++) {
      var pos = 0.0, d_pos = 0.0, neg = 0.0, d_neg = 0.0;

      for (j = 0; j < ar.length; j++) {
        var an_amount = ar[j][0], a_time = years[j];
        var tmp = an_amount * Math.exp(u * a_time);

        if (an_amount > 0.0) {
          pos += tmp;
          d_pos += tmp * a_time;
        } else {
          neg -= tmp;
          d_neg -= tmp * a_time;
        }
      }

      var delta = Math.log(neg / pos) / (d_neg / neg - d_pos / pos);
      u -= delta;

      if (Math.abs(delta) < epsilon) {
        converged = true;
        break; 
      }
    }
    if (converged) {
      result = -u;
    } else {
      result = "No convergence";
    }
  } else {
    result = "Bad data";
  }
  return result;
}