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解答記録 #1 implement curry()

Last updated at Posted at 2020-08-27

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

Alt Text

第一問 #1 implement curry()

まずサンプルコードからinput/outputを決めていきます

const  join = (a, b, c) => {
   return `${a}_${b}_${c}`
}

const curriedJoin = curry(join)

curriedJoin(1, 2, 3) // '1_2_3'

curriedJoin(1)(2, 3) // '1_2_3'

curriedJoin(1, 2)(3) // '1_2_3'

上から見るとcurry()はfunctionを返し、しかも任意の数の引数を渡せることができ、function自体は以下のことをする:

  1. 引数足りるなら、joinを実行して結果を返す
  2. 引数足りなければ、新しいfunctionを返て、1を繰り返す

2番はすごく大事です。curriedJoin(1,2) で返すfunctionは、渡される引数の前に1と2をinsertする必要。これは``Function.prototype.bind()`を使えば行ける。

function curry(func) {
  return function curried(...args) {
    // 1. if enough args, call func 
    // 2. if not enough, bind the args and wait for new one
    if (args.length >= func.length) {
      return func.apply(this, args)
    } else {
      return curried.bind(this, ...args)
    }
  }
}

よし, 通った!

Alt Text

第一問は簡単で、興味あれば一緒に https://bfe.dev で練習していきましょう。

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?