Hey! Did you know that in JS not only null and undefined but some ephemerical empty value is existing? :)
But let's first talk about not very common, but few times appieared in the real life during my programming career.
Let's take a look on a different implementations of a function when we need to do something N times in a row (i.e. generate random chars by executing provided algorithm).
I will introduce some score system to more easily describe pros and cons of the solutions such as readability and efficiency with score rate from 1 (no) to 5 (yeah!).
Using pad function and array spreading
const times = (n, fn) => [...''.padEnd(n)].map(fn);
readability: 2 - it's readable, but after some time :)
efficiency: 2 - everytime is a new array created, spreading functionality, padEnd function, map function
Array Array
const times = (n, fn) => Array.from(Array(n), fn);
readability: 3 - better then before, but still looks fancy. Let's do a short break of all that happend here:
-
Array(n)
gives us an empty array. Not null, not undefined, but empty. -
Array.from
an empty array will convert values fromempty
to undefined. - The second argument for
Array.from
is a funtion that will be executed against every value in the array.
efficiency: 3 - here we creating array of undefined from an empty array (what should be cheap at least memory wise).
for
const times = (n, fn) => {
for (let i = 0; i < n: i++) {
fn();
}
}
readability: 4 - for me it's not the best approach from the fancy code point of view, but it's really readable and similar to many other languages structures. Yeasy for beginners and new-comers
efficiency: 4 - everytime is a new array created, spreading functionality, padEnd function, map function
Python bonus
As I've started to learn Python - there is an additional example in this language. It's always interesting to compare syntaksis when learning a new language :)
def times(n, fn):
[fn() for _ in range(n)]
Not too much hacks, super concise, readable and much relays on the language core abilities itself. Love it!
readability: 5
efficiency: 5
Conclusion
As we can see - the function implementation can be short and easy to re-use, without any 3rd party libs needed.
Please, provide your solutions and scores in the comments!
Meanwhile you can take a look (on your own risk!) on how code can be bloated and shrink in the sope of one simple task/chank of functionality. From 180 to 6 lines ;)
Top comments (0)