Long multiplcation 4 (PMaths)
by whelkaholism
HTML
<div id="t">
</div>
CSS
#t { white-space: pre-line }
JavaScript
function log(s) {
document.getElementById('t').append(s + '\r\n');
}
function j(o) {
return JSON.stringify(o);
}
function PNumber(n) {
var _this = this;
var _cols = ['mil', 'hth', 'tth', 'th', 'h', 't', 'u'];
var _mult = {};
var _idxs = {};
_cols.forEach(function(k, i) {
_idxs[k] = i;
_mult[k] = Math.pow(10, _cols.length - i - 1);
});
_cols.forEach(function(k) {
var mult = _mult[k];
var x = Math.floor(n / mult);
n = n - (x * mult);
//log(j({ k:k, mult:mult, x:x, n:n}));
if (x > 0)
_this[k] = x;
});
this.next = function(c) {
return _cols[_idxs[c] - 1] || null;
};
this.valueOf = function() {
var res = 0;
_cols.forEach(function(k) {
_this[k] && (res += (_this[k] * _mult[k]));
});
return res;
};
this.eachColumn = function(f) {
for (var i = _cols.length - 1; i > 0; i--) {
(typeof(this[_cols[i]]) != 'undefined') && f(_cols[i], _this[_cols[i]]);
}
};
this.zero = function() {
this.eachColumn(function(c, v) {
_this[c] = 0;
});
return this;
};
}
var PMaths = function(options) {
var _this = this;
var _events = options && options.events;
this._sum = function() {
var res = 0;
[].forEach.call(arguments, function(x) {
res += x.valueOf();
});
return res;
};
this._add = function(pn1, pn2) {
return new PNumber(pn1.valueOf() + pn2.valueOf());
}
this.add = function() {
var res = new PNumber();
var args = [];
for (var i = 0; i < arguments.length; i++) args.push(arguments[i]);
var carries = new PNumber(this._sum.apply(this, args)).zero();
log('carries:' + j(carries));
carries.eachColumn(function(c, v) {
var a = [];
args.forEach(function(pn) {
a.push(pn[c]);
});
_events && _events.add && _events.add({
op: 'add',
col: c,
values: a,
carried: carries[c]
});
a.push(carries[c]);
var csum =...