473,320 Members | 1,952 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

custom Number operator

Hi folks, i've searched and searched and can't find any example of
what i'm trying to do. Essentially (i think) i need to add a new
operator to Number.

I'm using eval to evaluate expressions that can be entered by users,
these expressions are defined by another app so i can't change the
format of the expressions. I've managed to support the majority of
operators by supplying my own functions that wrap the equivalent Math
functions but i'm struggling with a few.

I need to support mod, div, shl and shr which will be in the format:

x div y, x mod y, x shl y, x shr y
How can i add an operator to Number to handle these? Is it even
possible?
Or is there some another way i can support them?

I considered using regexp to replace the relevent bits but that got
pretty ugly when i started to look at the possibility of nesting.
Any help greatly appreciated.
Cheers!
Jul 20 '05 #1
7 5780
ne********@hotmail.com writes:
Hi folks, i've searched and searched and can't find any example of
what i'm trying to do. Essentially (i think) i need to add a new
operator to Number.
Number is a function (although it can be used to represent the class
of objects it creates too). You can add *methods* to the number objects,
but not operators.
I'm using eval to evaluate expressions that can be entered by users,
these expressions are defined by another app so i can't change the
format of the expressions. I've managed to support the majority of
operators by supplying my own functions that wrap the equivalent Math
functions but i'm struggling with a few.

I need to support mod, div, shl and shr which will be in the format:

x div y, x mod y, x shl y, x shr y How can i add an operator to Number to handle these? Is it even
possible?
You can't create new operators in Javascript (that would be changing the
syntax of the language), so you can't just evaluate the string above.
Or is there some another way i can support them?
What you can do, is to use a string replace to change the operators
to the corresponding Javascript operator. They are:

div -> / (not precisly, though. Javascript doesn't have integer division)
mod -> %
shl -> >> (or >>> depending on how the most siginificant bit is set)
shr -> <<

input = input.replace(/\bdiv\b/g,"/").
replace(/\bmod\b/g,"%").
replace(/\bshl\b/g,">>").
replace(/\bshr\b/g,"<<");
I considered using regexp to replace the relevent bits but that got
pretty ugly when i started to look at the possibility of nesting.


If you replace infix operators with other infix operators, there shouldn't
be any problems (knock wood).

Your problem is that there is no integer division in Javascript. To replace
expr1 div expr2
with the corresponding
Math.floor(expr1 / expr2)
would require parsing the string. Possible, but hard(er) work. Same
for:
expr1 .myDiv(expr2)

/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'
Jul 20 '05 #2
wrote on 27 Nov 2003:
Hi folks, i've searched and searched and can't find any example
of what i'm trying to do. Essentially (i think) i need to add a
new operator to Number.

I'm using eval to evaluate expressions that can be entered by
users, these expressions are defined by another app so i can't
change the format of the expressions. I've managed to support
the majority of operators by supplying my own functions that
wrap the equivalent Math functions but i'm struggling with a
few.

I need to support mod, div, shl and shr which will be in the
format:

x div y, x mod y, x shl y, x shr y
How can i add an operator to Number to handle these? Is it even
possible?
Or is there some another way i can support them?

I considered using regexp to replace the relevent bits but that
got pretty ugly when i started to look at the possibility of
nesting.


JavaScript does not support operator overloading. However, you could
add named methods, using the prototype property, to the Math, Number,
or your own objects. An alternative would be to write a generic
parsing method that takes a string and evaluates it using your own
operator set, but I think that's more work than you'd be willing to
do.

Mike

--
Michael Winter
M.******@blueyonder.co.uk.invalid (remove ".invalid" to reply)
Jul 20 '05 #3
>
What you can do, is to use a string replace to change the operators
to the corresponding Javascript operator. They are:

div -> / (not precisly, though. Javascript doesn't have integer division)
mod -> %
shl -> >> (or >>> depending on how the most siginificant bit is set)
shr -> <<

input = input.replace(/\bdiv\b/g,"/").
replace(/\bmod\b/g,"%").
replace(/\bshl\b/g,">>").
replace(/\bshr\b/g,"<<");
--
If you replace infix operators with other infix operators, there shouldn't
be any problems (knock wood).
cheers, i realise now i was trying to make my regexp to complicated
for these.

Your problem is that there is no integer division in Javascript. To replace expr1 div expr2
with the corresponding
Math.floor(expr1 / expr2)
would require parsing the string. Possible, but hard(er) work. Same
for:
expr1 .myDiv(expr2)

/L

yeah, i came up with this initially but it's far from ideal:

expr = expr.replace(/([-+]?\d+(\.\d+)?)\W?div\W?([-+]?\d+(\.\d+)?)/gi,
'Math.floor($1/$3)');

I also have the same problem with suppproting ^ as a power operator,
e.g. x ^ y = Math.pow(x,y)
I was trying to avoid parsing the expression if i possibly could but
it's looking likley that i might have to do just that.
Jul 20 '05 #4
>
you could add named methods, using the prototype property, to the Math, Number,
or your own objects.

yeah, i looked at that but i couldn't see a way of supporting 'infix
operators' like mod, div, etc. can this be done?
Jul 20 '05 #5
ne********@hotmail.com writes:
yeah, i came up with this initially but it's far from ideal:

expr = expr.replace(/([-+]?\d+(\.\d+)?)\W?div\W?([-+]?\d+(\.\d+)?)/gi,
'Math.floor($1/$3)');
It might suffice for the expressions you have. It doesn't work for
general expressions (no single regular expression can do that).
Example:
(8 div 4) div 2
becomes:
(Math.floor(8/4)) div 2
and
(8 mod 2) div 2
isn't matched at all.

The \W looks curious. Is it supposed to match whitespace? In that case,
\s is better. \W matches any non-word character, which is quite a lot.
I was trying to avoid parsing the expression if i possibly could but
it's looking likley that i might have to do just that.


Most likely. You are changing infix to prefix. That requires parsing
if you have arbitrarily nested expressions.

/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'
Jul 20 '05 #6
JRS: In article <5b**************************@posting.google.com >, seen
in news:comp.lang.javascript, ne********@hotmail.com posted at Thu, 27
Nov 2003 03:49:50 :-

I need to support mod, div, shl and shr which will be in the format:

x div y, x mod y, x shl y, x shr y


In addition to what others have said, check that the behaviour of your
code agrees with expectation for all nine combinations of x<=>0, y<=>0.

--
© John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 IE 4 ©
<URL:http://jibbering.com/faq/> Jim Ley's FAQ for news:comp.lang.javascript
<URL:http://www.merlyn.demon.co.uk/js-index.htm> JS maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/JS/&c., FAQ topics, links.
Jul 20 '05 #7
Fox


ne********@hotmail.com wrote:

Hi folks, i've searched and searched and can't find any example of
what i'm trying to do. Essentially (i think) i need to add a new
operator to Number.

I'm using eval to evaluate expressions that can be entered by users,
these expressions are defined by another app so i can't change the
format of the expressions. I've managed to support the majority of
operators by supplying my own functions that wrap the equivalent Math
functions but i'm struggling with a few.

I need to support mod, div, shl and shr which will be in the format:

x div y, x mod y, x shl y, x shr y

How can i add an operator to Number to handle these? Is it even
possible?
Or is there some another way i can support them?

I considered using regexp to replace the relevent bits but that got
pretty ugly when i started to look at the possibility of nesting.

Any help greatly appreciated.
Cheers!

For what it's worth:

The following hasn't been extensively tested by any stretch, but
probably can give you ideas on how to proceed.

Example expressions (that can be evaluated):

x div y

12 mod 5

1020 div 33 mod 7 [resolves to 2 :: expression evaluated left to right]

5 * (((x div y) mod testz) shl 2) ^ 4

// this last one will resolve as 5 * Math.pow(subexpression, 4)
// all BASIC operators are resolved before the final string is eval'd
// so pay attention to parenthetic groupings!
Limitations:

1: variables to be resolved should be globally declared/defined.
otherwise, you need to find another way to make the translations
[i.e., variables are resolved before operations begin in function process]

2: complex expressions require an extra level of parsing:
e.g.:
// the formula for finding the day number in the year of a date
((275 * M) div 9) - K * ((M + 9) div 12) + D - 30

this will have to be "pre-processed" -- see details at end

3: as written, it will not handle extra spacing between parens
and variables/numbers
like: ( x div y ) -- the regex doesn't account for this condition
I tried to keep the regex's as simple as possible...

Notes:

you can skip the process function if numeric-only expressions are used
and use the evaluate function... just remember the "value"
returned will be a string and will need to be converted
e.g.: evaluate("122 div -7"); => returns "-18"
var res = +evaluate("122 div -7") results in type "number"

these routines have only been tested for very basic (no pun intended)
statements. Somebody better at regex could probably do a better job...

the "variable" extractor at the beginning of function process() should be
able to handle variable names with underscores and numerics as long
as
they begin with an alphabetic character (usual rules).

// main function to process expressions using
// div, mod, shl, shr, and ^
// add others to the regex and switch statements

function
process(p)
{

// used to extract var names
// won't allow a variable starting with a number
var re = /\b([A-Za-z]+[\w]*)\b/g;

var vars = p.match(re);
// "BASIC" operators will look like vars to JS -- so remove them

vars = vars.join(" ");

vars = vars.replace(/div|mod|shl|shr/g, "");
vars = vars.split(" ");

// grab and replace variable values from window object
// (hence the need for globals)

for(var i = 0; i< vars.length; i++)
{
if(vars[i]) // there will be blanks in the array - so test
p = p.replace(vars[i], window[vars[i]]);
// grabs the "current" variable value
// probably should have error checking here

}
// this section evals and removes parenthetical expressions
// only the most embedded will match (per pass)
// i.e.: (n op i) will match but (n op i) op i2 will not
// the routine replaces the parenthetical with a numeric value
// the the process is looped until all parentheticals are evaluated
var arr;

while(

arr = p.match(/([\d\w]+)\s+(div|mod|shl|shr|^)\s+([\d\w]+)/g)
)
{

var t = evaluate(arr[0]);
p = p.replace(arr[0], t);

var removeparen = /(\()(\d+)(\))/;

var newtest = p.match(removeparen);

if(newtest)
p = p.replace(new String(newtest[0]), newtest[2]);
else break; // this will stop infinite loops

// debugging statement -- in case of an infinite loop
// this process is interesting to watch...
// if(!confirm("current state = " + p)) break;
}

// after the parentheticals -- this section will resolve
// what's left -- from left to right...

while(
arr = p.match(/(-?\d+)\s+(div|mod|shl|shr|\^)\s+(-?\d+)/)
)
{
if(arr){

t = evaluate(arr[0]);
p = p.replace(new String(arr[0]), t);
}
}

// just a debugging statement
//alert("final state b4 return = " + p);

// should be nothing left but a JS expression to be evaluated

return eval(p);
}

// generic subroutine...takes exactly 1 operation: a op b
// evaluate expects a string value containing a "simple expression"
// e.g.: 12 mod 5 --
// NO variables!

function
evaluate(exp)
{
var re = /(-?\d+)\s+(div|mod|shl|shr|\^)\s+(-?\d+)/;
var t;
var tarr = exp.match(re);

switch(tarr[2])
{
case "div":
t = Math.floor(+tarr[1]/+tarr[3]);
break;

case "mod":
t = +tarr[1] % +tarr[3];
break;

case "shl":
t = +tarr[1] << +tarr[3];
break;

case "shr":
t = +tarr[1] >> +tarr[3];
break;
case "^":
t = Math.pow(+tarr[1] , +tarr[3]);
break;
break;

default:
// kick error if detected -- if required
break;

}

return t;
}
//////////////////////// Examples \\\\\\\\\\\\\\\\\\\\\\\\\\
// sample global var declarations used in expressions to be evaluated

var x = 30;
var y = 5;
var testz = 4;

var pat = "5 * (((x div y) mod testz) shl 2) ^ 4";

alert("process = " + process(pat)); // result = 20480

pat = "x div y";

alert( "process2 = " + process(pat));// result = 6

pat = "12 mod 5"; // result = 2

alert("process3 = " + process(pat));

alert("evaluate1 = " + evaluate("122 div -7");
//********************************************

more complex example:

var M = 11; // november month number (not JS oriented)
var D = 28; // today's date
var K = 2; // used for non-leapyear -- otherwise 1

var pat = "((275 * M) div 9) - K * ((M + 9) div 12) + D - 30";

var re = /(\([^)]+\))/g;

// this regex is a little unusual...
// it finds ((275 * M) and ((M + 9) only
// after evaluating, it replaces 1 left paren + eval'd value

var myarray = pat.match(re);

for(var i = 0; i < myarray.length; i++)
{
var t = eval(myarray[i].replace(/[\(]/, ""));

//inner parens removed, so replace open paren

pat = pat.replace(myarray[i], "(" + t);

}

// after this, pat becomes:
// (3025 div 9) - K * (20 div 12) + D - 30 [simplified enough for process()]

then

alert("pat string = " + pat + "\n" +
"day of year = " + process(pat)); // =>result 332

good luck...
Personally, I prefer something like:

Number.prototype.div = function(denom) { return Math.floor(this/denom); }
// e.g.: (122).div(7) or someVar.div(divisor); etc...

of course, there's no way to implement ^ as a method.
process() could be extended to handle logical operators as well, like
AND, OR, NOT, etc...
While I was putting this together, I made quite a number of
modifications to the original source. I've tried to make sure that all
the mods were properly updated in this post... if something doesn't work
as I've written it would, let me know -- I'll email you the working demo.

As written, the regex's only allow integer values -- if you need to
accept decimal values, change the lines:

arr = p.match(/(-?\d+)\s+(div|mod|shl|shr|\^)\s+(-?\d+)/) in process to
arr = p.match(/(-?[\d\.]+)\s+(div|mod|shl|shr|\^)\s+(-?[\d\.]+)/)

and

var re = /(-?\d+)\s+(div|mod|shl|shr|\^)\s+(-?\d+)/; in evaluate to
var re = /(-?[\d\.]+)\s+(div|mod|shl|shr|\^)\s+(-?[\d\.]+)/;

this will allow the use of decimals - however, strings like: 23.45.455
will break (but that's not something a careful programmer need worry
about -- right?).

I'm sure there are numerous other problems with this script -- off the
top of my head: 1) object properties will fail (e.g.: myObj.myVar mod
whatever) as will array notation (myArray[index])... and such... This is
just an algorithm -- not a complete solution. It should suit for simple
BASIC syntax statements.
Jul 20 '05 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

9
by: mathias | last post by:
I would like to define a custom operator in Python. (It is not about overloading an existing operator but about defining special new operators) Is this possible without deeply manipulating the...
12
by: Brian Genisio | last post by:
Hi all, I am developing some software, that creates a tree of information. For each node, currently I am overriding the new operator, because it is a requirement that after initialization, no...
16
by: Jason | last post by:
Hi, I need a way to use random numbers in c++. In my c++ project, when using the mingw compiler I used a mersenne twister that is publicly available and this did its job well. Now I have...
0
by: nick | last post by:
Hi, I need to manage a "layered" collection of objects, where each layer grows independently, e.g, o--+--+--+--+--+ 1st layer | o 2nd layer (empty) | o--+--+--+ 3rd...
13
by: Grahamo | last post by:
Hi, I'm implementing a custom iterator (random access type ) so I can use stl algorithms such as sort on my legacy containers. I'm having problems compiling however. when implementing my...
4
by: Robert Frunzke | last post by:
Hello, I need to implement a custom allocator to speed up the allocation of a specific class in my project and instead of hardwiring it, I would "templatize"(?) it. The allocator should have...
2
hyperpau
by: hyperpau | last post by:
Before anything else, I am not a very technical expert when it comes to VBA coding. I learned most of what I know by the excellent Access/VBA forum from bytes.com (formerly thescripts.com). Ergo, I...
0
by: archwn | last post by:
Dear all, I would like to create a custom logger which allows logging commands in stream-style, but at the same time the output goes to some file or to the screen (cout) or to both. The code below...
0
hyperpau
by: hyperpau | last post by:
Before anything else, I am not a very technical expert when it comes to VBA coding. I learned most of what I know by the excellent Access/VBA forum from bytes.com (formerly thescripts.com). Ergo, I...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.