Search code examples
lookupfinancepowershell-5.0

How can I implement a lookup table in PowerShell for a 2-dimensional dataset?


I'm writing a financial app and need to implement a lookup table (for the rate table shown) that when given a term and deposit, returns an interest rate

How can I implement this lookup table in PowerShell?

rates table


Solution

  • A hash table of hash tables meets my needs

    Note: I used ordered hashtables so the table will appear in order by term (top to bottom) and minimum (left to right) if I choose to output the table for the user

    class Rates
    {
        $ratesTable=[ordered]@{}
    
        Rates()
        {
            $this.ratesTable.add(12,[ordered]@{1000=.02;10000=.021;20000=.022;50000=.023;100000=.024})
            $this.ratesTable.add(24,[ordered]@{1000=.03;10000=.031;20000=.032;50000=.033;100000=.034})
            $this.ratesTable.add(36,[ordered]@{1000=.04;10000=.041;20000=.042;50000=.043;100000=.044})
            $this.ratesTable.add(48,[ordered]@{1000=.05;10000=.051;20000=.052;50000=.053;100000=.054})
            $this.ratesTable.add(60,[ordered]@{1000=.06;10000=.061;20000=.062;50000=.063;100000=.064})
        }
    
        [double] GetRate([int]$term, [int] $deposit)
        {
            $relevantMin = 0
            $found = $false
            $mins = $this.ratesTable.$term
    
            if ($mins)
            {
    
                ForEach ($min in $mins.GetEnumerator())
                {
                    if ($deposit -gt $min.Name)
                    {
                        $relevantMin = $min.Name
                        $found = $true
                    }
                    else
                    {
                        break
                    }
                }
            }
    
            if ($found)
            {
                return [double](($this.ratesTable.$term).$relevantMin)
            }
            else
            {
                return [double](-1)
            }
        }
    }
    
    cls
    
    $rate = [Rates]::new()
    
    #example - valid term and deposit
    $rate.GetRate(36,32000)
    
    #example - valid term and deposit
    $rate.GetRate(12,24000)
    
    #example - valid term and invalid deposit
    $rate.GetRate(36,500)
    
    #example - invalid term and valid deposit
    $rate.GetRate(72,16000)
    
    #example - valid term and valid deposit
    $rate.GetRate(60,10000000)
    

    Output

    0.042
    0.022
    -1
    -1
    0.064