Sling Academy
Home/JavaScript/Creating Utility Libraries to Extend Math in JavaScript

Creating Utility Libraries to Extend Math in JavaScript

Last updated: December 12, 2024

Utility libraries can greatly enhance the capabilities of a programming language's standard features. In JavaScript, the Math object provides basic functionalities such as calculations of constants, and trigonometric functions, but sometimes, more complex mathematical operations are also needed. In this article, we’ll focus on creating a utility library to extend the Math functionalities in JavaScript.

Setting Up Your Environment

To get started, open your code editor and create a new JavaScript file named mathUtils.js. This will be the file where our utility library is developed.

Defining the Basic Structure

First, define the basic structure of your utility library. We will use an Immediately Invoked Function Expression (IIFE) to encapsulate our library and avoid polluting the global scope.

(function() {
  const MathUtils = {};

  // Export to global scope
  if (typeof window !== 'undefined') {
    window.MathUtils = MathUtils;
  }
})();

Adding Utility Functions

Let’s add some utility functions to our library. Start simple with functions for computing factorial, the greatest common divisor (GCD), and operations involving prime numbers.

Factorial Function

The factorial of a number n is defined as the product of all positive integers less than or equal to n. Here is how you can implement it:

MathUtils.factorial = function(n) {
  if (n === 0 || n === 1) {
    return 1;
  }
  let result = 1;
  for (let i = 2; i <= n; i++) {
    result *= i;
  }
  return result;
};

Greatest Common Divisor (GCD)

The Euclidean algorithm efficiently calculates the GCD of two numbers. Here’s the implementation:

MathUtils.gcd = function(a, b) {
  while (b !== 0) {
    let temp = b;
    b = a % b;
    a = temp;
  }
  return a;
};

Prime Check

Checking if a number is prime can be approached in a few different ways. Here’s an implementation of a prime-checking function:

MathUtils.isPrime = function(n) {
  if (n <= 1) return false;
  if (n <= 3) return true;
  if (n % 2 === 0 || n % 3 === 0) return false;

  for (let i = 5; i * i <= n; i += 6) {
    if (n % i === 0 || n % (i + 2) === 0) return false;
  }

  return true;
};

Random Number Generators

Random number generation is useful in many applications. JavaScript's Math.random() produces pseudo-random numbers between 0 and 1, which you can further extend:

MathUtils.randomInt = function(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
};

Testing Your Library

To test the functions, open an HTML file and include your mathUtils.js file using a script tag, then run some sample tests:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Math Library Test</title>
</head>
<body>
  <script src="mathUtils.js"></script>
  <script>
    console.log(MathUtils.factorial(5)); // Output: 120
    console.log(MathUtils.gcd(27, 12));  // Output: 3
    console.log(MathUtils.isPrime(29));  // Output: true
    console.log(MathUtils.randomInt(1, 10)); // Output: random number between 1 and 10
  </script>
</body>
</html>

Conclusion

Expanding JavaScript’s Math library can be incredibly beneficial for applications requiring more advanced arithmetic capabilities. By implementing utility functions such as factorial, GCD, and prime-checking, we ensure a broader and more customized approach to mathematics in our applications. As you continue to build more complex functionalities, remember to encapsulate your functions and grow your library while keeping performance optimized.

Next Article: Supporting International Formats with Numeric Localization in JavaScript

Previous Article: Adopting Defensive Programming Techniques for JavaScript Math

Series: JavaScript Numbers

JavaScript

You May Also Like

  • Handle Zoom and Scroll with the Visual Viewport API in JavaScript
  • Improve Security Posture Using JavaScript Trusted Types
  • Allow Seamless Device Switching Using JavaScript Remote Playback
  • Update Content Proactively with the JavaScript Push API
  • Simplify Tooltip and Dropdown Creation via JavaScript Popover API
  • Improve User Experience Through Performance Metrics in JavaScript
  • Coordinate Workers Using Channel Messaging in JavaScript
  • Exchange Data Between Iframes Using Channel Messaging in JavaScript
  • Manipulating Time Zones in JavaScript Without Libraries
  • Solving Simple Algebraic Equations Using JavaScript Math Functions
  • Emulating Traditional OOP Constructs with JavaScript Classes
  • Smoothing Out User Flows: Focus Management Techniques in JavaScript
  • Creating Dynamic Timers and Counters with JavaScript
  • Implement Old-School Data Fetching Using JavaScript XMLHttpRequest
  • Load Dynamic Content Without Reloading via XMLHttpRequest in JavaScript
  • Manage Error Handling and Timeouts Using XMLHttpRequest in JavaScript
  • Handle XML and JSON Responses via JavaScript XMLHttpRequest
  • Make AJAX Requests with XMLHttpRequest in JavaScript
  • Customize Subtitle Styling Using JavaScript WebVTT Integration