Help

Eliminating Switch() Statements - A Dynamic [Elegant] Approach

619 0
cancel
Showing results for 
Search instead for 
Did you mean: 

Script developers are quick to reach for the Switch() directive in javascript. This is considered better than IF() statements for many reasons, but this is not specific to Airtable scripting; Switch() is used in all flavours of javascript and it’s a bit faster than evaluating IF() statements.

But just as Switch() is a better alternative to IF(), JSON may be a better alternative to Switch().

Consider the requirements of my Benford’s example.

  • Traverse every record to capture the first digit in the values of a target numeric field.
  • Count the instances where the first digit is 1 through 9.

This is a simple aggregation and one might perform the classification of the counts using a Switch() statement - one case for each count. This requires - among other things, ten variables to accumulate the counts and a Switch() statement to perform the counts. No engineer could be blamed for concluding this approach.

Alternative…

The alternative is just one variable; a JSON object that will ultimately contain the 10 classes of counts defined like this:

let benfordCounts = {};

Iterating across 30,000 records and aggregating while classifying the counts requires just one line of code.

benfordCounts[thisDigit] = (benfordCounts[thisDigit] === undefined) ? {"count" : 1} : {"count" : benfordCounts[thisDigit].count + 1};

When the dust settles (in about 1200 milliseconds) it leaves us with this object which looks a lot like a Switch() statement, right? But, unlike a Switch() statement, it is portable, searchable, can be evaluated, and even embellished with new data.

image
We tend to assume JSON objects are simply for data payloads, but they can be employed in a variety of ways to enhance code and in many cases eliminate lots of code while creating simple approaches that perform very fast.

0 Replies 0