File: development/js/utils/counter.js
import type from './type';
/**
* Implementation of a simple counter class
*
* @module Utils
* @class Utils.Counter
* @static
*/
const between = (min, max, cur) => {
return cur <= max && cur >= min;
}
/**
* Returns a circular counter with value(), countTo(), countUp() and countDown()
* methods
*
* @method makeCounter
* @for Utils.Counter
* @param {number} max Maximum value of the counter
* @param {number} now Initial value to start counting from
* @param {number} min Minimum value of the counter
* @return {object} A counter object
*
* @example
* import makeCounter from './utils/counter';
*
* var counter = makeCounter(3, 1);
*
* counter.value();
* // -> 1
*
* counter.countUp(2).value();
* // -> 3
*
* counter.countUp().value();
* // -> 0
*
*/
const makeCounter = function (max, now, min) {
var _max = type.isNumber(max) && max >= 0 ? max : 0,
_min = type.isNumber(min) && min >= 0 ? min : 0,
_cur = type.isNumber(now) && between(_min, _max, now) ? now : 0;
return {
value() {
return _cur;
},
countTo(step) {
if (type.isNumber(step) && between(_min, _max, step)) {
_cur = step;
}
return this;
},
countUp(steps) {
if (!type.isNumber(steps)) {
_cur = _cur >= _max ? _min : _cur + 1;
return this;
}
while (steps > 0) {
this.countUp();
steps -= 1;
}
return this;
},
countDown(steps) {
if (!type.isNumber(steps)) {
_cur = _cur <= _min ? _max : _cur - 1;
return this;
}
while (steps > 0) {
this.countDown();
steps -= 1;
}
return this;
}
}
}
export default makeCounter;