Skip to content

Instantly share code, notes, and snippets.

@kellishouts
Last active August 29, 2015 14:14
Show Gist options
  • Save kellishouts/04322c2fb49487a86bf9 to your computer and use it in GitHub Desktop.
Save kellishouts/04322c2fb49487a86bf9 to your computer and use it in GitHub Desktop.
Review Callbacks
//callbacks
var counter = 0;
var english = ["zero","one","two","three"];
function increase( cb ){
counter = counter + 1;
var counter_in_english = english[counter];
cb( counter_in_english );
}
increase( function( english_word ){
console.log( english_word );
} );
increase( function( english_word ){
console.log( english_word );
} );
increase( function( english_word ){
console.log( english_word );
} );
// multiple callbacks
var counter = 0;
var english = ["zero","one","two","three"];
function increase( success_cb, fail_cb ){
counter = counter + 1;
var counter_in_english = english[counter];
if( counter % 2 == 0 ){
even_cb( counter_in_english );
}else{
odd_cb( counter_in_english );
}
}
increase( function( english_word ){
console.log( "EVEN", english_word );
}, function( english_word ){
console.log( "ODD", english_word );
} );
increase( function( english_word ){
console.log( "EVEN", english_word );
}, function( english_word ){
console.log( "ODD", english_word );
} );
increase( function( english_word ){
console.log( "EVEN", english_word );
}, function( english_word ){
console.log( "ODD", english_word );
} );
// another example
var counter = 0;
var english = ["zero","one","two","three"];
function increase( cb ){
counter = counter + 1;
var counter_in_english = english[counter];
cb( counter_in_english );
}
increase( function( english_word ){
console.log( english_word );
} );
increase( function( ){
console.log( "lloose" );
} );
increase( function( english_word ){
console.log( english_word );
} );
// milk example
var milk = 2;
function getMilkFromStore( action ){
milk = milk - 1;
var hadMilk = milk > -1 ;
var brand = "moo moo milk";
action( hadMilk );
}
function afterGettingMilk( hadMilk ){
if( hadMilk ){
console.log('drink some milk');
}else{
console.log('sad face');
}
}
getMilkFromStore( afterGettingMilk ); // true
getMilkFromStore( afterGettingMilk ); // true
getMilkFromStore( afterGettingMilk ); // false
// ray's milk example
var groceryStore = {
Fruit: ["Apple", "Bananas", "Oranges"],
Milk: ["Low-Fat", "Skim", "Whole Milk"],
Candy: ["Goodbar", "Reese's pieces", "Sour Patch Kids"]
};
function goTo(location, aisle, callback){
for (var thisAisle in location) {
if (thisAisle === aisle) {
location[thisAisle].forEach(function(item){
var result = callback(item);
if (result === true) {
console.log("I found the " + item + " " + aisle);
}
});
}
}
}
goTo(groceryStore, "Milk", skimMilk);
function skimMilk () {
if (type === "Skim") {
return true;
}
return false;
}
function sourPatchKids() {
if (type === "Sour Patch Kids") {
return true;
}
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment