@nuintun/qrcode
Version:
A pure JavaScript QRCode encode and decode library.
79 lines (74 loc) • 2.07 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
*/
;
const Mode = require('../../common/Mode.cjs');
const BitArray = require('../../common/BitArray.cjs');
const asserts = require('../utils/asserts.cjs');
const mapping = require('../../common/encoding/mapping.cjs');
/**
* @module Kanji
*/
function getKanjiCode(character) {
const code = mapping.SHIFT_JIS_MAPPING.get(character);
return code != null ? code : NaN;
}
class Kanji {
#content;
/**
* @constructor
* @param content The content to encode.
*/
constructor(content) {
asserts.assertContent(content);
this.#content = content;
}
/**
* @property mode
* @description The mode of the segment.
*/
get mode() {
return Mode.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.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;
}
}
exports.Kanji = Kanji;