LeetCode 题解工作台

相等还是不相等

请你编写一个名为 expect 的函数,用于帮助开发人员测试他们的代码。它应该接受任何值 val 并返回一个包含以下两个函数的对象。 toBe(val) 接受另一个值并在两个值相等( === )时返回 true 。如果它们不相等,则应抛出错误 "Not Equal" 。 notToBe(val) 接…

category

0

题型

code_blocks

2

代码语言

hub

0

相关题

当前训练重点

简单 · To Be Or Not To Be core interview pattern

bolt

答案摘要

type ToBeOrNotToBe = { toBe: (val: any) => boolean;

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 To Be Or Not To Be core interview pattern 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

请你编写一个名为 expect 的函数,用于帮助开发人员测试他们的代码。它应该接受任何值 val 并返回一个包含以下两个函数的对象。

  • toBe(val) 接受另一个值并在两个值相等( === )时返回 true 。如果它们不相等,则应抛出错误 "Not Equal"
  • notToBe(val) 接受另一个值并在两个值不相等( !== )时返回 true 。如果它们相等,则应抛出错误 "Equal"

 

示例 1:

输入:func = () => expect(5).toBe(5)
输出:{"value": true}
解释:5 === 5 因此该表达式返回 true。

示例 2:

输入:func = () => expect(5).toBe(null)
输出:{"error": "Not Equal"}
解释:5 !== null 因此抛出错误 "Not Equal".

示例 3:

输入:func = () => expect(5).notToBe(null)
输出:{"value": true}
解释:5 !== null 因此该表达式返回 true.
lightbulb

解题思路

方法一

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/**
 * @param {string} val
 * @return {Object}
 */
var expect = function (val) {
    return {
        toBe: function (expected) {
            if (val !== expected) {
                throw new Error('Not Equal');
            }
            return true;
        },
        notToBe: function (expected) {
            if (val === expected) {
                throw new Error('Equal');
            }
            return true;
        },
    };
};

/**
 * expect(5).toBe(5); // true
 * expect(5).notToBe(5); // throws "Equal"
 */
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Evaluates the candidate's understanding of equality and inequality checks.

  • question_mark

    Tests the candidate’s ability to implement method chaining.

  • question_mark

    Checks the candidate's approach to handling edge cases like null and undefined.

warning

常见陷阱

外企场景
  • error

    Confusing 'toBe' with '===' in JavaScript which only checks strict equality.

  • error

    Incorrectly implementing the 'notToBe' method to return true for equal values instead of false.

  • error

    Not handling edge cases such as null or undefined in the comparisons.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Adding more methods for greater flexibility, like 'toBeGreaterThan' or 'toBeLessThan'.

  • arrow_right_alt

    Handling deep equality comparisons (e.g., arrays or objects).

  • arrow_right_alt

    Improving the solution by adding customizable error messages.

help

常见问题

外企场景

相等还是不相等题解:To Be Or Not To Be core… | LeetCode #2704 简单