Skip to content
This repository was archived by the owner on Mar 10, 2024. It is now read-only.
This repository was archived by the owner on Mar 10, 2024. It is now read-only.

Simplified polyfill #26

@dead-claudia

Description

@dead-claudia

Here's a simplified zero-dependency polyfill supporting all environments as far back as ES6, derived from the official polyfill at the time of writing.

const O = Object
const floor = Math.floor

function last(value, fallback) {
  if (value != null) {
    const l = +value.length
    if (l === l) {
      if (l > 9007199254740991) return 9007199254740990
      if (l >= 1) return floor(l) - 1
    }
  }
  return fallback
}

function install(name, desc) {
  if (Object.getOwnPropertyDescriptor(Array.prototype, name) == null) {
    Object.defineProperty(Array.prototype, name, desc)
  }
}

install("lastItem", {
  enumerable: false,
  configurable: false,
  get() {
    const l = last(this, -1)
    if (l >= 0) return this[l]
  },
  set(value) {
    // The coercion is so it doesn't throw in strict mode and has the
    // correct observable behavior WRT indexed property setters.
    O(this)[last(this, 0)] = value
  },
})

install("lastIndex", {
  enumerable: false,
  configurable: false,
  get() { return last(this, 0) },
})

This issue is purely informational, and no action here is needed. I just wanted to elaborate a bit upon the "There are polyfills which could use less code." part of this section of the README.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions