leetcode 3. 写接受任何值val,并返回一个具有以下两个函数的对象函数

编写一个函数,帮助开发人员测试代码。它应该接受任何值val,并返回一个具有以下两个函数的对象。
toBe(val)接受另一个值,如果两个值彼此===,则返回true。如果它们不相等,它应该抛出一个错误“不相等”。
notToBe(val)接受另一个值,如果这两个值为true,则返回true!==彼此如果它们相等,它应该抛出一个错误“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.

解决:

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

function expect(val: any): ToBeOrNotToBe {
    let toBeOrNotToBe = {
            toBe:  (actualVal) => {
                if (actualVal === val) {
                    return true;
                } else {
                    throw new Error("Not Equal");
                }
               
            },
            notToBe: (actualVal) => {
                if (actualVal !== val) {
                    return true;
                } else {
                    throw new Error("Equal");
                }
            }
                
    }
    return toBeOrNotToBe;
  
};

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

知识点:
1.throw new Error("Not Equal");
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Statements/throw
2.闭包

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容