Arithmetic Calculator

Run simple arithmetic calculator functions: add, subtract, multiply and divide.
Created By
Zoran Slamkov
Voiceflow Built
INPUT VARIABLES
{
number1
}
first number input (string)
{
number2
}
second number input (string)
{
operation
}
Arithmetic operation: add, subtract, multiply, divide
{
}
{
}
{
}
OUTPUT VARIABLES
{
result
}
calculated result
{
}
{
}
{
}
{
}
{
}
PATHS
{
success
}
success path
{
}
{
}
{
}
{
}
{
}

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}`
      }
    }]
  };
}

Function Walkthrough