0

Is there anything that allows for overloading some of the more common operators in javascript? For example, taking an example from python to overload the >>:

d1 = {'a':{'b':{'c':42}}}
class Perhaps:
    def __init__(self, value):
        self.value = value
    def __repr__(self): return str(self.value) # for direct value shorthand
    def __rshift__(self, func):
        if self.value is not None:
            return Perhaps(func(self.value))
        else:
            return self
Perhaps(d1) >> (lambda d:d['a']) >> (lambda d:d['b']) >> (lambda d:d['c'])
# 42

Is the following the closest we can come in javascript?

let d1 = {'a':{'b':{'c':42}}};
class Perhaps {
    constructor(value) {
        this.value = value;
    }
    rshift(func) {
        if (this.value !== null) {
            return new Perhaps(func(this.value));
        } else {
            return this;
        }
    }
}
console.log((new Perhaps(d1)).rshift(d => d.a)
                             .rshift(d => d.b)
                             .rshift(d => d.c).value);
David542
  • 104,438
  • 178
  • 489
  • 842

0 Answers0