8
4

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】JavaScriptでRubyのtimesを使う

Last updated at Posted at 2018-06-27

どうやらRubyでは10.timesと書くと0~10で反復可能なコードが書けるそうです。
jsでもやってみます。

const hello5 = 5 . times.map(() => 'hello')
console.log(hello5)
// => [ 'hello', 'hello', 'hello', 'hello', 'hello' ]

const list = 6 . times.map(v => v * 2)
console.log(list)
// => [ 0, 2, 4, 6, 8, 10 ]

これはProxyを使えば簡単です。

const handler = {
  get(target, propKey, receiver) {
    if (propKey === 'times') {
      return [...Array(Number(receiver)).keys()]
    }
    return Reflect.get(target, propKey, receiver)
  }
}

const proxy = new Proxy(Object.prototype, handler)
Object.setPrototypeOf(Number.prototype, proxy)

Proxyについては以下の資料でも読めばいいと思いますが、一度動かせばなんとなくわかるので読まなくてもいいと思います。

もちろん配列のようにアクセスしても動きます。

for (let i of 10['times']) {
  console.log(i + 1)
}
// => 1
// => 2
// => 3
// => 4
// => 5
// => 6
// => 7
// => 8
// => 9
// => 10

キモいですね。

以下のコードをChrome Devtoolを開いて貼り付ければ動作確認できます。

const handler = {
  get(target, propKey, receiver) {
    if (propKey === 'times') {
      const first = Number(receiver)
      return [...Array(first).keys()]
    }
    return Reflect.get(target, propKey, receiver)
  }
}

const proxy = new Proxy(Object.prototype, handler)
Object.setPrototypeOf(Number.prototype, proxy)

const hello5 = 5 . times.map(() => 'hello')
console.log(hello5)

const list = 6 . times.map(v => v * 2)
console.log(list)

for (let i of 10['times']) {
  console.log(i + 1)
}

しかしまあObject.setPrototypeOfの乱用は避けた方が無難でしょう。

色々Proxyでキモいことをやってみると楽しいと思います。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?