'Can I intercept/trap object behavior on comparison for equality
Playing around with Javascript objects is fun, and annoying:
const MyObject = function(value) {
let _myObject = {
[Symbol.valueOf]() {
return value
},
[Symbol.toPrimitive]() {
return value
},
}
return _myObject
}
let o = new MyObject("a")
let p = new MyObject("b")
o == "a"
# true
p == "a"
# false
o < p
# true
p < o
# false
p + "-foo"
# 'p-foo'
Having custom objects behave like primitive types looks potentially useful and intuitive! Until you try something like this:
let o = new MyObject("a")
let p = new MyObject("a")
o == "a"
# true
p == "a"
# true
o == p
# false
Javascript will (quite sensibly) return false when comparing two objects for equality.
Would there be any way to hack around the apparent “inconsistency” arising in a case like this? (Maybe some clever usage of proxies/Proxy handlers? )
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
