JavaScript Snippet – Using Degrees with Cosine, Sine & Tangent

Now Available in YourJS

Yesterday I was working with Math.cos, Math.sin and Math.tan and was thinking it would be nice to have the equivalent functions which accept the values in degrees instead of radians. For that reason I wrote the following definitions for Math.cosd, Math.sind and Math.tand:

After executing the above 5 lines you will be able to get the cosine at 45° by doing Math.cosd(45) or the sine at 75° by doing Math.sind(75) or the tangent at 135° by doing Math.tand(135). WARNING: this does extend a built-in object. If you would like these functions in a separate Degrees object so as to avoid mutating a built-in object you could use this:

(function (R) {
  Degrees = {
    cosd: function(d) { return Math.cos(d * R); },
    sind: function(d) { return Math.sin(d * R); },
    tand: function(d) { return Math.tan(d * R); }
  };
})(Math.PI / 180);

Have fun! šŸ˜Ž

JavaScript – Number.getOrdinalFor()

Now Available in YourJS

When dealing with numbers, at times for presentation’s sake, we need to add ordinals to numbers. For example, instead of today is the “September 28”, you may want to say that it is the “28th of September”. I wrote the following code snippet to easily add the ordinal for any integer in JavaScript:

(function(o) {
  Number.getOrdinalFor = function(intNum, includeNumber) {
    return (includeNumber ? intNum : "")
      + (o[((intNum = Math.abs(intNum % 100)) - 20) % 10] || o[intNum] || "th");
  };
})([,"st","nd","rd"]);

Description

Gets the appropriate ordinal (“st”, “nd”, “rd”, or “th”) for the specified integer.

Parameters

  1. intNum:
    The number for which the ordinal will be produced.
  2. includeNumber:
    The value that is evaluated as a boolean to determine whether or not to include the specified integer in the returned string. This is optional and thusly defaults to false.

Returns

The string containing the ordinal for the specified integer. If the second parameter evaluates to true, the specified number will returned with the ordinal appended to it.

Examples

The following shows how you could call this function:

var num1 = 1,
    num2 = 12,
    num3 = 123,
    num4 = 1432;
var str1 = Number.getOrdinalFor(num1, true), // 1st
    str2 = Number.getOrdinalFor(num2, true), // 12th
    str3 = Number.getOrdinalFor(num3, true), // 123rd
    str4 = Number.getOrdinalFor(num4, true); // 1432nd

You could even get a little fancy and run this on all of the numbers in a string by doing something like the following:

var str = "1, 2, and 3 place will get medals while 4 and later will get Cinnabons.";
alert(str.replace(/(\d+)/g, Number.getOrdinalFor));

The reason the above example works is because the first parameter that is passed into the function is the entire match, which in this case is the number found. The second parameter passed is the exact same thing, which since it is a string of one or more characters, will always evaluate to true. Having these two circumstances in mind, in every case that a number is found, the same number with the appropriate ordinal is replaces the number in the string.

You could modify it a bit to make it work with any numbers by doing something like this:

var str = "1, 2, 3, 4.5, 6, and 7.8 are all numbers.";
alert(str.replace(/\d*\.\d+|(\d+)/g, function(match, int) {
  return int
    ? Number.getOrdinalFor(parseInt(int, 10), 1)
    : match;
}));

I will not go into detail and explain why the above works. If you don’t understand it, I suggest, if you want to become really proficient in the language, that you dissect the code. Many times, if we try things out ourselves, we will be more likely to remember and understand why something works and when we can use something like that again. Of course, if you do get to a point where you just don’t understand something, leave a comment below and I will help you out. Have fun!!!

JavaScript – String.prototype.replaceAll()

Now Available in YourJS

For those of you who don’t know too much about regular expressions or just want to be able to replace every occurrence of a substring with something else, perhaps this definition for the replaceAll() function of all instances of String object will prove beneficial:

String.prototype.replaceAll = function(target, replacement) {
  return this.split(target).join(replacement);
};

Yep, that’s it! No more code is necessary in order to make the following work as expected:

// Display:  Chriz Wezt
alert("Chris West".replaceAll("s", "z"));

// Display:  Peter Piker kicks kekkers.
alert("Peter Piper picks peppers.".replaceAll("p", "k"));

// Display:  Anteedeesestableeshmentareeaneesm
alert("Antidisestablishmentarianism".replaceAll("i", "ee"));

By default, this function also works with regular expressions. Regardless of the global flag being set for a regular expression, this function will replace each match that is found.