1
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?

アクセスされたプロパティ名を記録し、配列として吐き出すオブジェクト

Posted at

実用性は置いといて、JavaScriptのProxyで、こんなことできるかなと思ってやってみたもの。

const recorder = new Proxy(() => [], {
  apply: function (target, _thisArg, args) {
    return [...target(), ...args];
  },
  get: function (target, prop) {
    return new Proxy(() => [...target(), prop], this);
  },
});

// アクセスしたプロパティを記録していき、関数として呼ぶと配列を吐く
console.log(
  recorder.hoge.fuga.piyo.hogehoge.hogefuga.hogepiyo.foo.bar.baz.foober.barbaz.foobarbaz[1][2][3]()
);

// ファイルパスを作るとか?
console.log({
  path: recorder['C:\\'].Users.Public.Downloads('somefile.txt').join('\\'),
});

// 丸サ進行
console.log({ chords: recorder.FMaj7.E7.Am7.Gm7.C7() });

動かしてみる

型をつける

  • 一応型をつけました。
    • もうちょっとスマートな書き方がありそうな気がします。
      • できればasを撲滅したい。
interface CallableProperty {
  (...args: string[]): string[];
  [key: string]: CallableProperty;
}

const recorder = new Proxy<CallableProperty>(
  ((...args: string[]) => args) as CallableProperty,
  {
    apply: function (target, _thisArg, args) {
      return [...target(), ...args];
    },
    get: function (target, prop) {
      return new Proxy(() => [...target(), prop], this);
    },
  }
);

終わりに

1
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
1
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?