Skip to content

Instantly share code, notes, and snippets.

@pragmaticobjects
pragmaticobjects / closure.js
Created September 9, 2011 13:07
Closure example
a = {};
function outer() {
var b = 0;
var c = function inner() {
var d = 10;
b = d + b + 1;
console.log(b);
}
a = c;
var tax= 0.08;
var fee = 10;
var sinTax = 0.02;
(function f(item, price) {
var h = {
'gas': function() {
var total = price + price*tax + fee;
alert(total);
},
@pragmaticobjects
pragmaticobjects / onclick.js
Created September 10, 2011 22:40
Onclick in a loop problem
var myElements = [ /* DOM Collection */ ];
for (var i = 0; i < 100; ++i) {
myElements[i].onclick = function() {
alert( 'You clicked on: ' + i );
};
}
@pragmaticobjects
pragmaticobjects / onclick.js
Created September 10, 2011 23:06
Closure solution
for (var i = 0; i < 100; ++i) {
myElements[i].onclick = (function(n) {
return function() {
alert( 'You clicked on: ' + n );
};
})(i);
}
@pragmaticobjects
pragmaticobjects / iterator.js
Created September 10, 2011 23:13
Closure iterator
var myarr = ["a", "b", "c"];
function iterator(arr) {
var idx = 0;
return function () {
return arr[idx++];
}
}
var getNext = iterator(myarr);
@pragmaticobjects
pragmaticobjects / switchcase.js
Created September 11, 2011 04:32
Switch Case
var calculateTotal = function(item, price) {
var tax= 0.08;
var fee = 10;
var sinTax = 0.02;
switch (item) {
case 'gas':
return price + price*tax + fee;
case 'wine':
return price + price*tax + price*sinTax;
@pragmaticobjects
pragmaticobjects / closureusage.js
Created September 11, 2011 04:37
Closure to replace switch case
var calculateTotal = function f(item) {
var tax= 0.08;
var fee = 10;
var sinTax = 0.02;
var h = {
'gas': function(price) {
return price + price*tax + fee;
},
'wine': function(price) {
return price + price*tax + price*sinTax;
@pragmaticobjects
pragmaticobjects / closureusage2.js
Created September 11, 2011 04:47
Closure to replace switch case 2
var calculateTotal = function f(item) {
var tax= 0.08;
var fee = 10;
var sinTax = 0.02;
var calGas = function(price) { return price + price*tax + fee; };
var calSinProd = function(price) { return price + price*tax + price*sinTax; };
var calFoodAsDefault = function(price) { return price + price*tax; };
var h = {
@pragmaticobjects
pragmaticobjects / closureusage3.js
Created September 11, 2011 05:04
Closure to replace switch case 3
var total = (function f(item) {
var tax= 0.08;
var fee = 10;
var sinTax = 0.02;
var calGas = function(price) { return price + price*tax + fee; };
var calSinProd = function(price) { return price + price*tax + price*sinTax; };
var calFood = function(price) { return price + price*tax; };
var h = {