0

I have two objects, as below:

var origin = {
    x: 10,
    y: 10
}

var coordinates = {
    x: 5,
    y: 5
}

I calculate the delta as follows:

var delta = {
    x : origin.x - coordinates.x,
    y : origin.y - coordinates.y
}

This works, BUT I am looking for a more elegant way, given all I really do is origin - coordinates. Unfortunately, origin - coordinates is not valid javascript

Any suggestions? Maybe using a ... spread operator?

  • Do you just have two objects or Array of objects ? – Dhaval Darji Nov 22 '21 at 10:00
  • 1
    Does this answer your question? [Is it possible to create custom operators in JavaScript?](https://stackoverflow.com/questions/20728460/is-it-possible-to-create-custom-operators-in-javascript) – Pronoy999 Nov 22 '21 at 10:01

2 Answers2

4

The basic answer is: No, there isn't a way to do that which is likely to pass your "elegance" test. :-) (I like Sairyu's approach of creating a reusable function [perhaps with a shorter name]. Or you might even make it a Point class with add, sub, etc.)

"Elegant" is a value judgement, but if these are the only properties in the objects and you want to avoid explicitly writing x and y, you can use a for..in loop, a for..of loop on Object.keys, or a combination of Object.entries, map, and Object.fromEntries though the overhead on that last one starts looking a bit overkill.

const delta = {};
for (const key in origin) {
    delta[key] = origin[key] - coordinates[key];
}

or

const delta = {};
for (const key of Object.keys(origin)) {
    delta[key] = origin[key] - coordinates[key];
}

or

const delta = Object.fromEntries(
    Object.entries(origin).map(
        ([key, value]) => [key, value - coordinates[key]]
    )
);

But again: None of these is likely to be "elegant" by most definitions I can imagine. :-)

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
3

Maybe the best way is by making a function, something like this :

function calculate_coordinates(point1, point2) {
    const x = point1.x - point2.x;
    const y = point1.y - point2.y;
    return {x, y};
}
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
Sairyu
  • 41
  • 5
  • 1
    This is probably the only thing that really qualifies as "elegant." :-) But note that your code is falling prey to what I call [*The Horror of Implicit Globals*](http://blog.niftysnippets.org/2008/03/horror-of-implicit-globals.html), you need to declare `x` and `y`. (Also, you can use shorthand property notation in the return: `return {x, y}`.) – T.J. Crowder Nov 22 '21 at 10:18
  • It could even be a class with `sub`, `add`, etc. – T.J. Crowder Nov 22 '21 at 10:20
  • I took the liberty of adding the declarations (and using shorthand notation). – T.J. Crowder Nov 22 '21 at 11:41
  • I'll put that in mind, thank you. – Sairyu Nov 22 '21 at 11:46