1

I am looking for a way to give an arithmetic operator sign as a function name and then call it. I want to do something like this :

+(4,5) // Answer : 9
/(9,3) //Answer : 3

I've already seen a code sample like this but I can't remember how it assigned a name like "+" to a function in JavaScript and then called it.

Can anyone show me some tricky ways to do this in JavaScript?

Amir Jalilifard
  • 2,027
  • 5
  • 26
  • 38
  • 2
    I really doubt you can do that. – jkd May 13 '15 at 02:01
  • 4
    I'm 99% certain you can't do this, and 100% certain you *shouldn't* do this. – Chris Hayes May 13 '15 at 02:01
  • 1
    doesnt it make more sense to just go a + b or 9/3.. Seems much easier to read then trying to dig through what you are trying to achieve. but then also no you cant assign to those operators. The closes you can go is with simple add(), sub(), mul(), div()... – Nico May 13 '15 at 02:01
  • I already see a tricky way and a code sample but I can't remember it. I am sure it is possible. It was something like ("+", function(){}) – Amir Jalilifard May 13 '15 at 02:02
  • There is a Tricky way. I am sure. I already see a code sample. – Amir Jalilifard May 13 '15 at 02:03
  • I don't think you did, at least not in JavaScript. – Dave Newton May 13 '15 at 02:03
  • 2
    You'd better go find that code sample, then, because the standard is quite clear you can't do this. You could create an object where one of the keys is `"+"`, and its value is a function, but that's not at all what your question asked. And again, why in the world do you even want this? – Chris Hayes May 13 '15 at 02:04
  • 1
    @AmirJalilifard you probably seen this: http://stackoverflow.com/questions/5834318/are-variable-operators-possible – Roko C. Buljan May 13 '15 at 02:05
  • Do you come from a Swift background? This seems like something Swift-ian. – Sumner Evans May 13 '15 at 03:10

4 Answers4

2

That's not possible

Function names can contain letters, digits, underscores, and dollar signs (same rules as variables).

Anik Islam Abhi
  • 25,137
  • 8
  • 58
  • 80
  • 3
    The _letters_ bit does contain **a lot** though, e.g. `function π() {return Math.PI;}`, `function ß() {return 'ss';}`, `function 漢字() {return 'Kanji';}` etc are all valid – Paul S. May 13 '15 at 02:03
  • I know after 10 years of coding with JS. But there is a tricky way! As I can remember in a code sample I saw it was written something like ("+", function(){}) . I just remember this part of code! – Amir Jalilifard May 13 '15 at 02:06
  • 3
    @PaulS.: `function 十(a, b) { return a + b; }` :) – Amadan May 13 '15 at 02:06
  • 1
    @AmirJalilifard that looks like it is an invocation of another function which takes the string `"+"` and decides which operation to perform – Paul S. May 13 '15 at 02:07
  • @Paul. Yes. But how? I can't remember this part! – Amir Jalilifard May 13 '15 at 02:08
  • @AmirJalilifard Considering you haven't given us an accurate description of what you want, you aren't going to get an answer here unless you update your question. – Chris Hayes May 13 '15 at 02:09
  • I exactly want this and I am sure it is possible because I have seen a code sample. +(4,5) // Answer : 9 I think I've seen that in JavaScript Ninja book – Amir Jalilifard May 13 '15 at 02:11
  • 2
    @AmirJalilifard **That is not possible.** I don't know how to make it any more clear. You either are misremembering what you read, or you read some bad information. – Chris Hayes May 13 '15 at 02:11
  • @AmirJalilifard you can try amadan way like this function 十(a, b) { return a + b; } and calling will be 十(4, 5). – Anik Islam Abhi May 13 '15 at 02:14
  • @AnikIslamAbhi: That was a joke though. (It works, to be sure, but... don't do that.) – Amadan May 13 '15 at 02:26
2

You can't

Variable / Function names can only have Letters, Underscores, $, Numbers (if they're not the first character) along with a few other ACII, and unicode characters

Check here or here for more information


Workaroundish

If you are determined on having a + as your function name, you could use:

window['+'] = function (a,b) {
    return a+b;
};

That is bad practice and still only creates a variable "theoretically" named + and can only be invoked using:

window['+'](9, 10);

Which returns 19


What you are thinking of

The syntax you are suggesting seems like Object.defineProperty syntax:

Object.defineProperty(this, '+', {value:function () {
    alert('foo');
}});

Try

You could create something like:

window.special = function(a, args) {
    var o = {
        '+': function (b,c) {
            return b+c;
        }
    };
    return o[a].apply(this, args);
};

Then:

special('+', [1, 2]);
Community
  • 1
  • 1
Downgoat
  • 13,771
  • 5
  • 46
  • 69
  • You still can't invoke that as `+(4, 5)` (or even as `window.+(4, 5)`). – Amadan May 13 '15 at 02:08
  • @Amadan I realize but it creates a function names `+` – Downgoat May 13 '15 at 02:08
  • No, it creates an anonymous function assigned to `window['+']`. See this: `a = function() {}; function b() {}; console.log(a, b)` - the first one is anonymous (despite being assigned to `a`), the second one is actually *named* `b`. – Amadan May 13 '15 at 02:10
2

I know after 10 years of coding with JS. But there is a tricky way! As I can remember in a code sample I saw it was written something like ("+", function(){}). I just remember this part of code!

@Paul. Yes. But how? I can't remember this part!

Define another function that takes a parameter which tells it which method to apply, for example

var op = (function () {
    var fns = Object.create(null),
        slice = Array.prototype.slice;
    fns['+'] = function () { // example adder
        var i, j = 0;
        for (i = 0; i < arguments.length; ++i)
            j += arguments[i];
        return j;
    };
    // add other methods here
    return function op(operator) {
        if (operator in fns)
            return fns[operator].apply(this, slice.call(arguments, 1));
        throw new SyntaxError('Not a valid operator: ' + operator);
    };
}());

op('+', 1, 2, 3, 4); // 10
Community
  • 1
  • 1
Paul S.
  • 64,864
  • 9
  • 122
  • 138
0

Just to add it is possible if you really want to override the function of '+' you could essentially write

window['+'] = function(a, b) { return a + b; };

But what does that do... This will add a function to the window namespace. However you still cant call it with +(a,b) you have to use the window namespace. Such as.

window['+'](4,5);

result: 9

which really is a pain to call the window space. You are not limited to the window space you could use any object.

Nico
  • 12,493
  • 5
  • 42
  • 62