Stack Program in Object Functional Programming

5/24/2012 code-examplejavascriptnodejs

# Summary

I have always used stack program as the first simplest example to express something new but powerful as previously I had shown Stack in Android App (opens new window) and now Stack Program in Object Functional Programming language using Javascript

Here we will need a node js server to run this program which is saved as js extension

In the following program, we created a closure of the Stack function and passed/called the messages like push, pop & print.

The var variables within Stack function are local to stack function and hence we can say this is an idiom for achieving the encapsulation principal of a class.

Since obj is the object here, so what if we say obj.sp = 20;

Don't worry, this will create a new variable inside obj table/object which will not affect the functionality of the closure that we are working onto i.e. Stack for now.

# Screenshot

Stack Program in Object Function Programming

# Code

function Stack(){
	var sp = 10;
	var stk = new Array(10);
	this.push = function(v){
		if(sp == 0){
			console.log("overflow");
		}else{
			sp = sp - 1;
			stk[sp] = v;
		}
	}
	this.pop = function(){
		if(sp == 10){
			console.log("underflow");
		}else{
			var temp = stk[sp];
			sp = sp + 1;
			return temp;
		}
	}
	this.print = function(){
		console.log("printing stack");
		for(i = sp;i<10;i++){
			console.log(stk[i]);
		}
	}
}

// above was creation of function name Stack
// Lets now create an object of the above function

var obj = new Stack();
/*
 * obj here is object of Stack or you can also say its a new closure formed using Stack function
 */
 
 obj.push(10);
 obj.push(20);

 obj.print();
 console.log("Poped out: " + obj.pop());
 obj.push(40);
 obj.push(50);
 obj.print();
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44