Jeff的隨手筆記

學習當一個前端工程師

0%

用LeetCode寫日記-Day3

今天是第3天,繼續加油!
今天的題目偷看答案了,沒有想到這麼快….

Day 3: To Be Or Not To Be

問題描述:

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".

問題難度:Easy

問題限制:無

我的解題思路

分析:

卡關在他要回傳兩個方法,沒有遇過不知道該如何處理,研究了一下子還是答不出來只好去看解答。

看到第一篇有教學才知道原來這樣就可以了:

1
2
3
4
5
6
7
8
return {
toBe: (parameters) => {
[doing some stuff]
},
notToBe: (parameters) => {
[doing some stuff]
}
}

既然了解要如何回傳兩個方法後,接下來就是處理[doing some stuff]
裡面就是簡單的if判斷式,就不在多說了

1
2
3
4
5
6
7
8
9
10
11
12
var expect = function(val) {
return {
toBe: (val2) => {
if (val !== val2) throw new Error('Not Equal')
return true
},
notToBe: (val2) => {
if (val === val2) throw new Error('Equal')
return true
}
}
};

其他解法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
var expect = function(val) {
return {
x : val,
notToBe : function(key){
if (this.x === key) {
throw new Error("Equal");
}
return true;
},
toBe : function(key){
if (this.x !== key) {
throw new Error("Not Equal");
}
return true;
}
}
};

這是一個思路相同但是用this的方式。

結語

只要了解如何回傳兩個方法其實這真的不難,不知道是剛睡醒還是怎樣,明明很簡單的東西卻是想不出來怎麼回答,真的是令人難過!