Given an instance v
of a class Vector
, say v = new Vector(3, 5, 7)
, is it somehow possible to use the syntax v(k)
to call a specific method of the class Vector
on v
with argument(s) k
?
To provide some context, I'd like to be able to use v(k)
to call the method getElem(k)
on v
, which retrieves the k
-th vector element of v
. For example, v(2)
would return 7
. In other words, v(k)
would act as an alias or shorthand for v.getElem(k)
.
Of course it would be possible to write a (custom) pre-processor to achieve the above, I just wondered whether there is a built-in way to realise it.
This question was inspired by the syntax of the C++ library Eigen
, which allows one to get/set matrix elements in a similar way. It would be lovely to have something like this in JavaScript.
A bit of code to accompany the class mentioned above —
class Vector {
constructor(...vecElems) {
this.vecElems = vecElems;
}
getElem(k) {
return this.vecElems[k];
}
dot(v) {
return this.vecElems.reduce((aV, cV, cI) => aV + cV * v.vecElems[cI], 0);
}
}
const v = new Vector(3, 5, 7);
const w = new Vector(4, 6, 8);
console.log(v.getElem(2), v.dot(w));