Search This Blog

Tuesday, March 9, 2010

Getting reference to the JavaScript Function object behind an operator

Programmer Question

Here is a lisp procedure that simply adds 'a' to the absolute value of 'b':



(define (a-plus-abs-b a b)
((if (> b 0) + -) a b))


I think this is beautiful, and I am trying to find the best way of writing this in JavaScript. But my JavaScript code is not beautiful:



var plus = function(a,b) {
return a + b;
};

var minus = function(a,b) {
return a - b;
};

var aPlusAbsB = function(a,b) {
return (b > 0 ? plus : minus)(a,b);
}


The main problem is that I cannot use the + and - symbols as references to the functions they really represent as I can with lisp. Can anyone come up with a more graceful way of doing something like this, or have I hit a language boundary?



Obviously, I can do this:



var aPlusAbsB = function(a,b) {
return a + Math.abs(b);
}


, but this is more of a thought experiment than a pragmatic question.



Is there any way I can get reference to the core functions in the JavaScript language just as if they were user-defined?



Find the answer here

No comments:

Post a Comment

Related Posts with Thumbnails