Created
September 22, 2011 00:39
-
-
Save joeegan/1233748 to your computer and use it in GitHub Desktop.
strat vs switch
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Object.size = function(obj) { | |
| var size = 0, key; | |
| for (key in obj) { | |
| if (obj.hasOwnProperty(key)) size++; | |
| } | |
| return size; | |
| }; | |
| function randomResultInArray (obj) { | |
| return obj[Math.floor(Math.random()*obj.length)]; | |
| } | |
| function randomIndexInObject (obj) { | |
| return Math.floor( Math.random() * (Object.size(obj)-1) ); | |
| } | |
| function capitalise(string) { | |
| return string.charAt(0).toUpperCase() + string.slice(1); | |
| } | |
| function print(msg) { | |
| document.write(msg + "<br>"); | |
| } | |
| /************* switch vs strategy *************/ | |
| /* switch (array) */ | |
| var fruitBasket = ["Oranges", "Apples", "Bananas", "Cherries"], | |
| fruitName = randomResultInArray(fruitBasket); | |
| switch (fruitName) { | |
| case "Oranges": | |
| print("Oranges are £0.59 a pound."); | |
| break; | |
| case "Apples": | |
| print("Apples are £0.32 a pound."); | |
| break; | |
| case "Bananas": | |
| print("Bananas are £0.48 a pound."); | |
| break; | |
| case "Cherries": | |
| print("Cherries are £3.00 a pound."); | |
| break; | |
| } | |
| /* strategy (obj) */ | |
| var stratFruitBasket = { | |
| oranges: "are £0.59 a pound.<br>", | |
| apples: "are £0.32 a pound.<br>", | |
| bananas: "are £0.48 a pound.<br>", | |
| cherries: "are £3.00 a pound.<br>" | |
| }; | |
| var i = 0, | |
| randIndex = randomIndexInObject(stratFruitBasket); | |
| $.each( stratFruitBasket, function( propertyName, fruitName ) { | |
| if (i == randIndex) { | |
| print(capitalise(propertyName) + " " + fruitName); | |
| return false; | |
| } | |
| i++; | |
| }); | |
| /* | |
| var cheeses = { | |
| cheddar: { | |
| complements: 'pickle', | |
| washDownWith: 'milk' | |
| }, | |
| stilton: { | |
| complements: 'beetroot', | |
| washDownWith: 'port', | |
| } | |
| }; | |
| $.each( cheeses, function( propertyName, cheese ) { | |
| $('<li>', { | |
| html: cheese.complements, | |
| id: propertyName | |
| }).appendTo( 'nav' ); | |
| }); | |
| */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment