jquery - Iterate Through Nested JavaScript Objects - Dirty? -
i have javascript wrote in pinch, think optimized smarter me. code runs on relatively small objects, runs fair amount of times, worth getting right:
/** * determine maximum quantity can show (ever) these size/color combos * * @return int=settings.limitedstockthreshold */ function getmaxdefaultquantity() { var max_default_quantity = 1; if (inventory && inventory.sizes) { sizecolor_combo_loop: (var key in inventory.sizes) { if (inventory.sizes[key].combos) { (var key2 in inventory.sizes[key].combos) { var sizecolor_combo = inventory.sizes[key].combos[key2]; if (isbackorderable(sizecolor_combo)) { //if 1 backorderable, can break out max_default_quantity = settings.limitedstockthreshold; break sizecolor_combo_loop; } else { //not backorderable, largest quantity (sizecolor_combo or max_default_quantity) var qoh = parseint(sizecolor_combo.quantityonhand || 1); if (qoh > max_default_quantity) { max_default_quantity = qoh; }; }; }; }; }; }; return math.min(max_default_quantity, settings.limitedstockthreshold); };
first, inventory object returned via json. has property inventory.sizes contain of available sizes product. each size has property inventory.sizes.combos maps of available colors size. each combo has property quantityonhand tells quantity available specific combo. (the json structure returned cannot modified)
what code loop through each size, each size's combos. checks if size-color combo backorderable (via method). if combo backorderable, can stop because default quantity defined elsewhere. if combo isn't backorderable, max_default_quantity largest quantityonhand find (with maximum of settings.limitedstockthreshold).
i don't nested loops , handling of math , default values feels overly complicated.
also, whole function wrapped in larger jquery object if helps clean up.
have considered using map-reduce? see live example of functional approach.
this particular example uses underscore.js can keep on elegant level without having implement details.
function dostuff(inventory) { var max = settings.limitedstockthreshold; if (!(inventory && inventory.sizes)) return; var quantity = _(inventory.sizes).chain() .filter(function(value) { return value.combos; }) .map(function(value) { return _(value.combos).chain() .map(function(value) { return isbackorderable(value) ? max : value.quantityonhand; }) .max().value(); }) .max().value(); return math.min(quantity, max); }
as explanation:
we take inventory.sizes set , remove don't contain combos. map each size maximum quantity of it's colour. mapping each combo either quantity or maximum quantity if backordable. take max of set.
finally take max of set of maxquantities per size.
we're still effectily doing double loop since take 2 .max
on set doesn't dirty.
there couple of if checks had in place still there.
[edit]
i'm pretty sure above code can optimized lot more. it's different way of looking @ it.
Comments
Post a Comment