Skip to content

Instantly share code, notes, and snippets.

@mrloop
Created March 12, 2016 09:38
Show Gist options
  • Save mrloop/b54cce53a28e07dabba0 to your computer and use it in GitHub Desktop.
Save mrloop/b54cce53a28e07dabba0 to your computer and use it in GitHub Desktop.
Simple minimal version of https://github.com/mrloop/vehicle-app, run via node `node part.js`
var part = function (spec) {
var that = {
getName: function (){
return spec.name
},
toString: function () {
var str = this.getName() + '\n' + this.getCents() + '\n';
return str + this.map(spec.parts, function(part){
return part.toString();
}).join('');
},
setParts: function(parts) {
spec.parts = parts;
},
getParts: function () {
return spec.parts;
},
getCents: function() {
return spec.cents || 0;
},
findPartsWithFnc: function (fnc) {
var arr = [];
if(fnc(this)){
arr = [this];
}
return this.reduce(spec.parts, function(array, part){
return array.concat(part.findPartsWithFnc(fnc));
}, arr);
},
reduceWithFnc: function (fnc){
var val = fnc(this);
return this.reduce(spec.parts, function(sum, part){
return sum + part.reduceWithFnc(fnc);
}, val);
},
findPartsWithName: function(name){
return this.findPartsWithFnc(function (part){
return part.getName() === 'engine';
});
},
findPartWithName: function(name){
return this.findPartsWithName(name)[0];
},
getTotalCost: function(){
return this.reduceWithFnc(function(part){
return part.getCents();
});
},
reduce: function (array, fnc, mem) {
if(isArray(array)){
for(var i=0; i< array.length; i++) {
mem = fnc(mem, array[i]);
}
}
return mem;
},
map: function (array, fnc) {
var arr = [];
if(isArray(array)){
for(var i=0; i< array.length; i++) {
arr.push(fnc(array[i]));
}
}
return arr;
}
};
return that;
};
var json = {
name: 'car',
cents: 123123,
parts: [
{
name: 'engine',
parts: [{
name: 'piston',
cents: 1233
},{
name: 'piston',
cents: 1443
},
{
name: 'bolt',
cents: 17
},{
name: 'bolt',
cents: 17
}]
},{
name: 'wheels',
parts: [{
name: 'wheel',
cents: 1200,
parts: [{
name: 'bolt',
cents: 15
},{
name: 'bolt',
cents: 15
},{
name: 'bolt',
cents: 15
}]
},{
name: 'wheel',
cents: 1200,
parts: [{
name: 'bolt',
cents: 15
},{
name: 'bolt',
cents: 15
},{
name: 'bolt',
cents: 15
}]
}]
},{
name: 'body',
cents: 456,
parts: [{
name: 'bolt',
cents: 13
},{
name: 'bolt',
cents: 13
}]
}
]
}
var buildFromParts = function (json) {
if(isArray(json)){
var arr = []
for(var i=0; i<json.length; i++){
arr.push(buildFromParts(json[i]));
}
return arr;
}else{
var parts = json.parts;
delete(json, 'parts');
var p = part(json);
if(parts){
p.setParts(buildFromParts(parts));
}
return p;
}
}
var isArray = function (thing) {
return Object.prototype.toString.call(thing) === '[object Array]';
}
var car = buildFromParts(json);
console.log(car.toString());
console.log(car.findPartWithName('engine').getName());
console.log(car.getTotalCost());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment