algs4js
Version:
Basic algorithms and data structures implemented with es6
76 lines (62 loc) • 2.43 kB
JavaScript
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _LogUtil = require('../util/LogUtil');
var _LogUtil2 = _interopRequireDefault(_LogUtil);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
/**
* Class Factorial
*
* Exposes static fucntionality for generating the factorial of a number.
*/
var Factorial = function () {
function Factorial() {
_classCallCheck(this, Factorial);
}
_createClass(Factorial, null, [{
key: 'validate',
/**
* Validates if the passed in number is an integer of zero or greater
*
* @param {number} num, the number to validate
* @throws {Error} error, if not an integer >= 0
*/
value: function validate(num) {
var isValid = Number.isInteger(num) && num >= 0;
_LogUtil2.default.debug('isValid for ' + num + ': ' + isValid);
if (!isValid) {
throw new Error(num + ' is not a valid integer >= 0');
}
}
/**
* Uses dynamic programming to calculate the factorial of a number, n!.
*
* Algorithm:
* X(i) = Sequence {1, 2, 3, ..., i}
* F(i) = Factorial for X(i)
* F(1) = 1;
* F(i) = F(i-1) * X(i)
*
* @param {number} num, the number to calculate its factorial
* @returns {number} the factorial
*/
}, {
key: 'calc',
value: function calc(num) {
this.validate(num);
_LogUtil2.default.debug('Calculating the factorial of ' + num);
var fim1 = 1;
var fi = fim1;
for (var i = 2; i <= num; i++) {
fi = fim1 * i;
fim1 = fi;
}
return fi;
}
}]);
return Factorial;
}();
exports.default = Factorial;
;