javascript lodashを使って実行する関数の引数を右から分割して利用する

javascript lodashを使って実行する関数の引数を右から分割して利用する

javascriptで、lodashを使って実行する関数の引数を右から分割して利用するサンプルコードを掲載してます。ブラウザはchromeを使用しています。

環境

  • OS windows10 pro 64bit
  • Apache 2.4.43
  • lodash 4.17.21
  • ブラウザ chrome 91.0.4472.77

lodash使用

こちらのサイトから最新版を確認して、CDN版を使用してます。

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>

関数の引数を右から分割して利用

関数の引数を右から分割して利用するには、「_.partialRight」を使用します。

'use strict';

function hoge(x, y) {
  return x + " と " + y;
}

const foo = _.partialRight(hoge, 'world');

console.log(
  foo('hello')
)
 
// 引数の順序を逆にする
const bar = _.partialRight(hoge, 'hello', _);

console.log(
  bar('world')
)

実行結果を確認すると、関数の引数が右から分割されて実行されていることが確認できます。

サンプルコード

以下は、
「実行」ボタンをクリックして、関数の引数を右から分割して実行してその結果を表示するサンプルコードとなります。

※cssには「tailwind」を使用して、アロー関数で関数は定義してます。

<!DOCTYPE html>
<html lang="ja">

<head>
  <meta charset="utf-8">
  <title>mebeeサンプル</title>
  <link href="https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css" rel="stylesheet">
  <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>
</head>

<script>

  const hoge = (x,y) => {

    bar.innerHTML = `${x} と ${y}を表示`

  }  

  const f = _.partial(hoge, 'hello');

  window.onload = () => {
    btn.onclick = () => { f("world") }
  }

</script>

<body>
  <div class="container mx-auto my-56 w-64 px-4">

    <div id="sample" class="flex flex-col justify-center">

      <h1 id="bar" class="font-semibold text-purple-700 text-lg mr-auto">実行結果</h1>     

      <button id="btn"
        class="mb-2 md:mb-0 bg-transparent hover:bg-green-300 text-green-700 font-semibold hover:text-white py-2 px-4 border border-green-300 hover:border-transparent rounded">
        実行
      </button>

    </div>

  </div>
</body>

</html>

実行結果を確認すると、引数が右から分割されて実行されたことが確認できます。