1

I have a task to implement expression 0..II to return [0, 1, 2] (same for all Roman numerals).

I have looked up Proxy object concept and this works fine.

var handler = {
	get: function(obj, prop) {
		console.log(prop);
		x = parseRomanNumeral(prop);
		if (x) {
			return Array.from(Array(x).keys());
		}

	},
	defineProperty: function(target, property, descriptor) {
		console.log('1');
	}
}

var target = {};
var proxy = new Proxy(target, handler);
console.log(proxy.II); //[0, 1]

But I don't understand how to do the same with the expression 0..I as 0. is the instance of Number. What should I pass to Proxy constructor?

1
  • are you looking for something like proxy['0']? Commented Mar 12, 2018 at 11:12

2 Answers 2

2

The expression 0..II actually means accessing II property on Number.prototype, since first dot is decimal while second is property accessor. For example:

console.log(0..toString()) // => '0'

So, I believe you're looking for combination of Object.setPrototypeOf and Proxy
Consider the following code

Object.setPrototypeOf(
  Number.prototype, 
  new Proxy(Number.prototype, {
    get(target, prop) {
      if(prop === 'II') {
        return [0, 1, 2]
      }
      else {
        return target[prop]
      }
    }
  }))
  
  console.log(0..II)  // [0, 1, 2]

While this can do the trick, I don't think extending primitives prototypes is a good idea, since it makes your code much less maintainable.

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

Comments

0

I believe you are looking for proxy['0..II']. The properties given to an object can be of three kinds: numbers, strings and symbols. Numeric values are also given as strings to the proxy handler, so proxy[1] gives "1" (and not 1) as the property.

Doing proxy.II is, indeed, the same as doing proxy['II'].

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.