Back to all functions

Arithmetic Calculator

Run simple arithmetic calculator functions: add, subtract, multiply and divide.

Created By
Zoran Slamkov
Community
download-icon
INPUT VARIABLES
{
number1
}
first number input (string)
{
number2
}
second number input (string)
{
operation
}
Arithmetic operation: add, subtract, multiply, divide
{
}
{
}
{
}
share-icon
OUTPUT VARIABLES
{
result
}
calculated result
{
}
{
}
{
}
{
}
{
}
paths-icon
PATHS
{
success
}
success path
{
}
{
}
{
}
{
}
{
}

Function Walkthrough

Function Code Snippet


export default async function main(args) {
  const { number1, number2, operation } = args.inputVars;

  // Convert string inputs to numbers
  const num1 = parseFloat(number1);
  const num2 = parseFloat(number2);
  let result;

  switch (operation) {
    case 'add':
      result = num1 + num2;
      break;
    case 'subtract':
      result = num1 - num2;
      break;
    case 'multiply':
      result = num1 * num2;
      break;
    case 'divide':
      result = num2 !== 0 ? num1 / num2 : 'Error: Division by zero';
      break;
    default:
      result = 'Invalid operation';
  }

  return {
    next: {
      path: 'success'
    },
    outputVars: {
      result: result.toString()  // Convert the result back to a string if needed
    },
    trace: [{
      type: 'text',
      payload: {
        message: `The result is: ${result}`
      }
    }]
  };
}
copy-icon

Have something to share?

Share your creation with over 250,000 other global Voiceflow users.

ghraphic
No items found.