UNPKG

@nuintun/qrcode

Version:

A pure JavaScript QRCode encode and decode library.

82 lines (78 loc) 2.03 kB
/** * @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 { NUMERIC_MAPPING } from '../../common/encoding/mapping.js'; /** * @module Numeric */ function getNumericCode(character) { const code = 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) { assertContent(content); this.#content = content; } /** * @property mode * @description The mode of the segment. */ get mode() { return 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(); 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; } } export { Numeric };