問題
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.
解題思路
toBe
跟 .notToBe
toBe
是當兩個值嚴格相等的時候,返回 true
,否則返回一個錯誤 "Not Equal"
notToBe
則是當兩個值不相等時,返回true
如果兩個相等 則回傳錯誤 "Equal"
所以我們的第一步要先建立一個 function
function expect(value) {}
接著我們需要她回傳兩個不同的物件 toBe
跟 notToBe
,裡面要包含用以判斷是否相等(或不相等)的funtion,我們先來解決 tobe 的部分。
從範例上可以看到以下兩點
function expect(value) {
return {
toBe:function (expect) {
if (value === expected) {
return true; }
}
回傳錯誤的時候,我們要用 throw Error
這個語法
function expect(value) {
return {
toBe:function (expected) {
if (value === expected) {
return true;
}
throw Error('Not Equal');
},
再來處理 notToBe
我們也如法泡製一次:
function expect(value) {
return {
toBe:function (expected) {
if (value === expected) {
return true;
}
throw Error('Not Equal');
},
notToBe:function (unexpected) {
if (value !== unexpected) {
return true;
}
throw Error('Equal');
}
};
}
接下來我們測試一下是否正確
完成!
但其實,上面這個寫法是很醜的,我們仔細看一下題目 notToBe(val)
的部分:
notToBe(val)
accepts another value and returnstrue
if the two values!==
each other. If they are equal, it should throw an error"Equal"
.
注意到了嗎,這題的錯誤是產生在他們相等的時候回傳的,但是在我們的 notToBe
裡,我們卻是在他不是 不是不相等的時候,才回傳這個錯誤,相對之下會比較不好讀。
notToBe:function (unexpected) {
if (value !== unexpected) {
return true;
}
throw Error('Equal');
}
};
所以我們改個寫法,變成「當他們相等的時候,直接回傳錯誤」
notToBe:function (unexpected) {
if (value === unexpected) {
throw Error('Equal')
}
return true;
為了讓程式看起來"對稱",我們也把 toBe
修改一下:
function expect(value) {
return {
toBe:function (expected) {
if (value !== expected) {
throw Error('Not Equal');
}
return true;
},