Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to multiply objects by specified rules? [duplicate]

Let's say i want an object that when multiplied with, it multiplies by two and subtracts 1. The syntax would look like this:

var a = {
    on_multiply: function(context){
        return context*2-1
    }
};
alert(2*a);

This would output 3. I don't want to write "a.on_multiply(2)" Is there a way to do this? If yes, is it possible to do this with arrays or matrixes also?

like image 430
Samuel Garbergs 6 Avatar asked Jul 09 '26 11:07

Samuel Garbergs 6


1 Answers

The simplest way I can think of to make the above example work is to assign a function named a, and have the context as a parameter of that function:

function a(context) {
    return (context * 2) - 1;
}

And if you really wanted a to be a function assigned to a name:

const a = context => 2 * context - 1;

And the above in ES5 syntax:

const a = functipn(context) {
    return (context * 2) - 1;
}

Hopefully this helps!

like image 188
Jack Bashford Avatar answered Jul 12 '26 02:07

Jack Bashford



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!