Search code examples
javascriptarrayspolyfills

Polyfill basics: How to implement a polyfill for Uint8Array.fill


Polyfill newbie here. I'm completely baffled by this simple case, in which I want to initialize a typed array:

var x = new Uint8Array(3).fill(42);
console.log(x);

This works fine in Chrome and Firefox: the console shows [42, 42, 42]. Safari, which does not support the fill method, throws this error: "TypeError: new Uint8Array(3).fill is not a function.". This makes perfect sense. So I figure I need to implement a polyfill, right? Right! MDN offers this one, but when I add this chunk of code nothing changes: Safari continues to throw the same error. Obviously I'm doing something wrong. And is this even this the right polyfill to use for Uint8Array?

Here's the code I'm executing (including the MDN polyfill):

if (!Array.prototype.fill) {
     Array.prototype.fill = 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;
   };
}


var x = new Uint8Array(3).fill(42);
console.log(x);

Any suggestions? Thanks!


Solution

  • (Just repeating @Rhumbori's comment, to close out my question...)

    Change these lines

    if (!Array.prototype.fill) {
     Array.prototype.fill = function(value) {
    

    to

    if (!Uint8Array.prototype.fill) {
     Uint8Array.prototype.fill = function(value) {