系列章節前端手寫題

[Easy] LeetCode JS 30 - 2704. To Be Or Not To Be (手寫 expect 函式)

2024年3月5日

重點摘要

「[Easy] LeetCode JS 30 - 2704. 手寫 expect 函式」文章教學,詳細解題思路與程式碼範例,幫助你輕鬆理解如何使用 JavaScript 實作簡易的測試框架,驗證程式碼的執行結果。

LeetCode 30 Days of JavaScript

本題來自 LeetCode 的 30 天 JacaScript 挑戰

2704. To Be Or Not To Be (手寫 expect 函式)

題目描述

為了幫助開發人員測試程式碼,你需要撰寫一個 expect 的函式。該函式可以接受任何值 val,並返回一個包含以下兩個功能的物件:

  • toBe(val) 接受另一個值,如果這兩個值相等(即 ===),則返回 true。如果不相等,則會拋出一個錯誤訊息 "Not Equal"。
  • notToBe(val) 接受另一個值,如果這兩個值不相等(即 !==),則返回 true。如果相等,則會拋出一個錯誤訊息 "Equal"。
// 範例一
輸入: func = () => expect(5).toBe(5)
輸出: {"value": true}
解說: 5 === 5 so this expression returns true.

// 範例二
輸入: func = () => expect(5).toBe(null)
輸出: {"error": "Not Equal"}
解說: 5 !== null so this expression throw the error "Not Equal".

本題解答

以下是本題的解答,詳細解題思路可以在 E+ 會員方案 看到。如果想練習更多題目,推薦可以到 GreatFrontEnd 上練習。

解法

var expect = function (val) {
  return {
    toBe: (value) => {
      if (value !== val) {
        throw new Error("Not Equal");
      } else {
        return true;
      }
    },
    notToBe: (value) => {
      if (value === val) {
        throw new Error("Equal");
      } else {
        return true;
      }
    },
  };
};
E+ 會員方案

獲得更完整深入的專屬內容

如果你喜歡 ExplainThis 分享的內容,歡迎加入 E+ 會員

除了專屬的文章、影片、社群,也支持 ExplainThis 持續創作