Categories
Java Script Tutorials

Shuffle an Array by extending built-in objects

Imagine if you transform your data like array for most of the time. Often times for loop with other variables are used to do the job. If it’s repeated than that code is extracted to its own function. Why not we extend the built in Array method and make it simple to use.

Shuffle an Array

The objective is to write a method that’s extend the built in Arrays with shuffle functionality. We need to have a little bit background about the prototype property that all built-in constructor function has. Be it String, Object, Function or Array. So if we extend the built in objects using the prototype object; all the object created afterwards will have this new function (shuffle in our case)

This will make much more sense with an example.

Array.prototype.shuffle = function() {
  console.log(this.length);
}
[1,2,3,4].shuffle(); // 4

So we have added new property to Arrays and later invoking it indicates that this refers to the array it is called upon. Now we have successfully extended the built-in Array Object.

Now let’s complete our example

Array.prototype.shuffle = function(){
    const elements = [].slice.call(this);
    let result = []
    for(let i=0, total = elements.length; i< total; i++ ){
        const random = Math.floor(Math.random() * (elements.length - 0)) + 0
        result.push(elements.splice(random, 1)[0])
    }
    return result
}

[1,2,3,4].shuffle(); // [2,4,3,1]
[2,3,5,7,8,9].shuffle(); // [8, 2, 3, 9, 5, 7]

The line 2 converts array like object to array. Line 5 can be generalized as follows and explained well by mdn.

Math.floor(Math.random() * (max - min)) + min

Beyond that, for each iteration I am plucking random item from the elements and pushing it into results array. The resultant array is now shuffled. Every time we call shuffle method, we get a new array with desired results.

Some Caveats

The extended method shuffle may be added by ECMAScript newer versions. It might be well battle tested and perform well than our solution. In order to deal with conflict we can apply certain kind of safety as

if (typeof Array.prototype.shuffle !== 'function'){
  Array.prototype.shuffle = function() {
  // …..
  }
}

There is always place for augmented functionalities to built in methods. Especially in the form of shims or pollyfills for older browsers. Browsers that supports ES5 or less.

Conclusion

The purpose of this article is to learn about extending the built objects. JavaScript makes it so easy to achieve them while considering some caveats.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.