forked from component/counter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
120 lines (92 loc) · 1.89 KB
/
index.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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
/**
* Module dependencies.
*/
var domify = require('domify'),
digit = require('./digit.html'),
pad = require('left-pad');
/**
* Expose `Counter`.
*/
module.exports = Counter;
/**
* Initialize a new `Counter`.
*
* @api public
*/
function Counter(el, options) {
if (!(this instanceof Counter)) return new Counter(el, options);
options = options || {};
//container
this.el = el || domify('<div class="counter"></div>');
//save options
this.digitClass = options.digitClass;
//list of digit elements
this._digits = [];
//display value
this.n = 0;
//ensure two digits by default
this.digits(options.digits || 2);
}
/**
* Set the total number of digits to `n`.
*
* @param {Number} n
* @return {Counter}
* @api public
*/
Counter.prototype.digits = function(n){
this.total = n;
this.ensureDigits(n);
return this;
};
/**
* Add a digit element.
*
* @api private
*/
Counter.prototype.addDigit = function(){
var el = domify(digit);
if (this.digitClass) el.classList.add(this.digitClass);
this._digits.push(el);
this.el.appendChild(el);
};
/**
* Ensure at least `n` digits are available.
*
* @param {Number} n
* @api private
*/
Counter.prototype.ensureDigits = function(n){
while (this._digits.length < n) {
this.addDigit();
}
};
/**
* Update digit `i` with `val`.
*
* @param {Number} i
* @param {String} val
* @api private
*/
Counter.prototype.updateDigit = function(i, val){
var el = this._digits[i];
var n = parseInt(val, 10) + 1;
if (n > 9) n = 0;
el.textContent = val;
};
/**
* Update count to `n`.
*
* @param {Number} n
* @return {Counter}
* @api public
*/
Counter.prototype.update = function(n){
this.n = n;
var str = pad(n.toString(), this.total, '0');
this.ensureDigits(this.total);
for (var i = 0; i < this.total; ++i) {
this.updateDigit(this.total - i - 1, str[this.total - i - 1]);
}
return this;
};