polynom

by evgkch

JavaScript

class Polynom {
	static Dx(polynom) {
  	const DxPolynom = new Polynom(new Float32Array(polynom.matrix.length));
		DxPolynom.forEach((_, vec) => {
      DxPolynom.setVal(
        vec,
        (vec[0] + 1) * polynom.getVal([vec[0] + 1, vec[1]])
      );
    });
    return DxPolynom;
  }
  static Dy(polynom) {
  	const DyPolynom = new Polynom(new Float32Array(polynom.matrix.length));
		DyPolynom.forEach((_, vec) => {
      DyPolynom.setVal(
        vec,
        (vec[1] + 1) * polynom.getVal([vec[0], vec[1] + 1])
      );
    });
    return DyPolynom;
  }
	// matrix n * n
	constructor(matrix){
  	this.matrix = new Float32Array(matrix);
    this.hypot = Math.sqrt(this.matrix.length);
  }
  // returns val at x ** i * y ** j
  getIndexVec(vec) {
  	return vec[0] + vec[1] * this.hypot;
  }
  // returns vec at matrix view
  getVecIndex(i) {
  	return [i % this.hypot, Math.floor(i / this.hypot)];
  }
  getVal(vec) {
  	if (vec[0] < this.hypot && vec[1] < this.hypot)
  		return this.matrix[this.getIndexVec(vec)];
    else
    	return 0;
  }
  setVal(vec, val) {
  	if (vec[0] < this.hypot && vec[1] < this.hypot)
  		this.matrix[this.getIndexVec(vec)] = val;
  }
  forEach(cb) {
  	this.matrix.forEach((val, i) => cb(val, this.getVecIndex(i)));
  }
  print() {
  	let str = '';
    let started = false;
    this.forEach((val, vec) => {
    	const isFirstVal = vec[0] === 0 && vec[1] === 0;
			if (val !== 0)
      {      	        
      	if (started && !isFirstVal)
        	str += ` +`;
        
        str += ` ${getCoefficient(val, isFirstVal)}`
        
        const x = `${getPowerSymb(vec[0], 'x')}`;
        if (x.length > 0)
        	str += ` ${x}`;
        
        const y = `${getPowerSymb(vec[1], 'y')}`;
        if (y.length > 0)
        	str += ` ${y}`;
          
        started = true;
      }
    });
    return str;
  }
}

function getCoefficient(c, isFirst = false) {
	if (c === 0 || (isFirst ? false : c === 1)) return '';
  else return `${c}`;
}

function...