@nuintun/qrcode
Version:
A pure JavaScript QRCode encode and decode library.
80 lines (75 loc) • 2.08 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 Hanzi
*/
function getHanziCode(character) {
const code = mapping.GB2312_MAPPING.get(character);
return code != null ? code : NaN;
}
class Hanzi {
#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.HANZI;
}
/**
* @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;
// GB/T 18284-2000.
for (const character of content) {
let code = getHanziCode(character);
// For characters with GB2312 values from 0xa1a1 to 0xaafe.
if (code >= 0xa1a1 && code <= 0xaafe) {
// Subtract 0xa1a1 from GB2312 value.
code -= 0xa1a1;
// For characters with GB2312 values from 0xb0a1 to 0xfafe.
} else if (code >= 0xb0a1 && code <= 0xfafe) {
// Subtract 0xa6a1 from GB2312 value.
code -= 0xa6a1;
} else {
throw new Error(`illegal hanzi character: ${character}`);
}
// Multiply most significant byte of result by 0x60 and add least significant byte to product.
code = (code >> 8) * 0x60 + (code & 0xff);
// Convert result to a 13-bit binary string.
bits.append(code, 13);
}
return bits;
}
}
exports.Hanzi = Hanzi;