-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathindex.js
More file actions
111 lines (92 loc) · 1.87 KB
/
index.js
File metadata and controls
111 lines (92 loc) · 1.87 KB
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
/**
* Module dependencies.
*/
var domify = require('domify')
, digit = require('./digit');
/**
* Expose `Counter`.
*/
module.exports = Counter;
/**
* Initialize a new `Counter`.
*
* @api public
*/
function Counter() {
this.el = domify('<div class="counter"></div>');
this._digits = [];
this.n = 0;
this.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);
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;
var curr = el.querySelector('.counter-top span').textContent;
el.querySelector('.counter-next span').textContent = n;
el.querySelector('.counter-top span').textContent = val;
el.querySelector('.counter-bottom span').textContent = val;
if (val == curr) return;
el.classList.add('flip');
setTimeout(function(){
el.classList.remove('flip');
}, 200);
};
/**
* Update count to `n`.
*
* @param {Number} n
* @return {Counter}
* @api public
*/
Counter.prototype.update = function(n){
this.n = n;
var str = n.toString();
var len = str.length;
var digits = Math.max(len, this.total);
this.ensureDigits(len);
for (var i = 0; i < len; ++i) {
this.updateDigit(digits - i - 1, str[len - i - 1]);
}
return this;
};