Home Web Front-end JS Tutorial Number - JavaScript Challenges

Number - JavaScript Challenges

Oct 31, 2024 am 09:03 AM

Number - JavaScript Challenges

You can find all the code in this post on GitHub.


Number related challenges


Clamp

The function clamps a middle value within a range between a defined minimum and maximum bound. The function takes three parameters: a preferred value, a minimum value, and a maximum allowed value.

/**
 * @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
Copy after login

Round to two decimal places

/**
 * @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
Copy after login

Big integer addition

/**
 * @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'
Copy after login

Add comma to numbers

/**
 * @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'
Copy after login

Add space to bank numbers

/**
 * @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"
Copy after login

Arabic numerals to Chinese characters

/**
 * @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")); // => 一二三四五
Copy after login

Merge continuous numbers

/**
 * @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']
Copy after login

Reference

  • clamp() - MDN
  • GreatFrontEnd
  • 62. implement BigInt addition - BFE.dev

The above is the detailed content of Number - JavaScript Challenges. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot Article

Hot Article

Hot Article Tags

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Replace String Characters in JavaScript Replace String Characters in JavaScript Mar 11, 2025 am 12:07 AM

Replace String Characters in JavaScript

jQuery Check if Date is Valid jQuery Check if Date is Valid Mar 01, 2025 am 08:51 AM

jQuery Check if Date is Valid

jQuery get element padding/margin jQuery get element padding/margin Mar 01, 2025 am 08:53 AM

jQuery get element padding/margin

Top 5 Date Manipulation JS Plugins Top 5 Date Manipulation JS Plugins Feb 28, 2025 am 12:34 AM

Top 5 Date Manipulation JS Plugins

10 jQuery Accordions Tabs 10 jQuery Accordions Tabs Mar 01, 2025 am 01:34 AM

10 jQuery Accordions Tabs

10 Worth Checking Out jQuery Plugins 10 Worth Checking Out jQuery Plugins Mar 01, 2025 am 01:29 AM

10 Worth Checking Out jQuery Plugins

jquery add scrollbar to div jquery add scrollbar to div Mar 01, 2025 am 01:30 AM

jquery add scrollbar to div

HTTP Debugging with Node and http-console HTTP Debugging with Node and http-console Mar 01, 2025 am 01:37 AM

HTTP Debugging with Node and http-console

See all articles