Simple JavaScript stack Module pattern.

Well i needed a simple stack to hold some values and i came up with this simple stack but you can use an array, i build this just for fun and to implement the module pattern in JavaScript. Have fun.

var mp = (function stack() {
    var _store = {};
    var index  = 0;
    var _push  = function(val) {
        if(val) {
            index++;
            _store[index]=val;
        }
    };
    var _len = function() {
        return index;
    };
    var _pop = function() {
        if (index >= 0) {
          var v = _store[index];
          delete _store[index];
          index--;
          return  v;
        }
    };
    return {
        len : _len,
        push: _push,
        pop : _pop
    };
}());


mp.push(10);
mp.push(11);
mp.push(12);
mp.push(13);
console.log(mp.len());
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s