

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 簡易計算器的 Lambda 函數
<a name="simple-calc-nodejs-lambda-function"></a>

我們將在圖中使用 Node.js Lambda 函數執行加、減、乘、除的二進位運算。

**Topics**
+ [簡易計算器 Lambda 函數的輸入格式](#simple-calc-lambda-function-input-format)
+ [簡易計算器 Lambda 函數的輸出格式](#simple-calc-lambda-function-output-format)
+ [簡易計算器 Lambda 函數實作](#simple-calc-lambda-function-implementation)

## 簡易計算器 Lambda 函數的輸入格式
<a name="simple-calc-lambda-function-input-format"></a>

此函數接受下列格式的輸入：

```
{ "a": "Number", "b": "Number", "op": "string"}
```

其中，`op` 可以是 `(+, -, *, /, add, sub, mul, div)` 中的任一項。

## 簡易計算器 Lambda 函數的輸出格式
<a name="simple-calc-lambda-function-output-format"></a>

若操作成功，其會傳回格式如下的結果：

```
{ "a": "Number", "b": "Number", "op": "string", "c": "Number"}
```

其中的 `c` 包含了計算結果。

## 簡易計算器 Lambda 函數實作
<a name="simple-calc-lambda-function-implementation"></a>

以下是 Lambda 函數的實作：

```
export const handler = async function (event, context) {
  console.log("Received event:", JSON.stringify(event));

  if (
    event.a === undefined ||
    event.b === undefined ||
    event.op === undefined
  ) {
    return "400 Invalid Input";
  }

  const res = {};
  res.a = Number(event.a);
  res.b = Number(event.b);
  res.op = event.op;
  if (isNaN(event.a) || isNaN(event.b)) {
    return "400 Invalid Operand";
  }
  switch (event.op) {
    case "+":
    case "add":
      res.c = res.a + res.b;
      break;
    case "-":
    case "sub":
      res.c = res.a - res.b;
      break;
    case "*":
    case "mul":
      res.c = res.a * res.b;
      break;
    case "/":
    case "div":
      if (res.b == 0) {
        return "400 Divide by Zero";
      } else {
        res.c = res.a / res.b;
      }
      break;
    default:
      return "400 Invalid Operator";
  }

  return res;
};
```