0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

BFE.dev解答記録 #23. sum()を実装する

Posted at

https://bfe.dev/ja はFrontEnd版のLeetCode、GAFAの面接を受けるなら練習した方がいいかなと。
以下は自分の練習記録です。

Alt Text

BFE.dev#23. sum()を実装するをみてみよう

問題

以下の条件を満たす前提でsum()を実装してください。

const sum1 = sum(1)
sum1(2) == 3 // true
sum1(3) == 4 // true
sum(1)(2)(3) == 6 // true
sum(5)(-1)(2) == 6 

分析

上記の用件からわかること

  1. sum() は引数を受けるfunctionを返す
  2. sum() では渡した引数を全部足して、1を繰り返す
  3. type coercionで、function == numberは可能。valueOftoStringを実装する必要

Let's code

まずfunctionを返す部分を作りましょう。引数の和を一時的に保存するために、2番目の引数にしたらいい。

function sum(num, currentSum = 0) {
  const newCurrentSum = num + currentSum
  
  const func = function(arg) {
    return sum(arg, num + currentSum)
  }

  return func
}

最後にvalueOfを入れれば完成

function sum(num, currentSum = 0) {
  const newCurrentSum = num + currentSum
  
  const func = function(arg) {
    return sum(arg, num + currentSum)
  }
  
  func.valueOf = () => newCurrentSum
  // below also works
  // func.toString = () => newCurrentSum.toString()
  
  return func
}

通った!

Alt Text

もし興味あれば、 BFE.devでやってみましょう https://bigfrontend.dev/ja/problem/create-a-sum

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?