UNPKG

@nuintun/qrcode

Version:

A pure JavaScript QRCode encode and decode library.

76 lines (72 loc) 1.81 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 { ALPHANUMERIC_MAPPING } from '../../common/encoding/mapping.js'; /** * @module Alphanumeric */ function getAlphanumericCode(character) { const code = ALPHANUMERIC_MAPPING.get(character); if (code != null) { return code; } throw new Error(`illegal alphanumeric character: ${character}`); } class Alphanumeric { #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.ALPHANUMERIC; } /** * @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 = getAlphanumericCode(content[i]); if (i + 1 < length) { const code2 = getAlphanumericCode(content[i + 1]); // Encode two alphanumeric letters in 11 bits. bits.append(code1 * 45 + code2, 11); i += 2; } else { // Encode one alphanumeric letter in six bits. bits.append(code1, 6); i++; } } return bits; } } export { Alphanumeric };