Skip to content

Instantly share code, notes, and snippets.

@JakeSidSmith
Last active September 1, 2017 17:00
Show Gist options
  • Save JakeSidSmith/fe8043995c1a650df7c2 to your computer and use it in GitHub Desktop.
Save JakeSidSmith/fe8043995c1a650df7c2 to your computer and use it in GitHub Desktop.
Javascript stories
// 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