Just because I can't help myself (and like a task like this while I'm having my breakfast), here's a sheet worker that will replace both the sheet workers above, and can be expanded if you add any more repeating sections that track inventory (unlikely as that seems): // first create a variable which holds the values that each section has in common, and their specific names.
const inventories = { inventory: { weight: 'item_weight', cost: 'item_cost', amount: 'item_amount', total_weight: 'item_total_weight', total_cost: 'item_total_cost', carry: 'current_carry_weight' }, "vehicle-inventory": { weight: 'vehicle_item_weight', cost: 'vehicle_item_cost', amount: 'vehicle_item_amount', total_weight: 'vehicle_item_total_weight', total_cost: 'vehicle_item_total_cost', carry: 'vehicle_current_carry_weight' } }
// forEach is a nicer syntax than For, and allows us to loop through the two inventory types Object.keys(inventories).forEach(section => {
// we need to build on on(changes) event line, which is a bit tricky. this variable does it.
const changes = Object.values(inventories[section]).map(value => `change:repeating_${section}:${value}`).join(' '); on(changes, () => { getSectionIDs(`repeating_${section}`, IDArray => {
// changed from var to const: both do the same thing, create a variable
const fieldNames = [];
// switched to use forEach syntax since we are already using it above
IDArray.forEach(id => { fieldNames.push(`repeating_${section}_${id}_${inventories[section].weight}`); fieldNames.push(`repeating_${section}_${id}_${inventories[section].cost}`); fieldNames.push(`repeating_${section}_${id}_${inventories[section].amount}`); }); getAttrs(fieldNames, function(values) { // since we are doing the whole repeating section, we need a variable to hold the values of each row const output = {}; // we also need to count the total weight as we go let total = 0; IDArray.forEach(id => { // we need to go through each row, and get the weight, cost, and amount // and calculate the totals for that row
// getting these variables is a bit trickier in this version! He we use template literal syntax.
const weight = parseFloat(values[`repeating_${section}_${id}_${inventories[section].weight}`]) || 0; const cost = parseFloat(`repeating_${section}_${id}_${inventories[section].cost}`) || 0; const amount = parseInt(`repeating_${section}_${id}_${inventories[section].amount}`) || 0; // calculate the totals for THIS row const row_weight = weight * amount; const row_cost = cost * amount; // save those values for updating the sheet later output[`repeating_${section}_${id}_${inventories[section].total_weight}`] = row_weight; output[`repeating_${section}_${id}_${inventories[section].total_cost}`] = row_cost; // update the total weight total += row_weight; }); // now we have looped through the entire set, we need to save the total weight output[inventories[section].carry] = total; // now we can save the stats to the sheet. setAttrs(output); }); }); }); });