John Abraham
John Abraham

Reputation: 18781

How to write a polyfill for array.prototype.find as a custom method?

Question: How do I write a custom Array.prototype.find() and not add it to the Array.prototype? I would like to keep my original code as close to the original as possible

Why? I heard it was bad practice to put a polyfill on Array.prototype.

I have used Array.prototype.find() and I'm running into problems on ios9 mobile.

this.currentModalInfo = this.langDataService.transformedData
    .find(function(obj) {
      if (obj.docs.language_code === routeParam) {
        return obj;
      }
    });

I found a polyfill on mdn:

if (!Array.prototype.find) {
  Array.prototype.find = function(predicate) {
    if (this === null) {
      throw new TypeError('Array.prototype.find called on null or undefined');
    }
    if (typeof predicate !== 'function') {
      throw new TypeError('predicate must be a function');
    }
    var list = Object(this);
    var length = list.length >>> 0;
    var thisArg = arguments[1];
    var value;

    for (var i = 0; i < length; i++) {
      value = list[i];
      if (predicate.call(thisArg, value, i, list)) {
        return value;
      }
    }
    return undefined;
  };
}

Upvotes: 2

Views: 1074

Answers (1)

Sean Vieira
Sean Vieira

Reputation: 159895

Simply replace the use of this in your polyfill with the use of an argument to your function:

function findIn(array, predicate) {
  if (array === null) {
    throw new TypeError('findIn called on null or undefined');
  }
  if (typeof predicate !== 'function') {
    throw new TypeError('predicate must be a function');
  }
  var list = Object(array);
  var length = list.length >>> 0;
  var thisArg = arguments[2];
  var value;

  for (var i = 0; i < length; i++) {
    value = list[i];
    if (predicate.call(thisArg, value, i, list)) {
      return value;
    }
  }
  return undefined;
}

Then your function call becomes:

this.currentModalInfo = findIn(this.langDataService.transformData, function(obj) {
  return obj.docs.language_code === routeParam;
});

Upvotes: 3

Related Questions