Наименьший общий делитель JavaScript, TypeScript

Код добавляет функцию nod() на прототип массива (Array).

declare interface Array<T> {
  nod(): number;
}

Array.prototype.nod = function () {
  let x = this[0];
  for (let i = 1; i < this.length; i++) {
    let y = this[i];
    while (x && y) x > y ? (x %= y) : (y %= x);
    x += y;
  }
  if (typeof x !== "number" || isNaN(x))
    throw new TypeError("Return type is not 'number'.");

  return x;
};

console.log([1.5, 2, 5, 6, 7].nod()); // 0.5
Array.prototype.nod = function () {
  let x = this[0];
  for (let i = 1; i < this.length; i++) {
    let y = this[i];
    while (x && y) x > y ? (x %= y) : (y %= x);
    x += y;
  }

  if (typeof x !== "number" || isNaN(x))
    throw new TypeError("Return type is not 'number'.");

  return x;
};

console.log([1.5, 2, 5, 6, 7].nod()); // 0.5

Comments are closed, but trackbacks and pingbacks are open.