Utilizing proxies and leveraging the power of the Map collection in tandem

I have been exploring the Map collection and came across the [[MapData]] internal slot, which led me to utilize Reflect for trapping purposes.

After some trial and error, I came up with the following code snippet:

const map = new Map();

const proxiedMap = new Proxy(map, {
 get(target, property, receiver) {
  const currentValue = Reflect.get(target, property, receiver);
  return typeof currentValue === "function" ? currentValue.bind(target) : currentValue;
 }
});

Although this code successfully works with methods like set and get, it encounters an error when handling size.

proxiedMap.set("a", 1);
proxiedMap.get("a"); // 1
console.log(proxiedMap.size) // TypeError: Method get Map.prototype.size called on incompatible receiver #<Map>

To mitigate this issue, I removed the receiver argument from Reflect. Surprisingly, this resolved the problem without fully understanding why.

const proxiedMap = new Proxy(map, {
  get(target, property) {
    const currentValue = Reflect.get(target, property)
    return typeof currentValue === "function" ? currentValue.bind(target) : currentValue
  }
})

Why does this inconsistency only seem to affect the behavior of the size method?

Answer №1

The receiver parameter within Proxy#get is referring to the proxy itself

const proxiedMap = new Proxy(map, {
 get(target, property, receiver) {
  console.log(receiver === proxiedMap)
 }
}

When using Reflect.get, the receiver pertains to this and is used for getter functions

function Reflect_get(target, property, receiver = target) {
  let descriptor = Object.getPropertyDescriptor(target, property)
  if (descriptor.get) return descriptor.get.apply(receiver)
  else return receiver[property]
}

Therefore, an error occurs when attempting to call get Map#size on proxiedMap which is not actually a Map object


In your scenario, there is no need to explicitly use bind as this will be automatically inferred as the proxy

You may also prefer using class extends Map over utilizing Proxy<Map>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using TypeScript to define callback functions within the Cordova.exec method

I'm encountering an issue with the TypeScript definition for Cordova. The codrova.d.ts file doesn't allow for any function arguments in the success-callback and error-callback. To better illustrate my problem, here's a small example: Here ...

Can you provide guidance on how to showcase a list?

What is the correct way to display a list received through a URL in JSON format? Here is an example project. When using a local variable everything works fine, but when trying to fetch the list from a URL, an error is displayed. constructor(props) { ...

What is the method to insert a new <input> element after the last input field has been filled in

I recently started working on a form using StackBlitz, but I've hit a roadblock and need some guidance on how to proceed. My goal is to achieve a similar effect like the one shown in this gif: https://i.stack.imgur.com/76nsY.gif and I'd like to ...

The KeyboardAvoidingView disrupts the structure of the flexbox layout

Check out this code snippet: return ( <KeyboardAvoidingView style={{ flex: 1 }} behavior="padding" enabled> <View style={style.flex1}> <View style={style.imageContainer}> <Image style={style.image} ...

Navigating through cors in next.js

Currently, I have set up my front end using Netlify and my backend using Heroku with Next.js For the fetch request on the front end, here is an example: fetch(`https://backendname.herokuapp.com/data`, { method: 'POST', headers: { & ...

Guidelines for specifying alternate structures in JSON schema

I have two different JSON file structures, one like this: { "api": "http://my.api.host", "modules": [ "core", "module", "another" ] } and the other like this: { "api": "http://my.api.host", "modules": "*" } The modules attri ...

Transforming unprocessed string information with a set position-dependent format into a structured format such as JSON

Here is the scenario I am dealing with: The input format consists of a string with a fixed total length, where each set of fixed positions represents a different value. For example, if the input is "ABCDE12345", position 1 to 3 ("ABC" ...

Once appearing, the element quickly vanishes after the fadeIn() function is

In the source code, there is a section that looks like this: <div class="dash page" id="home"> <?php include ('pages/home.php'); ?> </div> <div class="dash page" id="screenshots"> <?php include ('pages/scr ...

Typing a general d3 selection to target various types of SVG elements

I am looking for a callback function that can be utilized with both rect and circle elements. Here is an example: function commonTasks(selection:d3.Selection<PLACEHOLDER_TYPE, MyDataType, SVGGElement, unknown>) { selection .classed('my-c ...

Step-by-step guide on deploying your Nestjs API on Google App Engine

Encountering a hurdle while trying to deploy my nestjs api on Google App Engine has left me puzzled. Despite initializing my google cloud project with the google sdk, an error thwarted my progress. To tackle this challenge, I made key adjustments in my cod ...

Error message "Script start is missing" found in install.json for socket.io-php package

I am looking to develop a .io game that integrates with some PHP APIs, and I have been attempting to run the following files: install.json: { "name" : "workerman/phpsocket.io", "type" : "library", "keywords": ["socket.io"], "homepage": ...

Issue encountered during production build in Angular 6 due to NGRX

Trying to create and test the production build, I used the following command: ng build --prod --configuration=production ng serve --prod --configuration=production The build process completed successfully, however, upon opening the site on browsers, an ...

Detect the "@" character through keyUp for the implementation of @mentions feature

I am currently working on implementing an @mention feature using Vue and Vanilla JS, but I am facing issues with targeting the "@" character specifically. Within my template: <trix-editor ref="trix" @keyup="listenForUser" ></trix-editor& ...

Retrieve an array of existing fields in MongoDB by comparing a collection with an array of objects

I'm a newbie when it comes to Mongo and I'm attempting to compare an array with a collection of documents, returning a list of matching records. Let me break it down:First Array I have a collection (user) with the following documents: > db. ...

Transforming the mui stepper connection into a progress bar is simple. Each step contains individualized content to guide you through the process

Is there a way to make the MUI stepper connector act as a progress indicator? I have step content and connectors as separate divs, but I'm having trouble styling them. Any assistance would be greatly appreciated! ...

Using Vue Axios to load a Laravel view can be a seamless process that

I'm attempting to create a hyperlink to a Laravel view named faq.blade.php from my Vue component. I've tried using axios, and even though it logs the response in the console, the view isn't loading. How can I resolve this issue? FaqControll ...

Guide to resolving domain names in express.js

I've been working on an expressJS script that includes a mongoDB fetch. My objective is to create an API that displays my JSON-based test list on the /api/testlist route. When I try to access the index page, everything seems to be working fine. Howev ...

What is causing the issue of URL parameters becoming undefined when performing service injection in the app component?

When working with a service that reads parameters from the URL, everything seems to be functioning properly until attempting to inject the service into the constructor of the app.component.ts file or trying to call a service method from the app.component.t ...

When accessing the innerHTML and outerHTML properties on an HTMLElement, they may return undefined without triggering

Task: My goal is to take an HTML string, make changes to certain attributes of image tags within it, and then return the modified HTML string. The function I have developed follows these steps: private resolveImagesInHTML (body: string): string { le ...

Using res.sendfile in a Node Express server and sending additional data along with the file

Can a Node.JS application redirect to an HTML file using the res.sendFile method from express and include JSON data in the process? ...