1

Putting aside concerns about modifying JavaScript's Array.prototype for now, how would I go about writing a custom method on the Array prototype that returns an iterator in reverse? Specifically, I'd like to provide an entriesReverse() method that does exactly what Array.prototype.entries() does except in reverse order. I've got as far as a bespoke function:

const entriesReverse = (array) => ({
    [Symbol.iterator]() {
        let index = array.length;
        return {
            next: () => ({
                value: [--index, array[index]],
                done: index < 0
            })
        }
    }
})

but I'll be darned if I can figure out how to implement this as a method on the existing Array prototype. The problem seems to be trying to refer to 'this' inside the Symbol.iterator block - it doesn't refer to the array itself but to the iterator. Any thoughts?

1
  • Don't use an arrow function if you want to refer to the dynamic this argument. Commented Nov 19, 2021 at 0:16

1 Answer 1

0

It'll be easier to use a generator function. Call the original .entries() and turn it into an array of the entries, then iterate backwards over that array and yield each item.

Array.prototype.entriesReverse = function*() {
  const entries = [...this.entries()];
  for (let i = entries.length - 1; i >= 0; i--) {
    yield entries[i];
  }
};

for (const entry of ['a', 'b', 'c'].entriesReverse()) {
  console.log(entry);
}

Another option:

Array.prototype.entriesReverse = function*() {
  yield* [...this.entries()].reverse();
};

for (const entry of ['a', 'b', 'c'].entriesReverse()) {
  console.log(entry);
}

Sign up to request clarification or add additional context in comments.

1 Comment

Huh. That works. Inspired by your use of a generator, I came up with something even more concise: Array.prototype.entriesReverse = function*() { for(let index = this.length - 1; index >= 0; index--) { yield [index, this[index]]; } } Which appears to work just fine. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.