dreamerhammer / learning

0 stars 0 forks source link

Better ways in Javascript #2

Open dreamerhammer opened 5 years ago

dreamerhammer commented 5 years ago

1. Check if defineProperty is available

var defineProperty = (function() {
    // IE 8 only supports `Object.defineProperty` on DOM elements.
    try {
    var object = {};
    var $defineProperty = Object.defineProperty;
    var result = $defineProperty(object, object, object) && $defineProperty;
    } catch (exception) {}
    return result;
}());
console.log(!!defineProperty)

2. polyfill of String.prototype.repeat

String.prototype.repeat = function (count) {
   'use strict';
    if (this == null) {
        throw new TypeError('can\'t convert ' + this + ' to object');
    }
    var str = '' + this;
    count = +count;
    if (count != count) {
        count = 0;
    }
    if (count < 0) {
        throw new RangeError('repeat count must be non-negative');
    }
    if (count == Infinity) {
        throw new RangeError('repeat count must be less than infinity');
    }
    count = Math.floor(count);
    if (str.length == 0 || count == 0) {
        return '';
    }
    if (str.length * count >= 1 << 28) {
        throw new RangeError('repeat count must not overflow maximum string size');
    }
    var rpt = '';
    for (; ;) {
        if ((count & 1) == 1) {
            rpt += str;
        }
    count >>>= 1;
    if (count == 0) {
        break;
    }
    str += str;
    }
    return rpt;
}