Esther125 / git-practice

0 stars 0 forks source link

Week 02 回覆 #2

Open azole opened 1 month ago

azole commented 1 month ago

readme

ok

sum

fib

stack

上述問題可以回覆在 issue 裡,要不要改回去原檔案可以自行判斷,我會建議可以修改回去,保持作業的完整性與品質。

Esther125 commented 2 weeks ago

sum

// Method2: Use forEach() Function function sum_with_for_each(ary) { let sum = 0; ary.forEach((element) => { sum += element; }); return sum; } console.log(sum_with_for_each([1, 5, 3, 2])); // 11

// Method3: Use join() & eval() function sum_with_eval_and_join(ary) { let result = eval(ary.join("+")); return result; } console.log(sum_with_eval_and_join([1, 5, 3, 2])); // 11

// Method4: Use lodash var _ = require("lodash"); function sum_withlodash(ary) { let result = .sum(ary); return result; } console.log(sum_with_lodash([1, 5, 3, 2])); // 11


## fib
1. 把程式碼變得更簡潔:把 (n==1) 和 (n==2) 的條件判斷寫在一起,修改過後如下:
```javascript
function fib(n) {
    // TODO: implement fibonacci
    if (n == 0) {
        return 0;
    } else if (n == 1 || n == 2) {
        return 1;
    } else {
        return fib(n - 1) + fib(n - 2);
    }
}
  1. 其他寫法: 用迴圈
    function fib_2(n) {
    let arr = [1, 1];
    if (n == 0) {
        return 0;
    }
    if (n == 1 || n == 2) {
        return 1;
    }
    for (let i = 3; i <= n; i++) {
        let tmp = arr[i - 3] + arr[i - 2];
        arr.push(tmp);
    }
    return arr[n - 1];
    }

    stack

  2. #items; 代表把 items 設為 private,沒辦法直接被外部 class 訪問 (老師不好意思我本來以為你是在問 //TODO 是甚麼意思><)
  3. // 檢查 stack 是否為空
    isEmpty() {
        // TODO
        return this.#items.length == 0;
    }
  4. 對,應該是 undefined 才是正確的