Kung Fu Kung Fu

Fujian White Crane Kung Fu

Zope Zope

What I have and am doing with Zope

Photos Photos

Photoalbum, both old and new.

Receptsamlingen Receptsamlingen

In Swedish only. About my "Collection of Recipes" website.

Contact me Contact me

My contact details and how to contact me.

  Mobile version of this page Mobile version of this page


 

isArithmeticExpression() in Javascript

19th of December 2007

Following from some work that I blogged about two days ago (Calculator in Python for dummies) I've now extended the functionality thinking into the AJAX scripts that sit on top of this Python server-side functionality. How this was implemented is boring but the following function helped me a lot. Here's the code with a very basic unit test after:

 function isArithmeticExpression(s) {
   return /[\d]\s*\+\s*[\d]|[\d]\s*\-\s*[\d]|[\d]\s*\/\s*[\d]|[\d]\s*\*\s*[\d]|[\d]\s*\^\s*[\d]/.test(s) &&
         s.split(/\)/).length == s.split(/\(/).length &&
         !/[A-Za-z_]/.test(s);
 }

 function assert(fact) {
   if (!fact) alert("Assert failure!");
 }
 assert(isArithmeticExpression('') == false);
 assert(isArithmeticExpression('++123') == false);
 assert(isArithmeticExpression('+123') == false);
 assert(isArithmeticExpression('2+123') == true);
 assert(isArithmeticExpression('2 + 123') == true);
 assert(isArithmeticExpression('2 + - 123') == false);
 assert(isArithmeticExpression('2 + 123') == true);
 assert(isArithmeticExpression('(2 + 123)') == true);
 assert(isArithmeticExpression('2^6') == true);
 assert(isArithmeticExpression('(2+1))^6') == false);
 assert(isArithmeticExpression('a+123') == false);
 assert(isArithmeticExpression('1a1+2x3') == false);

Basically, it returns true if the string appears to contain only numbers and one of the expected operators +, -, *, / or ^ in between two numbers.

It's far from perfect. I can think of cases where it will actually fail. But those cases are very rare and are too unlikely to happy and cause a major problem in this application and I'd rather get on with it than to spend any more time on this. After all, this is just a Javascript that tries to help if it can. The server-side code needs to "perfect" and if someone enters a weird expression, the server-side error handling will at least pick it up.


Comment

 
Name:
Email:
hide my email address.

Your email address will be encoded to prevent email-extraction spiders from reading it so you won't get spammed if you decide to show your email address.