Sometimes when I am used to a particular convenience or tool when working with one technology, I tend to want to default to using the same feature with another. However, core developers across technologies do not always agree on what are the most fundamental functions that should be built-in.
For example, if we tried to sum the array defined below — an error essentially saying “I don’t know what you are talking about” would appear. But this problem could be fixed in an idiomatic way by “reducing” the array by summing element by element, starting with the value 0 as defined in the second positional argument (which is optional in this instance as this is the default setting).
What if we wanted to call sum repeatedly and wanted to avoid rewriting similar lines as per above? We could refactor by making our own little sum function.
If we return to the console, we can let the browser know how it should handle the array passed into sum.
Another nifty function that has been in my core Python toolbox is the range function. When three arguments are passed into range, Python would create a generator — which I treat it as a self-destructing list — that allows iteration beginning from the first argument (the “minimum”), up to but not including the second argument (the “maximum” that is excluded), in increments as per the third argument (the “step”). We let mn, mx, and s represent minimum, maximum and step respectively.
JS does not have a native range function, but we can approximate one with the one-liner below. First, we initialise an array with maximum less minimum empty elements, fill them with some placeholder value (0 in this case), and map to each element their index plus minimum value (index starts with 0 in JS). Once that is done, we drop elements that do not fall in step with the filter method — any element less the minimum that is not fully divisible by the defined step would be discarded.
We try it out in our browser. We want the console to log values starting from 1, up to but not including 10, in steps or increments of 2.
And it works!
The point is that when we are faced with a situation when our initial hand of cards is not favourable for the task at hand, let us push ourselves to find ways to forge our own set of tools that would level the playing field. The problem could be technical, social, or even philosophical, but if we allow ourselves to focus on how to overcome the difficulties to solve the problem instead of on our initial position — we would emerge successively stronger with each new challenge.