LoginSignup
2
2

More than 1 year has passed since last update.

文字列をShift-JISでエンコードしたい

Posted at

jsでテキストのエンコードデコードをしたいときに便利なのがTextEncoderとTextDecoderクラス
TextDecoderは文字コードを指定してUint8ArrayからStringにデコードできる
TextEncoderはStringからUint8Arrayにエンコードできるが文字コードはutf-8のみである
shift-jisでエンコードしたいときはその手のライブラリに頼るのが一般的
せっかくTextDecoderがあるのでなんとかしたいというお話

const
sjis=class{
	constructor(){
		this.e={};this.d={};
		((td=new TextDecoder('sjis'),f=w=>(_=>
			_.length==1&&_!=''&&(this.e[_]=w).reduce((a,x,i,{length:l})=>(i==l-1?a[x]=_:a[x]||(a[x]={})),this.d)
		)(td.decode(new Uint8Array(w))))=>[...Array(238)].forEach((_,i)=>
			i<191?f([i+(i<128?0:0xa1-128)]):[...Array(188)].forEach((_,j)=>f([i-191+(i-191<31?0x81:0xe0-31),j+0x40+(62<j)]))
		))();
		return this;
	}
	encode(w){return[...w].flatMap(x=>this.e[x]);}
	decode(w){return w.reduce((a,x)=>(x=a.x[x],x.length?(a.a+=x,a.x=this.d):a.x=x,a),{a:'',x:this.d}).a;}
};

this.e, this.dがそれぞれエンコードとデコード用のテーブル
constructorの中でshift-jisのTextDecoderを作成し
wikiを参考に全ての文字の位置をf()に渡してテーブルを作成している
テーブルの作成や参照にreduceを使っている

多分同じ手法で他の文字コードもエンコードできるようになる

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