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?

なまくらtypeof判定

Posted at

JavaScriptのtypeofによる型判定ではいちいち全文字比較するのが定番となっている。例えば

if(typeof a==="undefined");

などといった具合だ。しかしこれはかなり省略できる。

if((typeof a)[8]);

これで良い。型名に8文字目(0基点)が存在するのはundefinedだけなのだ。この調子で全ての型を網羅すると以下のようになる。

const a=[0,0n,!0,{},"",Symbol(0),Date][Math.random()*8|0];
if((typeof a)[8]);//undefined
if((typeof a)[0]=="f");//function
if((typeof a)[0]=="n");//number
if((typeof a)[0]=="o");//object
if((typeof a)[1]=="o");//boolean
if((typeof a)[1]=="i");//bigint
if((typeof a)[1]=="t");//string
if((typeof a)[1]=="y");//symbol

この方が高速だと思ったら大間違いである。へたすると遅い可能性すらある。それも環境次第。運次第。そしてあなたの気持ち次第。
さりげなく可読性のかけらも無い意味不明な処理に見えるが気のせいである。
まあそんな事はこの際どうでもいいので、もっとどうでもいい事を見せびらかしておこう。以下の表は全型名の0~8文字目を抜き出したものだ。下から縦に読むと型名になる。

8 d
7 en
6 non
5 iiatrtgl
4 ftenecno
3 eclibeib
2 dnogmjrm
1 nuoiubty
0 ufbbnoss

0~6文字目まで必ず共通文字が存在している。7文字目でようやく重複がなくなる。以下の表は行単位で整列して分かりやすくなっている。3文字目が特に仲良しだ(bbceeiil)。

8 d
7 en
6 nno
5 agiilrtt
4 ceefnnot
3 bbceeiil
2 dgjmmnor
1 binotuuy
0 bbfnossu

nが8個、beioが5個ずつ、tが4個、uが3個。その他1~2個ずつ。

どうでもいい召喚program
const t="bigint boolean function number object string symbol undefined".split` `;
for(let a=9;a--;){
	let b=[],c;
	for(c of t)b.push(c[a]);
	document.write(b.sort().join``,"<br>")
}
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?