DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Bruce Axtens
Bruce Axtens

Posted on • Updated on

Extending the Array class to calculate the Fibonacci sequence

Today I learned how to do something wrong. Well, okay, that's not entirely true. I've been doing wrong things for a long long time.

Take extending native objects. The general opinion is that this is bad practise and should be avoided, for various good reasons. There are better ways of doing this apparently, even subclassing.

So, today I learned yet another way of doing Fibonacci sequences and, as you can see from that RosettaCode link, there are lots of interesting ways in lots of different languages. My way isn't in that collection (yet). Maybe someone'll beat me to it.

So I was extending the Array object with a method to generate an n-length array with an optional code-block to initialise each member. I came up with this:

Array.prototype.times = function (a, c) {
    if (a)
        for (var b = 0; b < a; b++)
            this[b] = "function" === typeof c ? c(b, this) : b;
    return this
};
Enter fullscreen mode Exit fullscreen mode

Then I started thinking of ways to test it and went through a few different things, finally quite accidentally stumbling over the Fibonacci sequence which can be generated like this:

var fibonacci = [].times(81, function (i, array) {
    return (i < 2)
     ? i
     : array[i - 2] + array[i - 1];
});
print(JSON.stringify(fibonacci));
Enter fullscreen mode Exit fullscreen mode

That generates Fibonacci-0 to Fibonacci-80. After that JavaScript loses precision and the series breaks down.

Somehow, I don't think that MDN is going to add .times to its list of Array object methods, but I really wish they had something like it. Meanwhile, here in my little internet backwater, I'll be using it.

Bottom line: Don't do this. It's bad practise. It might get you reprimanded by your team leader. It might even hasten the end of the world.

Top comments (2)

Collapse
curtisfenner profile image
Curtis Fenner

This can very nearly be accomplished using Array(n) and .forEach, though you need two statements since forEach returns nothing.

Collapse
bugmagnet profile image
Bruce Axtens Author

True and I have used that technique too.

🌚 Friends don't let friends browse without dark mode.

Sorry, it's true.