1.0.0 • Published 2 years ago

array-proxy v1.0.0

Weekly downloads
-
License
ISC
Repository
github
Last release
2 years ago

Array proxy

Description

JavaScript proxy objects don't work with arrays because they have native properties that are not proxied. This library make them work.

Usage

const { arrayHandler } = require('array-proxy')

const handler = {
  get: (target, prop, receiver) => {
    if (prop === 'foo') {
      return 'bar'
    }
    return Reflect.get(target, prop, receiver)
  }
}
const newHandler = arrayHandler(handler)

const nativeProxy = new Proxy([42], handler)
const arrayProxy = new Proxy([42], newHandler)

console.log(nativeProxy.foo)
// => bar
console.log(nativeProxy.forEach(e => console.log(e)))
// => throws
//    Uncaught TypeError: Method Array.prototype.forEach called on incompatible receiver #<Array>
//        at Proxy.forEach (<anonymous>)

console.log(arrayProxy.foo)
// => bar
arrayProxy.forEach(e => console.log(e))
// => 42

API

arrayHandler(handler)

The input is a proxy handler.

Returns a new proxy handler which wraps the input in a handler which make proxies work with arrays.