Skip to content
This repository has been archived by the owner on Jan 26, 2022. It is now read-only.

"Fine" polyfill #47

Open
taralx opened this issue May 30, 2021 · 3 comments
Open

"Fine" polyfill #47

taralx opened this issue May 30, 2021 · 3 comments

Comments

@taralx
Copy link

taralx commented May 30, 2021

(As opposed to "rough" polyfill.)

I probably have some errors in here, but I believe this matches the spec text.

Array.prototype.at = function at(k) {
  // 1. Let O be ? ToObject(this value)
  if (this == null) {
    throw new TypeError("Array.prototype.at called on null or undefined");
  }
  const O = Object(this);
  // 2. Let len be ? LengthOfArrayLike(O).
  const len = Math.min(Math.max(Math.trunc(O.length) || 0, 0), 2097151);
  k = Math.trunc(k) || 0;
  if (k < 0) k += len;
  if (0 <= k && k < len) return O[k];
}
Array.prototype[Symbol.unscopables].at = true;

String.prototype.at = function at(k) {
  // 1. Let O be ? RequireObjectCoercible(this value).
  if (this == null) {
    throw new TypeError("String.prototype.at called on null or undefined");
  }
  // 2. Let S be ? ToString(O).
  const S = String.prototype.concat.call(this);
  k = Math.trunc(k) || 0;
  if (k < 0) k += S.length;
  return S[k];
}

(function (TypedArray) {
  TypedArray.prototype.at = function at(k) {
    const len = Reflect.get(TypedArray.prototype, "length", this);
    k = Math.trunc(k) || 0;
    if (k < 0) k += len;
    return this[k];
  }
})(Object.getPrototypeOf(Int8Array));
@ljharb
Copy link
Member

ljharb commented May 31, 2021

@SebastianSimon
Copy link

if (k < 0) k += S.length; should be if (k < 0) k += len; in the TypedArray polyfill.

Also, wouldn’t it be better to check the property’s existence first?

if(!Array.prototype.hasOwnProperty("at")){
  Object.defineProperty(Array.prototype, "at", {
    writable: true,
    configurable: true,
    value: {
      at(n){
        // Polyfill for Array.prototype.at here.
      }
    }.at
  });
}

(The method syntax and property descriptors are just there to make the method definition as close as possible to existing methods, e.g. new Array.prototype.at(); shouldn’t work, so function shouldn’t be used, etc.)

@taralx
Copy link
Author

taralx commented Jun 9, 2021

Yup, all of these should be wrapped with correct existence checks. I'm not so much a purist on the meta-polyfilling like function-ness.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants