clock.js

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
function zeroPad(n) {
  var str = "" + n;
  var pad = "00";
  return pad.substring(0, pad.length - str.length) + str;
}

function wrap(n, limit) {
  // wrap number around when it reaches limit
  // Similar to n %= limit but also takes care of negatives nicely.
  return ((n % limit) + limit) % limit;
}

var Time = function(hour, minute) {
  return {
    hour: hour,
    minute: minute,

    plus: function(minutes) {
      minute = this.minute + minutes;
      hour = this.hour + Math.floor(minute / 60);
      hour = wrap(hour, 24);
      minute = wrap(minute, 60);
      return Time(hour, minute);
    },

    minus: function(minutes) {
      return this.plus(-minutes);
    },

    equals: function(other) {
      return this.minute == other.minute && this.hour == other.hour;
    },

    toString: function() {
      return zeroPad(this.hour) + ":" + zeroPad(this.minute);
    }
  };
};

var Clock = {
  at: function(hour, minute) {
    minute = minute || 0;
    return new Time(hour, minute);
  }
};

module.exports = Clock;

Comments


You're not logged in right now. Please login via GitHub to comment