8. Introduction to Functions7. Writing A Custom Aggregation Function

7 - Writing a custom aggregation Function

This content is also available at learn.palantir.com ↗ and is presented here for accessibility purposes.

📖 Task Introduction

You want to provide your Workshop module users with a metric card highlighting the percentage of unresolved alerts in the queue. Workshop can natively calculate and present numeric aggregations, but sometimes you may need to calculate a metric using business logic that is not available via the Workshop front-end.

We can extend Workshop’s capability with a Function that supplies the figure we need. In this task, you’ll add a custom Function as a method in the MyFunctions class.

🔨 Task Instructions

  1. Open the ../src/index.ts file in your repository.

  2. We need to create space for a new function inside the MyFunctions class. Place your cursor after the closed brace on line 8 and hit enter twice.

  3. Insert the following code block, being careful to ensure the @Function() decorator and public... lines are aligned with the function above.

    • Also replace jmeierPercentUnresolved with a dedicated name you'll recognize (for example, replace jmeier with your name) and replace JmeierFlightAlert with your API name.
    • The comments in the code describe the operations being performed.
    @Function()
        //Take in an array of flight alert objects aliased as "alerts" 
        //and return a Double
        public jmeierPercentUnresolved(alerts: JmeierFlightAlert[]): Double {
        
        //Check that your array actually has objects in it, otherwise return a "0"
            if (alerts.length === 0) {
                return 0;
            }
        
        //Cycle through your array incrementing a variable ("numberUnresolved") 
        //by 1 every time it encounters an alert without a resolved status
            let numberUnresolved = 0;
            for (const alert of alerts) {
                if (alert.status != "Resolved") {
                    numberUnresolved++;
                }
            }
        
        //return the number of un-resolved alerts divided by the 
        //length of the original array
            return numberUnresolved/alerts.length;
        }
    
  4. If your Code Assist is running, you’ll see that the output type of Double is underlined in red, indicating an issue with the code. In short, your repository has discovered a type that has not been imported.

    • Add Double to the Functions API import statement: import { Function, Integer, Double } from "@foundry/functions-api";