@nuintun/qrcode
Version:
A pure JavaScript QRCode encode and decode library.
77 lines (73 loc) • 2.03 kB
JavaScript
/**
* @module QRCode
* @package @nuintun/qrcode
* @license MIT
* @version 5.0.2
* @author nuintun <nuintun@qq.com>
* @description A pure JavaScript QRCode encode and decode library.
* @see https://github.com/nuintun/qrcode#readme
*/
import { Mode } from '../../common/Mode.js';
import { BitArray } from '../../common/BitArray.js';
import { assertContent } from '../utils/asserts.js';
import { SHIFT_JIS_MAPPING } from '../../common/encoding/mapping.js';
/**
* @module Kanji
*/
function getKanjiCode(character) {
const code = SHIFT_JIS_MAPPING.get(character);
return code != null ? code : NaN;
}
class Kanji {
#content;
/**
* @constructor
* @param content The content to encode.
*/
constructor(content) {
assertContent(content);
this.#content = content;
}
/**
* @property mode
* @description The mode of the segment.
*/
get mode() {
return Mode.KANJI;
}
/**
* @property content
* @description The content of the segment.
*/
get content() {
return this.#content;
}
/**
* @method encode
* @description Encode the segment.
*/
encode() {
const bits = new BitArray();
const content = this.#content;
for (const character of content) {
let code = getKanjiCode(character);
// For characters with Shift JIS values from 0x8140 to 0x9ffc.
if (code >= 0x8140 && code <= 0x9ffc) {
// Subtract 0x8140 from Shift JIS value.
code -= 0x8140;
// For characters with Shift JIS values from 0xe040 to 0xebbf.
} else if (code >= 0xe040 && code <= 0xebbf) {
// Subtract 0xc140 from Shift JIS value.
code -= 0xc140;
} else {
throw new Error(`illegal kanji character: ${character}`);
}
// Multiply most significant byte of result by 0xc0 and add least significant byte to product.
code = (code >> 8) * 0xc0 + (code & 0xff);
// Convert result to a 13-bit binary string.
bits.append(code, 13);
}
return bits;
}
}
export { Kanji };