Created
February 28, 2018 11:10
-
-
Save haingdc/ecaaf2b514a4ba94cd9ae47cb696f5e2 to your computer and use it in GitHub Desktop.
A Gentle Introduction to Functional JavaScript: Part 2
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
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset="utf-8"> | |
<meta name="viewport" content="width=device-width"> | |
<title>JS Bin</title> | |
</head> | |
<body> | |
<div id="pony-list-wrapper"></div> | |
<script> | |
var ponies = [ | |
[ | |
['name', 'Fluttershy'], | |
['image', 'http://tinyurl.com/gpbnlf6'], | |
['description', 'Fluttershy is a female Pegasus pony and one of the main characters of My Little Pony Friendship is Magic.'] | |
], | |
[ | |
['name', 'Applejack'], | |
['image', 'http://tinyurl.com/gkur8a6'], | |
['description', 'Applejack is a female Earth pony and one of the main characters of My Little Pony Friendship is Magic.'] | |
], | |
[ | |
['name', 'Twilight Sparkle'], | |
['image', 'http://tinyurl.com/hj877vs'], | |
['description', 'Twilight Sparkle is the primary main character of My Little Pony Friendship is Magic.'] | |
] | |
]; | |
function joinWord(sentence, word) { | |
return sentence + ' ' + word; | |
} | |
var map = function(callback, array) { | |
var newArray = []; | |
for (var i = 0; i < array.length; i = i + 1) { | |
newArray[i] = callback(array[i], i); | |
} | |
return newArray; | |
}; | |
var reduce = function(callback, initialValue, array) { | |
var working = initialValue; | |
for (var i = 0; i < array.length; i = i + 1) { | |
working = callback(working, array[i]); | |
} | |
return working; | |
}; | |
var addToObject = function(obj, arr) { | |
obj[arr[0]] = arr[1]; | |
return obj; | |
}; | |
var ponyArrayToObject = function(ponyArray) { | |
return reduce(addToObject, {}, ponyArray); | |
}; | |
var tidyPonies = map(ponyArrayToObject, ponies); | |
/** | |
* Tweet Sized Templating Engine. | |
* By Thomas Fuchs. | |
* http://mir.aculo.us/2011/03/09/little-helpers-a-tweet-sized-javascript-templating-engine/ | |
*/ | |
function t(s,d){ | |
for(var p in d) | |
s=s.replace(new RegExp('{'+p+'}','g'), d[p]); | |
return s; | |
} | |
var ponyToListItem = function(pony) { | |
var template = '<li><img src="{image}" alt="{name}"/>' + | |
'<div><h3>{name}</h3><p>{description}</p>' + | |
'</div></li>'; | |
return t(template, pony); | |
}; | |
var ponyList = map(ponyToListItem, tidyPonies); | |
var html = '<ul>' + reduce(joinWord, '', ponyList) + '</ul>'; | |
document.getElementById('pony-list-wrapper').innerHTML = html; | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment