编写一个函数,帮助开发人员测试代码。它应该接受任何值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.闭包