8
2

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 5 years have passed since last update.

関数の実行ごとに名取の声が再生されるProxy

Last updated at Posted at 2018-07-29
yarn add natori.proxy
const 名取 = require('natori.proxy')

const sum = (a, b) => a + b
const 名取sum = 名取(sum, 'ってね')
// 各関数実行時に名取が再生される

console.log(名取sum(1, 2))
// => 3
// 「ってね」

console.log(名取sum(1, 2) + 名取sum(1, 2))
// => 6
// 「ってねを禁止されてね.禁止されってね...うははっ」, 「ってね」

名取プロキシでラップされた関数の実行ごとに名取の声が流れる。
名取(sum, 'エッチ')みたいに第2引数にキーワードが指定できる。

実装

内部で使っている名取の声を流すのはsana-voiceというライブラリ。

akameco/sana-voice: さなボタンからランダムに再生するCLI

これはPromiseで非同期なので、関数の実行ごとに合わせて実行すると、同時に実行されて音声がかぶってしまう。
ので、前の再生が終わったら次の音声を再生させたい。
こういうPromiseをキューで扱い場合はp-queueを使うと便利。

sindresorhus/p-queue: Promise queue with concurrency control

concurrencyにいくつ平行で実行するかを指定して、queue.addでPromiseを積んでいくだけでキューで実行される。

const queue = new PQueue({ concurrency: 1 })

// ...
  queue.add(() => sanaVoice(key))

ライブラリの全コード。キューの他はProxyを使うだけ。

'use strict'
const PQueue = require('p-queue')
const sanaVoice = require('sana-voice')

const queue = new PQueue({ concurrency: 1 })

module.exports = (func, key = 'てね') => {
  const handler = {
    apply(target, prop, args) {
      queue.add(() => sanaVoice(key))
      return Reflect.apply(target, prop, args)
    },
  }
  return new Proxy(func, handler)
}

よかったらスターしてください。
akameco/natori.proxy: proxy for 名取

関連

コマンドラインで名取さなを再生する - Qiita
Proxyを使って関数の呼び出し回数や全実行結果を取得する - Qiita
【JavaScript】うるせぇお前がGolangになるんだよ - Qiita
【Proxy】JavaScriptでRubyのtimesを使う - Qiita

8
2
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
8
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?