Working with Google Apps Script:
I have a scenario where I need to process two arrays. The first array contains monetary values extracted from an invoice, and the second array contains applicable VAT/tax rates.
The goal is to pair each tax value with its corresponding monetary value from the array.
To illustrate, consider the following input:
https://i.sstatic.net/trAqsdBy.jpg
Based on the given input arrays:
values = [4000, 2500, 2066.12, 2000, 1834.86];
taxRates = [9,21];
The expected output in this case would be:
taxAmounts = [[2000, 2500], [1834.86, 2066.12]];
This resulting output corresponds to the colors shown in the provided image, indicating the source of each number:
taxAmounts[0][0] = 2000 = green = inclusive tax amount (for taxRates[0])
taxAmounts[1][0] = 1834.86 = brown = exclusive tax amount (for taxRates[0])
taxAmounts[0][1] = 2500 = yellow = inclusive tax amount (for taxRates[1])
taxAmounts[1][1] = 2066.12 = pink = exclusive tax amount (for taxRates[1])
In essence, the objective is to compute:
inclusive tax amounts for each tax rate specified in 'taxRates'
exclusive tax amounts for each tax rate specified in 'taxRates'
Approach Taken:(pseudo code)
Algorithmically search for two items in the array that differ by 21%
Upon finding, check if the higher of these numbers is also the maximum within the array
If it's the highest number --> return this number (indicating only one tax bracket)
If not the highest number --> multiple tax brackets exist
Check for matching value pairs for the next item in the 'taxRates' Array (recursive approach)
If sum of the found numbers equals the highest number in the array -->
Return these two numbers
Else continue searching for lower percentage values, e.g., 104%, until...
...sum of all matched values equals the highest number in the array, then return these numbers
If no suitable match is found after exhaustive checks
Return undefined;
Attempts have been made to implement the above logic into code form, but so far the output isn't as anticipated. There likely exists room for improvement in writing a more efficient solution.
Snippet of the attempted code:
function findBtwPairs(btwRates, amountsArr, incBtwArr, exBtwArr){
// Code implementation here...
}
// Helper functions defined below...
function sumArray(array){
return array.reduce(add, 0);
}
function add(accumulator, a) {
return accumulator + a;
}
function roundTo(num, decimals) {
return (+num.toFixed(decimals));
}