There are several ways that you could create a common reusable shared function in Karate Test Automation but I method I prefer is to write it in Java and then call it from the feature file.
By writing it in Java, it is easier to step through to debug if the function you are building has bugs in it. I’ve created a Java file named MyRandom.java and placed it at the location shown in the screenshot below.
The content of the MyRandom.java
Define the function in feature file background section and you will be able to call it like a normal function. See screenshot below.
When the scenario is ran, it will print the random numbers declared in the Java file.