EcmaScript 6 – String.prototype.repeat()

One simple function that is on the roster to be released in EcmaScript 6 is String.prototype.repeat. The following can be used to define it in browsers which don’t currently have it defined natively:

String.prototype.repeat = String.prototype.repeat || function(count) {
    return Array(count >= 0 ? parseInt(count, 10) + 1 : -1).join(this);
};

Here are some examples of using this function (modified from the originals found on MDN):

alert("->".repeat(-1));     // RangeError
alert("->".repeat(0));      // ""
alert("->".repeat(1));      // "->"
alert("->".repeat(2));      // "->->"
alert("->".repeat(3.6));    // "->->->" (count will be converted to integer)
alert("->".repeat(1/0));    // RangeError

There is more information about this new JavaScript function here.

JavaScript – Fraction Part of a Number

One thing that is common knowledge about JavaScript and other languages is that floating point numbers are not always stored the way you think. Also doing math with these numbers is even more iffy. One thing I recently wanted to do was effectively the opposite of parseInt(). In other words, I just wanted the fractional part of the passed number to be returned. Thusly the following function was born:

/**
 * @license Copyright 2014 - Chris West - MIT Licensed
 */
(function(RGX) {
    frac = function(num) {
        return +(+num).toExponential().replace(RGX, function(m, neg, num, dot, offset) {
            var zeroes = Array(Math.abs(offset) + 2).join('0');
            num = (zeroes + num + (dot ? '' : '.') + zeroes).split('.');
            return +(neg + '.' + num.join('').slice(+offset + num[0].length));
        });
    };
})(/(-?)(\d+(\.?)\d*)e(.+)/);

I really got the idea from the first programming language I ever used: that of the Casio graphing calculators. The following are example calls and results for the function:

var a = frac(1.234);     // 0.234
var b = frac(56789e-3);  // 0.789
var c = frac(12345678);  // 0
var d = frac(-34.5697);  // -0.5697
var e = frac('-.9');     // -0.9
var f = frac(null);      // 0
var g = frac(undefined); // NaN
var h = frac('sdfa');    // NaN

Personally I thought it was strange that this function isn’t natively provided in most languages but there are some alternatives. One that works in some languages but not in JavaScript (nor in Python interestingly enough) is the following:

a = 34.5697;
fracPart = a % 1;
alert(fracPart);  // 0.5696999999999974

Another alternative method that seems like it should work but doesn’t in JavaScript is as follows:

a = 34.5697;
fracPart = a - parseInt(a);
alert(fracPart);  // 0.5696999999999974

For this reason, if you have a need to pull the decimal portion of a number out, feel free to use the frac function defined at the beginning of this post. 😎

JavaScript – Testing For Negative Zero

One thing that I always took for granted until last week was testing for negative numbers. What I mean is that I had no clue that -0 is actually different from 0. Interestingly enough when using strict equality to test the two values they still appear to be equal but they are in fact different. For this reason, I decided to write the following function:

function isNegative(n) {
  return ((n = +n) || 1 / n) < 0;
}

I admit that this function probably isn't that useful because I haven't thought of one time when you really need to know if a value is -0 or 0, but just in case I or anyone else in the future does need a way to differentiate, the above function should do the trick. The following are some examples of calling the function:

var a = isNegative(-Infinity); // true
var b = isNegative(-12);       // true
var c = isNegative(-0);        // true
var d = isNegative(0);         // false
var e = isNegative(34);        // false
var f = isNegative(Infinity);  // false
var g = isNegative("Hello");   // NaN -> false
var h = isNegative(undefined); // NaN -> false
var i = isNegative(null);      // 0 -> false
var j = isNegative(-null);     // -0 -> true
var k = isNegative("-5");      // -5 -> true
var l = isNegative("-0");      // -0 -> true
var m = isNegative("0");      // 0 -> false
var n = isNegative("6");      // 6 -> false
var o = isNegative("");      // 0 -> false

I'm guessing this is more than you ever wanted to know about negative numbers so I will end the post here. 😎