首頁  >  文章  >  web前端  >  Number - JavaScript 挑戰

Number - JavaScript 挑戰

DDD
DDD原創
2024-10-31 09:03:02790瀏覽

Number - JavaScript Challenges

您可以在 GitHub 上找到本文中的所有程式碼。


與數字相關的挑戰


夾鉗

此函數將中間值限制在定義的最小和最大界限之間的範圍內。函數採用三個參數:首選值、最小值和最大允許值。

/**
 * @param {number} value
 * @param {number} lower
 * @param {number} upper
 * @return {number}
 */

function clamp(value, lower, upper) {
  return Math.min(upper, Math.max(lower, value));
}

// Usage example
console.log(clamp(12, 0, 1)); // => 1
console.log(clamp(12, 5, 13)); // => 12
console.log(clamp(12, 15, 100)); // => 15

四捨五入至小數點後兩位

/**
 * @param {any} value
 * @returns any
 */

function fixedTwoDigits(value) {
  if (typeof value !== "number") {
    return value;
  }

  return Number(value.toFixed(3).slice(0, -1));
}

// Usage example
console.log(fixedTwoDigits(Math.random())); // => 0.xx

大整數加法

/**
 * @param {string} numStr1
 * @param {string} numStr2
 * @return {string}
 */

function add(num1, num2) {
  const num1Arr = num1.split("").map(Number);
  const num2Arr = num2.split("").map(Number);
  let carry = 0;
  let result = [];

  while (num1Arr.length || num2Arr.length || carry) {
    const sum = (num1Arr.pop() ?? 0) + (num2Arr.pop() ?? 0) + carry;
    carry = sum > 9 ? 1 : 0;
    result.push(sum % 10);
  }

  return result.reverse().join("");
}

// Usage example
console.log(add("999999999999999999", "1")); // => '1000000000000000000'

給數字加上逗號

/**
 * @param {number} num
 * @return {string}
 */

function addComma(num) {
  const [integerStr, floatStr] = String(num).split(".");
  let count = 0;
  let result = "";

  for (let i = integerStr.length - 1; i >= 0; i -= 1) {
    count += 1;
    result = integerStr[i] + result;

    if (count % 3 === 0 && i !== 0) {
      result = "," + result;
    }
  }

  return floatStr ? result + `.${floatStr}` : result;
}

// Usage example
console.log(addComma(1)); // => '1'
console.log(addComma(1000)); // => '1,000'
console.log(addComma(-12345678)); // =>  '-12,345,678'
console.log(addComma(12345678.12345)); // =>  '12,345,678.12345'

為銀行號碼新增空格

/**
 * @param {string} num
 * @return {string}
 */

function addSpacesEveryFourDigits(num) {
  const numStr = String(num);
  let result = "";

  for (let i = 0; i < numStr.length; i += 1) {
    result += numStr[i];

    if ((i + 1) % 4 === 0 && i + 1 !== numStr.length) {
      result += " ";
    }
  }

  return result.trim();
}

// Example usage:
console.log(addSpacesEveryFourDigits("1234567890")); // => "1234 5678 90"

阿拉伯數字轉漢字

/**
 * @param {string} arabicNumber
 * @return {string}
 */

function digitToChinese(digit) {
  const digitMap = ["零", "一", "二", "三", "四", "五", "六", "七", "八", "九"];
  return digitMap[digit];
}

function arabicToChineseNumber(arabicNumber) {
  let chineseNumber = "";

  for (let i = 0; i < arabicNumber.length; i++) {
    chineseNumber += digitToChinese(arabicNumber[i]);
  }

  return chineseNumber;
}

// Usage example
console.log(arabicToChineseNumber("12345")); // => 一二三四五

合併連續數字

/**
 * @param {Array} Array
 * @return {arr}
 */

function mergeContinousNumbers(arr) {
  if (!arr || arr.length === 0) {
    return [];
  }

  const merged = [];
  let start = arr[0];
  let end = arr[0];

  for (let i = 1; i < arr.length; i += 1) {
    if (arr[i] === end + 1) {
      end = arr[i];
    } else {
      if (start === end) {
        merged.push(String(start));
      } else {
        merged.push(`${start}->${end}`);
      }

      start = end = arr[i];
    }
  }

  if (start === end) {
    merged.push(String(start));
  } else {
    merged.push(`${start}->${end}`);
  }

  return merged;
}

// Usage example
console.log(mergeContinousNumbers([1, 2, 3, 4, 6, 7, 9, 13, 15])); // => ['1->4', '6->7', '9', '13', '15']

參考

  • clamp() - MDN
  • 偉大的前端
  • 62。實作 BigInt 加法 - BFE.dev

以上是Number - JavaScript 挑戰的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn