Home > Web Front-end > JS Tutorial > Proxy - JavaScript Challenges

Proxy - JavaScript Challenges

Susan Sarandon
Release: 2024-11-04 09:12:30
Original
702 people have browsed it

Proxy - JavaScript Challenges

You can find all the code in this post at the repo Github.


Proxy related challenges


Access negative index

/**
 * @param {Array} arr 
 */

function withNegativeIndex(arr) {
  return new Proxy(arr, {
    get(target, property, receiver) {
      const index = Number(property);

      if (index < 0) {
        property = target.length + index;
      }

      return Reflect.get(target, property, receiver);
    }
  });
}

// Usage example
const fruits = ["apple", "banana", "orange"];
const proxiedFruits = withNegativeIndex(fruits);

console.log(proxiedFruits[-1]); // => 'orange'
console.log(proxiedFruits[-2]); // => 'banana'
console.log(proxiedFruits[-3]); // => 'apple'
console.log(proxiedFruits[0]);  // => 'apple'
console.log(proxiedFruits[1]);  // => 'banana'
console.log(proxiedFruits[2]);  // => 'orange'
Copy after login

Reference

  • Proxy - MDN

The above is the detailed content of Proxy - JavaScript Challenges. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template