isArithmeticExpression() in Javascript

19 December 2007   0 comments   Javascript

Powered by Fusion×

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 &&

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.


Thank you for posting a comment

Your email will never ever be published

Related posts

Calculator in Python for dummies 17 December 2007
String comparison function in Python (alpha) 22 December 2007
Related by keywords:
To readline() or readlines() 12 March 2004
bool is instance of int in Python 05 December 2008
Reciprocal lesson about gender perspectives 02 September 2011
Nginx vs. Squid 17 March 2009
How and why to use django-mongokit (aka. Django to MongoDB) 08 March 2010
Nasty surprise of Django cache 09 December 2008
IssueTrackerProduct now officially abandoned 30 March 2012
Google Calendar, iCalendar Validator but not bloody Apple iCal 09 April 2009
On the command line no one can hear you screen. Or can they? 03 May 2012
In Django, how much faster is it to aggregate? 27 October 2010
tempfile in Python standard library 07 February 2006
Random ID generator for Zope 02 September 2005