Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
September 10, 2022 04:47 pm GMT

Real world use cases of object proxies

Standard definition

The Proxy object enables you to create a proxy for another object, which can intercept and redefine fundamental operations for that object.

Thinking

Let's simplify that a little.

"Customise the behaviour of an object, using handlers" -- in a broad sense.

Target and Handlers

Target is the object of concern on which Proxy is applied

Handlers or traps are functions passed as second parameter to Proxy which are responsible to handle actions (such as get, set etc) on the target

new Proxy(target, handler);

Let's look at some examples which will add weight around what the statement intends to convey.

Handle defaults

Consider a script which is to be used to match the winners with prizes they have won and everyone who participated gets a consolation prize.

A cleaner approach to coding it as opposed to a long list of if-else statements or switch is to use Proxy:

const prizeRegistry = {  karen: "First Prize - BMW X5",  mark: "Second Prize - Scooty",  athira: "Third Prize - Bicycle"};const prizeHandler = {  get(obj, prop) {    return prop in obj ?      obj[prop] :      "Consolation prize - Chocolate Bar";  }};const prizeList = new Proxy(prizeRegistry, prizeHandler);console.log(prizeList.karen);// expected output: "First Prize - BMW X5"console.log(prizeList.reena);// expected output: "Consolation prize - Chocolate Bar"

Input validations

With user inputs being a cog in the wheel to most of the applications today. Validations are to be placed to keep the data clean, ironically often as a result the code responsible gets messed up with time.

const validator = {  set(obj, prop, value) {    if (prop === 'weight') {      if (!Number.isInteger(value)) {        throw new TypeError('The weight is not an integer');      }      if (value > 200) {        throw new RangeError('The weight seems invalid');      }    }    // The default behavior to store the value    obj[prop] = value;    // Indicate success    return true;  }};const fish = new Proxy({}, validator);fish.weight = 100;console.log(fruit.weight); // expected output: 100fish.weight = 'small';    // Throws an exceptionfish.weight = 300;        // Throws an exception

Finding an array item object by its property

const products = new Proxy([  { name: 'Firefox', type: 'browser' },  { name: 'SeaMonkey', type: 'browser' },  { name: 'Thunderbird', type: 'mailer' }],{  get(obj, prop) {    // The default behavior to return the value; prop is usually an integer    if (prop in obj) {      return obj[prop];    }    // Get the number of products; an alias of products.length    if (prop === 'number') {      return obj.length;    }    let result;    const types = {};    for (const product of obj) {      if (product.name === prop) {        result = product;      }      if (types[product.type]) {        types[product.type].push(product);      } else {        types[product.type] = [product];      }    }    // Get a product by name    if (result) {      return result;    }    // Get products by type    if (prop in types) {      return types[prop];    }    // Get product types    if (prop === 'types') {      return Object.keys(types);    }    return undefined;  }});console.log(products[0]);          // { name: 'Firefox', type: 'browser' }console.log(products['Firefox']);  // { name: 'Firefox', type: 'browser' }console.log(products['Chrome']);   // undefinedconsole.log(products.browser);     // [{ name: 'Firefox', type: 'browser' }, { name: 'SeaMonkey', type: 'browser' }]console.log(products.types);       // ['browser', 'mailer']console.log(products.number);      // 3

The above snippet is mozilla documentation shows how an object in an array of objects can be optimally found using proxy

There are a number of other real-world usecase(s) that could leverage the awesomeness of Proxy to better maintain and help keep the code cleaner.

P.S These are the few i use day in and out, there are few more such as DOM manupulations, Property forwarding. You can check em out here.

Hope this helps. Cheers


Original Link: https://dev.to/jeevankishore/real-world-use-cases-of-object-proxies-3d87

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To