Skip to content

Instantly share code, notes, and snippets.

@rwaldron
Created June 7, 2012 16:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rwaldron/3fd8229d6e133c6760c9 to your computer and use it in GitHub Desktop.
Save rwaldron/3fd8229d6e133c6760c9 to your computer and use it in GitHub Desktop.
var calculator = (function () {
var result = 0;
var calculator = {
add: function (n) {
if (typeof n === "number") {
result += n;
}
return calculator;
},
subtract: function (n) {
if (typeof n === "number") {
result -= n;
}
return calculator;
},
multiply: function (n) {
if (typeof n === "number") {
result *= n;
}
return calculator;
},
Divide: function (n) {
if (typeof n === "number" && n == 0) {
result /= n;
}
return calculator;
},
getResult: function () {
return result;
}
};
return calculator;
})();
var product = calculator.add(2).add(3).getResult(),
other;
console.log( product === 5 );
other = calculator.add(2).add(3).getResult();
console.log( other === 5 ); // false!!!
// Instead, use a closed over constructor declaration to create "private" data:
(function( scope ) {
// Map instances to values
var map = [ [], [] ],
operators = {
"add": "+",
"subtract": "-",
"multiply": "*",
"divide": "/"
};
function Calculator( n ) {
if ( !(this instanceof Calculator) ) {
return new Calculator( n || 0 );
}
var value = n != null ? n : 0;
map[0].push(this);
map[1].push(value);
}
function update(key, val) {
map[1][ map[0].indexOf(key) ] = val;
}
function operate() {
var args = [].slice.call(arguments),
operator = args.shift();
// Ensure all values are numbers
args.filter(function(val) {
return +val;
});
// Safely eval the operation
return new Function("return " + args.join(operator))();
}
Calculator.prototype = {
get value() {
return map[1][ map[0].indexOf(this) ];
}
};
// Define operation methods for Calculator prototype
Object.keys( operators ).forEach(function( opKey ) {
Calculator.prototype[ opKey ] = function( n ) {
update( this, operate( operators[ opKey ], this.value, n ) );
return this;
};
});
scope.calc = Calculator;
})( global );
var v1 = calc(0).add(2).add(3).value,
v2;
console.log( v1 === 5 );
v2 = calc(0).add(2).add(3).value;
console.log( v2 === 5 ); // true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment