@nuintun/qrcode
Version:
A pure JavaScript QRCode encode and decode library.
84 lines (79 loc) • 2.07 kB
JavaScript
/**
* @module QRCode
* @package @nuintun/qrcode
* @license MIT
* @version 5.0.3
* @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 Numeric
*/
function getNumericCode(character) {
const code = mapping.NUMERIC_MAPPING.get(character);
if (code != null) {
return code;
}
throw new Error(`illegal numeric character: ${character}`);
}
class Numeric {
#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.NUMERIC;
}
/**
* @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 = Array.from(this.#content);
const { length } = content;
for (let i = 0; i < length; ) {
const code1 = getNumericCode(content[i]);
if (i + 2 < length) {
// Encode three numeric letters in ten bits.
const code2 = getNumericCode(content[i + 1]);
const code3 = getNumericCode(content[i + 2]);
bits.append(code1 * 100 + code2 * 10 + code3, 10);
i += 3;
} else if (i + 1 < length) {
// Encode two numeric letters in seven bits.
const code2 = getNumericCode(content[i + 1]);
bits.append(code1 * 10 + code2, 7);
i += 2;
} else {
// Encode one numeric letter in four bits.
bits.append(code1, 4);
i++;
}
}
return bits;
}
}
exports.Numeric = Numeric;