Blog

Code Optimization Posted on December 30, 2019

I had a tutorial video catch my eye about a somewhat newer javascript library for photo manipulation called CamanJS.

With so many buttons to have to listen for button clicks, the code gets quite repetitive with if/else if statements for each button. I managed to shorten it and optimize it into less repetition.

Here's what the web app looks like:

Here's the old code with all the if/else if statements:

With the new code, what I did was take the HTML element id of the buttons which were brightness-add, brightness-remove, contrast-add, contrast-remove, saturation-add, saturation-remove, etc., and I split the id into an array by the hyphen. This set the filter name (brightness, contrast, saturation, or vibrance) as the first index of the array (arr[0]) and add or remove as the 2nd index of the array (arr[1]).

I then checked if the arr[1] was equal to add or remove and set a variable equal to 5 or -5 depending on whether we were adding or removing. And then I made an array of the filters setting each one to a function that called the library methods. And then finally, we called the appropriate function based on which value was at arr[0]. Here's what that code looks like: