DEV Community

Adam Crockett πŸŒ€
Adam Crockett πŸŒ€

Posted on

Operator Overloading in JavaScript, more fun with a technical design.

More for fun than anything else, I am a little obsessed with strange syntax. If you want to know how this works check out the first post. This is a mock-up of some sort of node.js http server library that reads more in english, probably good for some code generation πŸ€·β€β™‚οΈ.

This is parsing just fine 🀣 stick it in your console I dare you.

// Skip to the end for shock and awe.
const get = () => ({
  valueOf(){
    return 0;
  }
});
const Ok = {
  valueOf(){
    return 1;
  },
  html(){
    return {
      valueOf(){
        return 2;
      }
    }
  }
}
const Err = {
  valueOf(){
    return "";
  },
  page() {}
}

// usage?
const homeRoute = get `/foo/bar` << Ok.html `
<div>
   somehow tis valid?
</div>
` | Err.page()
Enter fullscreen mode Exit fullscreen mode

I should note that valueOf is returning some random values, the fully computed value of homeRoute is 0, what you would want to do perhaps instead is build up some stringified JSON object which describes this chain of routing. Was a URL given? Was an error given? etc etc.

I kind of like this design because it's so decoupled it's beyond funny. It's also a very to the point design. URL OK HTML OR ERR. It's like a caveman, hmmm caveman.js 😳 nah

Top comments (2)

Collapse
 
diek profile image
diek

Wtf

Collapse
 
adam_cyclones profile image
Adam Crockett πŸŒ€

Everything you thought you knew is a lie!