Last active
September 1, 2017 17:00
-
-
Save JakeSidSmith/fe8043995c1a650df7c2 to your computer and use it in GitHub Desktop.
Javascript stories
This file contains 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
// The quick brown fox jumps over the lazy dog | |
var hasAttributes = function (animal, attributes) { | |
var matches = 0; | |
for (var i = 0; i < attributes.length; i += 1) { | |
if (animal.attributes.indexOf(attributes[i]) >= 0) { | |
matches += 1; | |
} | |
} | |
if (matches === attributes.length) { | |
return true; | |
} | |
return false; | |
}; | |
var the = function (attributes, species) { | |
for (var a = 0; a < animals.length; a += 1) { | |
if (animals[a].species === species && hasAttributes(animals[a], attributes)) { | |
return animals[a]; | |
} | |
} | |
return undefined; | |
}; | |
var animals = [ | |
{ | |
species: 'fox', | |
attributes: ['quick', 'brown'], | |
height: 20, | |
jumpHeight: 64, | |
jumpsOver: function (target) { | |
return this.jumpHeight > target.height; | |
} | |
}, | |
{ | |
species: 'dog', | |
attributes: ['lazy'], | |
height: 32, | |
jumpHeight: 54 | |
} | |
]; | |
the(['quick', 'brown'], 'fox').jumpsOver(the(['lazy'], 'dog')); | |
// How much wood would a woodchuck chuck if a woodchuck could chuck wood? | |
var aWoodchuck = { | |
could: function (action, item) { | |
if (this[action]) { | |
return this[action][item] !== undefined; | |
} | |
return false; | |
}, | |
chuck: { | |
wood: 2, | |
dirt: 3, | |
grass: 4 | |
}, | |
canBeBotheredTo: [ | |
'chuck', | |
'eat' | |
] | |
}; | |
var would = function (animal, action) { | |
return { | |
'animal': animal, | |
'action': action, | |
'would': animal.canBeBotheredTo.indexOf(action) >= 0, | |
'if': function (test) { | |
var result = this; | |
result.could = test; | |
return result; | |
} | |
}; | |
}; | |
var howMuch = function (item, animal) { | |
if (animal.could) { | |
return animal.animal[animal.action][item]; | |
} | |
return 0; | |
}; | |
howMuch('wood', would(aWoodchuck, 'chuck').if(aWoodchuck.could('chuck', 'wood')) ); | |
// Hello, world | |
var world = { | |
population: 7.046 * 1000 * 1000, | |
diameter: 12.742 * 1000, | |
name: 'Earth', | |
recievedMessages: [] | |
}; | |
var hello = function (thing) { | |
thing.recievedMessages.push('Hello'); | |
}; | |
hello(world); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment