@nuintun/qrcode
Version:
A pure JavaScript QRCode encode and decode library.
78 lines (74 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 { GB2312_MAPPING } from '../../common/encoding/mapping.js';
/**
* @module Hanzi
*/
function getHanziCode(character) {
const code = GB2312_MAPPING.get(character);
return code != null ? code : NaN;
}
class Hanzi {
#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.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();
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;
}
}
export { Hanzi };