返回介绍

solution / 2700-2799 / 2704.To Be Or Not To Be / README_EN

发布于 2024-06-17 01:03:01 字数 2960 浏览 0 评论 0 收藏 0

2704. To Be Or Not To Be

中文文档

Description

Write a function expect that helps developers test their code. It should take in any value val and return an object with the following two functions.

  • toBe(val) accepts another value and returns true if the two values === each other. If they are not equal, it should throw an error "Not Equal".
  • notToBe(val) accepts another value and returns true if the two values !== each other. If they are equal, it should throw an error "Equal".

 

Example 1:

Input: func = () => expect(5).toBe(5)
Output: {"value": true}
Explanation: 5 === 5 so this expression returns true.

Example 2:

Input: func = () => expect(5).toBe(null)
Output: {"error": "Not Equal"}
Explanation: 5 !== null so this expression throw the error "Not Equal".

Example 3:

Input: func = () => expect(5).notToBe(null)
Output: {"value": true}
Explanation: 5 !== null so this expression returns true.

Solutions

Solution 1

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

function expect(val: any): ToBeOrNotToBe {
  return {
    toBe: (toBeVal: any) => {
      if (val !== toBeVal) {
        throw new Error('Not Equal');
      }
      return true;
    },
    notToBe: (notToBeVal: any) => {
      if (val === notToBeVal) {
        throw new Error('Equal');
      }
      return true;
    },
  };
}

/**
 * expect(5).toBe(5); // true
 * expect(5).notToBe(5); // throws "Equal"
 */
/**
 * @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"
 */

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文