/** * * @param {Array} questionnaireItems * @returns {void} */ export default function…
- User
/** *
-
@param {Array} questionnaireItems
-
@returns {void} */ export default function (questionnaireItems) { questionnaireItems.forEach((questionnaireItem) => { let product = 1; let count = 0; let min = Number.POSITIVE_INFINITY; let max = Number.NEGATIVE_INFINITY; for (const quotation of questionnaireItem.quotations) { for (const quote of quotation.cleanedQuotes) { const price = parseFloat(quote.price); quote.price = price; if (price > 0) { product *= price; count++; min = Math.min(min, price); max = Math.max(max, price); } } } const geomean = count > 0 ? Math.pow(product, 1 / count) : 0;
const stdev = Math.sqrt( questionnaireItem.quotations.reduce((sum, quotation) => { for (const quote of quotation.cleanedQuotes) { const price = parseFloat(quote.price); if (price > 0) sum += Math.pow(price - geomean, 2); } return sum; }, 0) / count ); const variation = stdev / geomean;
if (geomean > 0) { questionnaireItem.geomean = geomean.toFixed(2); questionnaireItem.stdev = stdev.toFixed(2); questionnaireItem.variation = variation.toFixed(2); questionnaireItem.min = min.toFixed(2); questionnaireItem.max = max.toFixed(2); questionnaireItem.product = product.toFixed(2); questionnaireItem.count = count.toFixed(2); } }); }
export function recalculateRow(rowData) { // console.log("Row date is: ", rowData); let product = 1; let count = 0; let min = Number.POSITIVE_INFINITY; let max = Number.NEGATIVE_INFINITY; for (const quotation of Object.values(rowData.quotes)) { for (const key of Object.keys(quotation)) { const price = parseFloat(quotation[key]); if (isOnlyQuote(key) && price > 0) { product *= price; count++; min = Math.min(min, parseFloat(price)); max = Math.max(max, price); } } } const geomean = count > 0 ? Math.pow(product, 1 / count) : 0;
const stdev = Math.sqrt( Object.values(rowData.quotes).reduce((sum, quotation) => { for (const key of Object.keys(quotation)) { const price = parseFloat(quotation[key]); if (isOnlyQuote(key) && price > 0) sum += Math.pow(price - geomean, 2); } return sum; }, 0) / (count - 1) ); const variation = stdev / geomean;
if (geomean > 0) { rowData.geomean = isNaN(geomean) ? "0" : geomean.toFixed(2); rowData.deviation = isNaN(stdev) ? "0" : stdev.toFixed(2); rowData.variation = isNaN(variation) ? "0" : variation.toFixed(2); rowData.minQ = isNaN(min) ? "0" : min.toFixed(2); rowData.maxQ = isNaN(max) ? "0" : max.toFixed(2); rowData.product = isNaN(product) ? "0" : product.toFixed(2); rowData.count = isNaN(count) ? "0" : count.toFixed(2); rowData.ratio = isNaN(max / min) ? "0" : (max / min).toFixed(2); } // console.log("Recalculated data: ", geomean, stdev, variation, rowData); }
const isOnlyQuote = (str) => { return /^((?!_)[A-Za-z0-9])+$/.test(str); }; will the above function return the right calculations when questionnaireItems with the correct data are fetched from the backend
-
- Assistant
As an AI language model, I cannot predict the behavior of a specific function without knowing the exact input and expected output. However, based on the given code, it seems that the function is correctly calculating the geomean, standard deviation, variation, min, max, product, and count for each questionnaire item and updating their properties accordingly. The
recalculateRowfunction also seems to be recalculating the same values for a single row using its quotes object. Therefore, if the questionnaireItems and rowData objects have the correct data structure and values, these functions should return the expected results. - User
useEffect(() => { // // console.log('fetching: ', saveCounter); setIsAgGridLoading(true); setRowData([]); // setColumnDefs([...initColumnDef]);
// if() let reqUrl; if (auth.userRole === userRoles.DIRECTORATE_DIRECTOR) { reqUrl = CLEANED_QUOTATIONS_GET_By_REGIONCODE( location?.state?.id, selectedRegion.code ); } else { reqUrl = CLEANED_QUOTATIONS_GET(location?.state?.id); } emisAxiosInstance .get(reqUrl, { headers: { Authorization: `Bearer ${auth.accessToken}` }, // signal: controller.signal }) .then((response) => { // console.log('grid data response: ', response); // console.log('auth: ', auth); // Calculate geomean and stuff const { marketplaces, maxQuotation } = getMarketplacesAndMaxQuotation(response); console.log( "Results : ", geomean_calculator(response.data.data.questionnaireItems) ); console.log("response: ", response); // responseData = response; setReqResponseData(response); generateRows(response, marketplaces, maxQuotation); generateColumns(response, marketplaces, maxQuotation); }); setIsAgGridLoading(false); // }, [saveCounter, fetchRegionCode]);}, [saveCounter, selectedRegion]); console logging geomean_calcultor function which is the abaove calculation fucntion shows undefined ? could this be an async await issue?
- Assistant
Yes, it's possible that the
geomean_calculatorfunction is returning undefined because of the async nature of the HTTP request and response processing.You can try adding an
asynckeyword in front of the function declaration andawaitfor the response to be returned before calling thegenerateRowsandgenerateColumnsfunctions.Additionally, set
isAgGridLoadingto false inside thethenblock of the http request, not outside of it. This is to make sure that the data processing completed before setting it to false.Example:
async function fetchData() { setIsAgGridLoading(true); setRowData([]); let reqUrl; if (auth.userRole === userRoles.DIRECTORATE_DIRECTOR) { reqUrl = CLEANED_QUOTATIONS_GET_By_REGIONCODE( location?.state?.id, selectedRegion.code ); } else { reqUrl = CLEANED_QUOTATIONS_GET(location?.state?.id); } const response = await emisAxiosInstance.get(reqUrl, { headers: { Authorization: `Bearer ${auth.accessToken}` }, // signal: controller.signal }); const { marketplaces, maxQuotation } = getMarketplacesAndMaxQuotation(response); const geomeanResults = geomean_calculator(response.data.data.questionnaireItems); console.log("Results : ", geomeanResults); generateRows(response, marketplaces, maxQuotation); generateColumns(response, marketplaces, maxQuotation); setIsAgGridLoading(false); } useEffect(() => { fetchData(); }, [saveCounter, selectedRegion]); - User
console.log("Results : ", geomeanResults); this is returning undefined
- Assistant
If the
geomeanResultsis returning undefined, it is possible that thegeomean_calculatorfunction is not returning anything. You can check if the function is implemented correctly and make sure that it returns some value.Alternatively, you can also use a try-catch block to handle any errors that may occur in processing the response and update the state accordingly.
Example:
async function fetchData() { setIsAgGridLoading(true); setRowData([]); let reqUrl; if (auth.userRole === userRoles.DIRECTORATE_DIRECTOR) { reqUrl = CLEANED_QUOTATIONS_GET_By_REGIONCODE( location?.state?.id, selectedRegion.code ); } else { reqUrl = CLEANED_QUOTATIONS_GET(location?.state?.id); } try { const response = await emisAxiosInstance.get(reqUrl, { headers: { Authorization: `Bearer ${auth.accessToken}` }, // signal: controller.signal }); const { marketplaces, maxQuotation } = getMarketplacesAndMaxQuotation(response); const geomeanResults = geomean_calculator(response.data.data.questionnaireItems); console.log("Results : ", geomeanResults); generateRows(response, marketplaces, maxQuotation); generateColumns(response, marketplaces, maxQuotation); setIsAgGridLoading(false); } catch (error) { console.log("Error fetching data: ", error); setIsAgGridLoading(false); } } useEffect(() => { fetchData(); }, [saveCounter, selectedRegion]); - User
- Assistant
The
geomean_calculatorfunction seems to be correctly calculating the geomean, standard deviation, and other values for each questionnaire item and updating their properties accordingly. It's possible that thequestionnaireItemsarray passed as input to the function is not being populated correctly or passed in the wrong format.You can try logging the
questionnaireItemsarray and see if it is being populated correctly. Also, check if there are any errors or type mismatches while passing and processing the data.