The useful Javascript prototype functions

I want to share some Javascript prototype functions as below:

String.prototype.format = function (n, x, s, c) {
    /// <summary>
    /// Number.prototype.format(n, x, s, c)
    /// Example:
    /// 12345678.9.format(2, 3, ',', '.');  // "12,345,678.90"
    /// 123456.789.format(4, 4, ' ', ':');  // "12 3456:7890"
    /// 12345678.9.format(0, 3, '-');       // "12-345-679"
    /// </summary>
    /// <param name="n" type="type">length of decimal</param>
    /// <param name="x" type="type">length of whole part</param>
    /// <param name="s" type="type">sections delimiter</param>
    /// <param name="c" type="type">decimal delimiter</param>
    /// <returns type=""></returns>
    var re = '\\d(?=(\\d{' + (x || 3) + '})+' + (n > 0 ? '\\D' : '$') + ')';
    // console.log(this.toString());
    if (this.toString()) {
        var item = this.toString().replace(/,/g, '');
        var num = Number(item).toFixed(Math.max(0, ~~n));
        return (c ? num.replace('.', c) : num).replace(new RegExp(re, 'g'), '$&' + (s || ','));
    }
    return '';
};


String.prototype.replaceAll = function (search, replacement) {
    /// <summary>
    /// Replace all string in js
    /// </summary>
    /// <param name="search" type="type"></param>
    /// <param name="replacement" type="type"></param>
    /// <returns type=""></returns>
    var target = this;
    return target.replace(new RegExp(search, 'g'), replacement);
};


String.prototype.startsWith = function (word) {
    /// <summary>
    /// check whether starts With the word
    /// </summary>
    /// <param name="word" type="type"></param>
    /// <returns type=""></returns>
    return (this.indexOf(word) == 0);
};

//js startsWith function
String.prototype.endsWith = function (word) {
    /// <summary>
    /// check whether ends with the word
    /// </summary>
    /// <param name="word" type="type"></param>
    /// <returns type=""></returns>
    return str.indexOf(word, str.length - word.length) !== -1;
};

Date.prototype.addMonths = function (m) {
    /// <summary>
    /// Add months for date object
    /// </summary>
    /// <param name="m" type="type"></param>
    /// <returns type=""></returns>
    var d = new Date(this);
    var years = Math.floor(m / 12);
    var months = m - (years * 12);
    if (years) d.setFullYear(d.getFullYear() + years);
    if (months) d.setMonth(d.getMonth() + months);
    return d;
}

Date.prototype.addDays = function (days) {
    /// <summary>
    /// Add days for date object
    /// </summary>
    /// <param name="days" type="type"></param>
    /// <returns type=""></returns>
    var dat = new Date(this.valueOf());
    dat.setDate(dat.getDate() + days);
    return dat;
}

// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find
// find the element in array
// e.g  
//var currItem = dataSource.find(function (ds) {
//    return ds.startDate.getTime() == date.getTime()
//});
if (!Array.prototype.find) {
    Object.defineProperty(Array.prototype, 'find', {
        value: function (predicate) {
            // 1. Let O be ? ToObject(this value).
            if (this == null) {
                throw new TypeError('"this" is null or not defined');
            }

            var o = Object(this);

            // 2. Let len be ? ToLength(? Get(O, "length")).
            var len = o.length >>> 0;

            // 3. If IsCallable(predicate) is false, throw a TypeError exception.
            if (typeof predicate !== 'function') {
                throw new TypeError('predicate must be a function');
            }

            // 4. If thisArg was supplied, let T be thisArg; else let T be undefined.
            var thisArg = arguments[1];

            // 5. Let k be 0.
            var k = 0;

            // 6. Repeat, while k < len
            while (k < len) {
                // a. Let Pk be ! ToString(k).
                // b. Let kValue be ? Get(O, Pk).
                // c. Let testResult be ToBoolean(? Call(predicate, T, « kValue, k, O »)).
                // d. If testResult is true, return kValue.
                var kValue = o[k];
                if (predicate.call(thisArg, kValue, k, o)) {
                    return kValue;
                }
                // e. Increase k by 1.
                k++;
            }

            // 7. Return undefined.
            return undefined;
        }
    });
}


if (!Number.prototype.padLeft) {
    Number.prototype.padLeft = function (n, str) {
        /// <summary>
        /// pad left with 0
        /// e.g.  console.log((23).padLeft(5));     //=> '00023'
        /// </summary>
        /// <param name="n" type="type"></param>
        /// <param name="str" type="type"></param>
        /// <returns type=""></returns>
        return (this < 0 ? '-' : '') +
                Array(n - String(Math.abs(this)).length + 1)
                 .join(str || '0') +
               (Math.abs(this));
    }
}

// https://tc39.github.io/ecma262/#sec-array.prototype.includes
if (!Array.prototype.includes) {
    Object.defineProperty(Array.prototype, 'includes', {
        value: function (searchElement, fromIndex) {

            if (this == null) {
                throw new TypeError('"this" is null or not defined');
            }

            // 1. Let O be ? ToObject(this value).
            var o = Object(this);

            // 2. Let len be ? ToLength(? Get(O, "length")).
            var len = o.length >>> 0;

            // 3. If len is 0, return false.
            if (len === 0) {
                return false;
            }

            // 4. Let n be ? ToInteger(fromIndex).
            //    (If fromIndex is undefined, this step produces the value 0.)
            var n = fromIndex | 0;

            // 5. If n ≥ 0, then
            //  a. Let k be n.
            // 6. Else n < 0,
            //  a. Let k be len + n.
            //  b. If k < 0, let k be 0.
            var k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);

            function sameValueZero(x, y) {
                return x === y || (typeof x === 'number' && typeof y === 'number' && isNaN(x) && isNaN(y));
            }

            // 7. Repeat, while k < len
            while (k < len) {
                // a. Let elementK be the result of ? Get(O, ! ToString(k)).
                // b. If SameValueZero(searchElement, elementK) is true, return true.
                if (sameValueZero(o[k], searchElement)) {
                    return true;
                }
                // c. Increase k by 1. 
                k++;
            }

            // 8. Return false
            return false;
        }
    });
}

 229 total views,  1 views today

Share your vote!


You may also like...

Translate »