Translate

Friday, 3 May 2024

Write a dw script to check if the input is a prime number? in MuleSoft 377

 Write a dw script to check if the input is a prime number? in MuleSoft


Here's a DataWeave script in MuleSoft 4 to check if the input is a prime number:



Code snippet


%dw 2.0
output application/json

fun isPrime(payload: number) = (payload > 1)
  where not (2 to payload - 1) any ((item) -> mod(payload, item) == 0)

---
isPrime(payload)

Explanation:

  1. Function Definition: We define a function named isPrime that takes a single argument payload of type number.

  2. Prime Number Check: The function first checks if the payload is greater than 1. This is because 1 is not considered a prime number.

  3. where Clause: The where clause filters the numbers between 2 and payload (inclusive) using a range (2 to payload - 1).

  4. any Function: We use the any function to check if any of the numbers in the range divide the payload perfectly (with no remainder).

  5. mod Function: The mod function calculates the remainder when payload is divided by each number in the range.

  6. == 0 Check: The any function checks if the remainder (mod(payload, item)) is equal to 0. If any remainder is 0, it means the payload is not a prime number.

  7. Function Return: The where clause returns true if no remainder is 0 (indicating a prime number), and false otherwise. The overall function (isPrime) returns this result.

Main Flow:

  • The --- line separates the function definition from the main flow.

  • The script calls the isPrime function with the message payload (payload).

  • The result (true or false) is then the output of the DataWeave script.

Usage:

You can use this script in a MuleSoft flow by setting the message payload to the number you want to check and then invoking the DataWeave script. The output will be true if the number is prime and false otherwise.


No comments:

Post a Comment

Note: only a member of this blog may post a comment.