JSFiddle - React, Tailwind, and code Playground
by darul75
HTML
<div id="planets"></div>
JavaScript
var planets = [
{name: 'mercure', radius: 2440},
{name: 'venus', radius: 6052},
{name: 'earth', radius: 6378},
{name: 'mars', radius: 3397},
{name: 'jupiter', radius: 71492},
{name: 'saturn', radius: 58232},
{name: 'uranus', radius: 25362},
{name: 'neptune', radius: 24622 }
];
// 1) Function to extract a property
var prop = function(name) {
return function(object) {
return object[name];
}
}
// 2) Function to capitalize a string
var cap = function(s) {
return s.replace(/(?:^|\s)\S/g, function(a) { return a.toUpperCase(); });
}
// 3) A DSL factory to build html components.
var HtmlFactory = function() {
this.elt = {};
return {
create : function(tagName) {
this.elt = document.createElement(tagName);
return this;
},
addChild : function(child) {
this.elt.appendChild(child);
return this;
},
setProp : function(prop, value) {
this.elt[prop] = value;
return this;
},
getElement : function() {
return this.elt;
}
};
}
// 1) prepare functions to extract name and radius
var getName = prop('name');
var getRadius = prop('radius');
// 2) prepare function to build a paragraph inner text
var buildText = function(elt) {
return cap(getName(elt)) + ' radius is: ' + getRadius(elt);
}
// 3) prepare function to build a paragraph
var buildParagraphElt = function(value) {
return new HtmlFactory().create('p').setProp('innerHTML', value).getElement();
};
// 4) Composition utility
var compose = function(f,g) {
return function(x) {
return f(g(x));
}
}
// finally do the job
// build main div element
var divElt = new HtmlFactory().create('div');
var buildParagraph = compose(buildParagraphElt, buildText);
// map over items and build paragraphs html elts
var paragraphsElts = planets.map(buildParagraph);
// finally append it to div
paragraphsElts.forEach(divElt.addChild,...