Long Multiplication 3

by whelkaholism

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div id="help"></div>
<hr/>
<div id="debug"></div>
<hr/>
<div id="working"></div>

CSS

* {
  line-height: 1.35em;
}

JavaScript

function PlaceMaths()
{
	var _this = this;
  var parts = ['units', 'tens', 'hundreds', 'thousands', 'ten-thousands', 'hundred-thousands', 'millions'];
  var hparts = {};
  for(var i = 0; i < parts.length; i++) hparts[parts[i]] = i;
  
  this.calcs = [];
  this.working = [];

	this.multiply = function(n1, n2)
  {
	  this.trace = [];
	  this.calcs = [];
    this.working = [];
    
  	this.trace.push('Multiply ' + n1 + ' by ' + n2);
    
    this.execute(n1, n2, this.colProduct);
    
    var last = this.calcs[this.calcs.length - 1];
    
    this.calcs.push({
    	help: 'Now you just need to add your two numbers together - so ' + last.working.units + ' + ' + last.working.tens + ' = ?'
    });
        
    $.each(this.calcs, function(i, o) { _this.trace.push(JSON.stringify(o)); });
  };
  
  var _prevp2;
  this.colProduct = function(n1, n2, p1, p2, n1maxcol, n2maxcol)
  {
  	var p2c = hparts[p2];
    var p1c = hparts[p1];
    var currworking = this.working[p2c] || 0;
    var final = null;
  
  	var res = times(n1, n2);
    var calc = {
    	n1: n1, 
    	op:'x',
      n2: n2,
      res: n1 * n2,
      v: res.v,
      carry: res.carry,
      on: p2
    };
    
    var prevcalc = this.calcs[this.calcs.length - 1];
    prevcalc && prevcalc.carry && (calc.plus = prevcalc.carry);
    prevcalc && prevcalc.shift && (calc.shift = prevcalc.shift);
    calc.tot = (calc.plus || 0) + calc.res;
    
    calc.working = (prevcalc && prevcalc.working) || {};
    
    var o = vc(calc.tot);
    calc.v = o.v;
    calc.carry = o.carry;
        
    if(p2 != _prevp2)
    {
    	p2c > 0 && (calc.shift = p2c);
              
    	this.calcs.push({
      	op: p2c > 0 ? '<<' : '_',
        on: calc.on,
      	help: 'Now working out the ' + calc.on + 
        (p2c > 0 ? '; so start a new workings-out line and put a zero in the units column; we\'ve just done those and we\'ll add them on at the end!' : '')
     	});
		}
    
    this.calcs.push(calc);

    currworking += calc.v * Math.pow(10,...