I know the pattern that basically tells you to create a js object and then pass in that object as a param into the parent function, but I have a slight twist on this that I wanted to see if was possible.
Say I have the following parent function
//helper functions
function handleArray(array, target, n) {
for (var i = 0; i < n; i++) {
array.push(new target());
}
}
//parent function
function tally(n1, n2, n3, n4, n5, cargo) {
var sportArray = [];
var familyArray = [];
var truckArray = [];
var miniArray = [];
var cargoArray = [];
var output =[];
var parsed = [];
var names = [];
//buids out my objects based on helper function above
handleArray(sportArray,SportsCar, n1);
handleArray(familyArray,FamilyCar, n2);
handleArray(truckArray,Truck, n3);
handleArray(miniArray,MiniVan, n4);
handleArray(cargoArray,CargoVan, n5);
//storing all the cars together in mega array
var carArray = sportArray.concat(familyArray, truckArray, miniArray, cargoArray);
//gives us a mapped array of just the capacity values stored in one neat array
var carsMapped = carArray.map( function(o) { return o.capacity; });
var startCargo = cargo; //maintain original in memory
var sumTotal = carsMapped.reduce(function(prev,curr){
return prev + curr;
});
// strggling hard core here maybe revise OO properties to make easier?
// var test = full(carsMapped, cargo);
// console.log();
//now for the printing finale!!!!
console.log("Allocating " + startCargo + " LB of cargo in total");
for(var i = 0; i < carArray.length; i++) {
names.push(carArray[i].type);
parsed.push(carArray[i].capacity);
console.log( "A " + names[i] + " with " + parsed[i] + " LBs");
}
console.log("We have " + cargo + " LBs of cargo left over.")
}
// //test output
tally(1,3,4,2,1, 7356);
// tally(1, 6, 1, 2, 3, 7356);
// // tally(1,1,1,1,1);
// // tally(0,0,1,0,0);
I want to be able to condense n1..n5 arguments into ideally just two arguments. However if I understand the options object param it would be something like this:
var options = {
sport: 'n1',
family: 'n2',
truck: n3,
mini: n4,
cargo: n5
}
function tally(options, cargo){...;}
This is fine except I cant actuallly set the values of n1..n5 like before hand and this is critical to my parent function tally to work because n1..n5 represent different objects that are created on the fly.
Any patterns or tips on how I could use less arguments while working around these issues?
Thanks~
optionsobject where each key matches an argument (n1,n2, etc.) and the value would be the value you want to pass for that argument.n1: 'sport', n2: 'family'etc.