Ditto is real

Anyone who grew up watching the Pokémon anime in the 90s will think are we that old already and secondly about how Ditto plays a role in there. Ditto is a very cool Pokémon who could assume the form of any of the other Pokémon including moves.

Mocking

So I needed a Ditto to mock some object in a frontend application. The reason for this was I just wanted to mock the entire library and so whatever would be called in whatever order would also return a Ditto as to make it possible to chain ridiculous things like Ditto.a.b.c.d().f and it would work and return a Ditto.

The way you do this is to use a Proxy object in JavaScript. What it does is you provide a target and a handler which means you can intercept and augment some behaviour. For example a simple audit log as to who touched what objects, or maybe click behaviour or even as a form of Synthetic Monitoring. You could also make objects immutable with this behaviour as it would be when you freeze or seal objects.

Target

The target is whatever object you want to add the behaviour to. It can be a function or an object.

Handler

The handler holds the behaviour you want to want the target to obtain. So on an object you can specify a get key with a function that will be executed on getting an object. You can also set an apply key which will be executed on calling a function. There are several others you can call, even adding behaviour to when new gets used.

Ditto was born

The following piece of code creates a Ditto.

const Ditto = new Proxy(() => {}, {
    get: () => {return Ditto;},
    set: () => {},
    apply: () => {return Ditto;},
});

What it will do is on getting a property you will return the Ditto. On setting a property nothing will happen. So it will not be stored. Then when you execute the Ditto on any property it will return a Ditto.

#code #javascript