jenny
jenny

Reputation: 277

fill() not supported in IE11

I have the following syntax. I am new to ES6 syntax.

const renderLoading = () => Array(20).fill('').map(() => <ExpampleLine/>);

The fill() command is not supported in Internet explorer. Is there any work around for fill() alone or should I rewrite whole syntax. Need some help with the syntax.

Upvotes: 3

Views: 7520

Answers (2)

mvermand
mvermand

Reputation: 6117

And this is a TypeScript compliant variant:

if (!Array.prototype.fill) {
    Object.defineProperty(Array.prototype, 'fill', {
        value: function(value) {

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

            const O = Object(this);
            // tslint:disable-next-line:no-bitwise
            const len = O.length >>> 0;
            const start = arguments[1];
            // tslint:disable-next-line:no-bitwise
            const relativeStart = start >> 0;

            let k = relativeStart < 0 ?
                Math.max(len + relativeStart, 0) :
                Math.min(relativeStart, len);

            const end = arguments[2];
            // tslint:disable-next-line:no-bitwise
            const relativeEnd = end === undefined ? len : end >> 0;

            const final = relativeEnd < 0 ?
                Math.max(len + relativeEnd, 0) :
                Math.min(relativeEnd, len);

            while (k < final) {
                O[k] = value;
                k++;
            }

            return O;
        }
    });
}

Upvotes: 1

Conan
Conan

Reputation: 2709

Use a polyfill:

if (!Array.prototype.fill) {
  Object.defineProperty(Array.prototype, 'fill', {
    value: function(value) {

      // Steps 1-2.
      if (this == null) {
        throw new TypeError('this is null or not defined');
      }

      var O = Object(this);

      // Steps 3-5.
      var len = O.length >>> 0;

      // Steps 6-7.
      var start = arguments[1];
      var relativeStart = start >> 0;

      // Step 8.
      var k = relativeStart < 0 ?
        Math.max(len + relativeStart, 0) :
        Math.min(relativeStart, len);

      // Steps 9-10.
      var end = arguments[2];
      var relativeEnd = end === undefined ?
        len : end >> 0;

      // Step 11.
      var final = relativeEnd < 0 ?
        Math.max(len + relativeEnd, 0) :
        Math.min(relativeEnd, len);

      // Step 12.
      while (k < final) {
        O[k] = value;
        k++;
      }

      // Step 13.
      return O;
    }
  });
}

As provided here: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/fill?v=example#Polyfill

Upvotes: 9

Related Questions