Use const/let instead of var

This commit is contained in:
Linus Unnebäck 2020-04-16 22:50:11 +01:00
parent a5a8563ba4
commit 9cc0e3b78d
No known key found for this signature in database
GPG key ID: CE70CEAE9C0FA66F
71 changed files with 772 additions and 772 deletions

View file

@ -1,4 +1,4 @@
var QRCode = require('../lib')
const QRCode = require('../lib')
QRCode.toString('yo yo yo', function (error, data) {
if (error) {

View file

@ -1,12 +1,12 @@
var express = require('express')
var app = express()// .createServer()
var http = require('http')
var fs = require('fs')
var QRCode = require('../lib')
var canvasutil = require('canvasutil')
var { createCanvas, loadImage } = require('canvas')
const express = require('express')
const app = express()// .createServer()
const http = require('http')
const fs = require('fs')
const QRCode = require('../lib')
const canvasutil = require('canvasutil')
const { createCanvas, loadImage } = require('canvas')
var path = require('path')
const path = require('path')
// app.use(express.methodOverride())
// app.use(express.bodyParser())
@ -29,12 +29,12 @@ app.get('/', function (req, res) {
})
})
var effectHandlers = {}
const effectHandlers = {}
app.get('/generate', function (req, res) {
var q = req.query || {}
const q = req.query || {}
var effect = q.effect || 'plain'
let effect = q.effect || 'plain'
if (!effectHandlers[effect]) {
effect = 'plain'
}
@ -48,7 +48,7 @@ app.get('/generate', function (req, res) {
}
})
} else {
var msg = error.message + '\n' + error.stack
const msg = error.message + '\n' + error.stack
res.header('Content-Type', 'text/plain')
res.send(msg)
console.error(msg)
@ -72,28 +72,28 @@ effectHandlers.bacon = function (args, cb) {
}
effectHandlers.rounded = function (args, cb) {
var canvas = createCanvas(200, 200)
const canvas = createCanvas(200, 200)
QRCode.toCanvas(canvas, args.text || '', function (err) {
if (err) {
cb(err, canvas)
return
}
var tpx = new canvasutil.PixelCore()
var luma709Only = canvasutil.conversionLib.luma709Only
var up = []
var down = []
var left = []
var right = []
var upPx
var downPx
var leftPx
var rightPx
var r
var t
var l
var d
var corner = 0
const tpx = new canvasutil.PixelCore()
const luma709Only = canvasutil.conversionLib.luma709Only
const up = []
const down = []
const left = []
const right = []
let upPx
let downPx
let leftPx
let rightPx
let r
let t
let l
let d
let corner = 0
tpx.threshold = 100
@ -166,16 +166,16 @@ effectHandlers.rounded = function (args, cb) {
}
effectHandlers.remoteImage = function (args, cb) {
var src = args.src
var domain
var uri
let src = args.src
let domain
let uri
if (!src) {
cb(new Error('src required'), null)
} else {
if (src.indexof('://') !== -1) {
src = src.split('://').unshift()
var parts = src.split('/')
const parts = src.split('/')
domain = parts.shift()
uri = parts.join('/')
@ -187,14 +187,14 @@ effectHandlers.remoteImage = function (args, cb) {
return
}
var options = {
const options = {
host: domain,
port: 80,
path: uri,
method: 'GET'
}
var req = http.request(options, function (res) {
const req = http.request(options, function (res) {
if (res.statusCode < 200 || res.statusCode > 299) {
cb(new Error('http ' + res.statusCode + ' response code'), null)
return
@ -202,7 +202,7 @@ effectHandlers.remoteImage = function (args, cb) {
res.setEncoding('utf8')
var data = ''
let data = ''
res.on('data', function (chunk) {
data += chunk
console.log('BODY: ' + chunk)
@ -223,27 +223,27 @@ effectHandlers.remoteImage = function (args, cb) {
effectHandlers.image = function (args, cb) {
loadImage(args.src || '').then((img) => {
var convert = canvasutil.conversionLib
var canvas = createCanvas(200, 200)
const convert = canvasutil.conversionLib
const canvas = createCanvas(200, 200)
QRCode.toCanvas(canvas, args.text || '', function (err) {
if (err) {
cb(err, false)
return
}
var codeCtx = canvas.getContext('2d')
var frame = codeCtx.getImageData(0, 0, canvas.width, canvas.width)
var tpx = new canvasutil.PixelCore()
var baconCanvas = createCanvas(canvas.width, canvas.width)
var ctx = baconCanvas.getContext('2d')
var topThreshold = args.darkThreshold || 25
var bottomThreshold = args.lightThreshold || 75
const codeCtx = canvas.getContext('2d')
const frame = codeCtx.getImageData(0, 0, canvas.width, canvas.width)
const tpx = new canvasutil.PixelCore()
const baconCanvas = createCanvas(canvas.width, canvas.width)
const ctx = baconCanvas.getContext('2d')
const topThreshold = args.darkThreshold || 25
const bottomThreshold = args.lightThreshold || 75
tpx.threshold = 50
// scale image
var w = canvas.width
var h = canvas.height
let w = canvas.width
let h = canvas.height
if (img.width > img.height) {
w = w * (canvas.height / h)
@ -256,10 +256,10 @@ effectHandlers.image = function (args, cb) {
try {
tpx.iterate(baconCanvas, function (px, i, l, pixels, w, h, pixelCore) {
var luma = (0.2125 * px.r + 0.7154 * px.g + 0.0721 * px.b)
var codeLuma = convert.luma709Only(frame.data[i * 4], frame.data[i * 4 + 1], frame.data[i * 4 + 2])
var yuv
var rgb
const luma = (0.2125 * px.r + 0.7154 * px.g + 0.0721 * px.b)
const codeLuma = convert.luma709Only(frame.data[i * 4], frame.data[i * 4 + 1], frame.data[i * 4 + 2])
let yuv
let rgb
if (codeLuma > pixelCore.threshold) {
if (luma < bottomThreshold) {
@ -296,8 +296,8 @@ effectHandlers.image = function (args, cb) {
}
effectHandlers.plain = function (args, cb) {
var canvas = createCanvas(200, 200)
var text = args.text || ''
const canvas = createCanvas(200, 200)
const text = args.text || ''
QRCode.toCanvas(canvas, text || '', function (err) {
cb(err, canvas)
})

View file

@ -1,6 +1,6 @@
var QRCode = require('../lib')
const QRCode = require('../lib')
var path = './tmp.png'
const path = './tmp.png'
QRCode.toFile(path, 'life of the party bros', {
color: {
dark: '#00F', // Blue modules

View file

@ -1,10 +1,10 @@
var QRCode = require('../lib')
var http = require('http')
const QRCode = require('../lib')
const http = require('http')
function testQRCode (req, res) {
res.writeHead(200, { 'Content-Type': 'text/html' })
var jungleBook = "The moonlight was blocked out of the mouth of the cave, for Shere Khan's\n" +
const jungleBook = "The moonlight was blocked out of the mouth of the cave, for Shere Khan's\n" +
'great square head and shoulders were thrust into the entrance. Tabaqui,\n' +
'behind him, was squeaking: "My lord, my lord, it went in here!"\n' +
'\n' +

View file

@ -1,4 +1,4 @@
var SJIS_UTF8 = [
const SJIS_UTF8 = [
[0x8140, ' 、。,.・:;?!゛゜´`¨^ ̄_ヽヾゝゞ〃仝々〆〇ー―‐/\~∥|…‥‘’“”()〔〕[]{}〈〉《》「」『』【】+-±×'],
[0x8180, '÷=≠<>'],
[0x818f, '¥$¢£%#&*@§☆★'],
@ -89,10 +89,10 @@ var SJIS_UTF8 = [
module.exports = function toSJIS (utf8Char) {
if (!utf8Char || utf8Char === '') return
for (var i = 0; i < SJIS_UTF8.length; i++) {
var kanji = SJIS_UTF8[i][1]
for (let i = 0; i < SJIS_UTF8.length; i++) {
const kanji = SJIS_UTF8[i][1]
var posIndex = kanji.indexOf(utf8Char)
const posIndex = kanji.indexOf(utf8Char)
if (posIndex >= 0) {
return SJIS_UTF8[i][0] + posIndex
}

View file

@ -1,14 +1,14 @@
var canPromise = require('./can-promise')
const canPromise = require('./can-promise')
var QRCode = require('./core/qrcode')
var CanvasRenderer = require('./renderer/canvas')
var SvgRenderer = require('./renderer/svg-tag.js')
const QRCode = require('./core/qrcode')
const CanvasRenderer = require('./renderer/canvas')
const SvgRenderer = require('./renderer/svg-tag.js')
function renderCanvas (renderFunc, canvas, text, opts, cb) {
var args = [].slice.call(arguments, 1)
var argsNum = args.length
var isLastArgCb = typeof args[argsNum - 1] === 'function'
const args = [].slice.call(arguments, 1)
const argsNum = args.length
const isLastArgCb = typeof args[argsNum - 1] === 'function'
if (!isLastArgCb && !canPromise()) {
throw new Error('Callback required as last argument')
@ -50,7 +50,7 @@ function renderCanvas (renderFunc, canvas, text, opts, cb) {
return new Promise(function (resolve, reject) {
try {
var data = QRCode.create(text, opts)
const data = QRCode.create(text, opts)
resolve(renderFunc(data, canvas, opts))
} catch (e) {
reject(e)
@ -59,7 +59,7 @@ function renderCanvas (renderFunc, canvas, text, opts, cb) {
}
try {
var data = QRCode.create(text, opts)
const data = QRCode.create(text, opts)
cb(null, renderFunc(data, canvas, opts))
} catch (e) {
cb(e)

View file

@ -8,7 +8,7 @@
* and their number depends on the symbol version.
*/
var getSymbolSize = require('./utils').getSymbolSize
const getSymbolSize = require('./utils').getSymbolSize
/**
* Calculate the row/column coordinates of the center module of each alignment pattern
@ -27,12 +27,12 @@ var getSymbolSize = require('./utils').getSymbolSize
exports.getRowColCoords = function getRowColCoords (version) {
if (version === 1) return []
var posCount = Math.floor(version / 7) + 2
var size = getSymbolSize(version)
var intervals = size === 145 ? 26 : Math.ceil((size - 13) / (2 * posCount - 2)) * 2
var positions = [size - 7] // Last coord is always (size - 7)
const posCount = Math.floor(version / 7) + 2
const size = getSymbolSize(version)
const intervals = size === 145 ? 26 : Math.ceil((size - 13) / (2 * posCount - 2)) * 2
const positions = [size - 7] // Last coord is always (size - 7)
for (var i = 1; i < posCount - 1; i++) {
for (let i = 1; i < posCount - 1; i++) {
positions[i] = positions[i - 1] - intervals
}
@ -55,19 +55,19 @@ exports.getRowColCoords = function getRowColCoords (version) {
* Note that the coordinates (6,6), (6,38), (38,6) are occupied by finder patterns
* and are not therefore used for alignment patterns.
*
* var pos = getPositions(7)
* let pos = getPositions(7)
* // [[6,22], [22,6], [22,22], [22,38], [38,22], [38,38]]
*
* @param {Number} version QR Code version
* @return {Array} Array of coordinates
*/
exports.getPositions = function getPositions (version) {
var coords = []
var pos = exports.getRowColCoords(version)
var posLength = pos.length
const coords = []
const pos = exports.getRowColCoords(version)
const posLength = pos.length
for (var i = 0; i < posLength; i++) {
for (var j = 0; j < posLength; j++) {
for (let i = 0; i < posLength; i++) {
for (let j = 0; j < posLength; j++) {
// Skip if position is occupied by finder patterns
if ((i === 0 && j === 0) || // top-left
(i === 0 && j === posLength - 1) || // bottom-left

View file

@ -1,4 +1,4 @@
var Mode = require('./mode')
const Mode = require('./mode')
/**
* Array of characters available in alphanumeric mode
@ -9,7 +9,7 @@ var Mode = require('./mode')
*
* @type {Array}
*/
var ALPHA_NUM_CHARS = [
const ALPHA_NUM_CHARS = [
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
@ -34,13 +34,13 @@ AlphanumericData.prototype.getBitsLength = function getBitsLength () {
}
AlphanumericData.prototype.write = function write (bitBuffer) {
var i
let i
// Input data characters are divided into groups of two characters
// and encoded as 11-bit binary codes.
for (i = 0; i + 2 <= this.data.length; i += 2) {
// The character value of the first character is multiplied by 45
var value = ALPHA_NUM_CHARS.indexOf(this.data[i]) * 45
let value = ALPHA_NUM_CHARS.indexOf(this.data[i]) * 45
// The character value of the second digit is added to the product
value += ALPHA_NUM_CHARS.indexOf(this.data[i + 1])

View file

@ -6,12 +6,12 @@ function BitBuffer () {
BitBuffer.prototype = {
get: function (index) {
var bufIndex = Math.floor(index / 8)
const bufIndex = Math.floor(index / 8)
return ((this.buffer[bufIndex] >>> (7 - index % 8)) & 1) === 1
},
put: function (num, length) {
for (var i = 0; i < length; i++) {
for (let i = 0; i < length; i++) {
this.putBit(((num >>> (length - i - 1)) & 1) === 1)
}
},
@ -21,7 +21,7 @@ BitBuffer.prototype = {
},
putBit: function (bit) {
var bufIndex = Math.floor(this.length / 8)
const bufIndex = Math.floor(this.length / 8)
if (this.buffer.length <= bufIndex) {
this.buffer.push(0)
}

View file

@ -23,7 +23,7 @@ function BitMatrix (size) {
* @param {Boolean} reserved
*/
BitMatrix.prototype.set = function (row, col, value, reserved) {
var index = row * this.size + col
const index = row * this.size + col
this.data[index] = value
if (reserved) this.reservedBit[index] = true
}

View file

@ -1,5 +1,5 @@
var encodeUtf8 = require('encode-utf8')
var Mode = require('./mode')
const encodeUtf8 = require('encode-utf8')
const Mode = require('./mode')
function ByteData (data) {
this.mode = Mode.BYTE
@ -19,7 +19,7 @@ ByteData.prototype.getBitsLength = function getBitsLength () {
}
ByteData.prototype.write = function (bitBuffer) {
for (var i = 0, l = this.data.length; i < l; i++) {
for (let i = 0, l = this.data.length; i < l; i++) {
bitBuffer.put(this.data[i], 8)
}
}

View file

@ -1,6 +1,6 @@
var ECLevel = require('./error-correction-level')
const ECLevel = require('./error-correction-level')
var EC_BLOCKS_TABLE = [
const EC_BLOCKS_TABLE = [
// L M Q H
1, 1, 1, 1,
1, 1, 1, 1,
@ -44,7 +44,7 @@ var EC_BLOCKS_TABLE = [
25, 49, 68, 81
]
var EC_CODEWORDS_TABLE = [
const EC_CODEWORDS_TABLE = [
// L M Q H
7, 10, 13, 17,
10, 16, 22, 28,

View file

@ -8,7 +8,7 @@ function fromString (string) {
throw new Error('Param is not a string')
}
var lcStr = string.toLowerCase()
const lcStr = string.toLowerCase()
switch (lcStr) {
case 'l':

View file

@ -1,5 +1,5 @@
var getSymbolSize = require('./utils').getSymbolSize
var FINDER_PATTERN_SIZE = 7
const getSymbolSize = require('./utils').getSymbolSize
const FINDER_PATTERN_SIZE = 7
/**
* Returns an array containing the positions of each finder pattern.
@ -9,7 +9,7 @@ var FINDER_PATTERN_SIZE = 7
* @return {Array} Array of coordinates
*/
exports.getPositions = function getPositions (version) {
var size = getSymbolSize(version)
const size = getSymbolSize(version)
return [
// top-left

View file

@ -1,8 +1,8 @@
var Utils = require('./utils')
const Utils = require('./utils')
var G15 = (1 << 10) | (1 << 8) | (1 << 5) | (1 << 4) | (1 << 2) | (1 << 1) | (1 << 0)
var G15_MASK = (1 << 14) | (1 << 12) | (1 << 10) | (1 << 4) | (1 << 1)
var G15_BCH = Utils.getBCHDigit(G15)
const G15 = (1 << 10) | (1 << 8) | (1 << 5) | (1 << 4) | (1 << 2) | (1 << 1) | (1 << 0)
const G15_MASK = (1 << 14) | (1 << 12) | (1 << 10) | (1 << 4) | (1 << 1)
const G15_BCH = Utils.getBCHDigit(G15)
/**
* Returns format information with relative error correction bits
@ -15,8 +15,8 @@ var G15_BCH = Utils.getBCHDigit(G15)
* @return {Number} Encoded format information bits
*/
exports.getEncodedBits = function getEncodedBits (errorCorrectionLevel, mask) {
var data = ((errorCorrectionLevel.bit << 3) | mask)
var d = data << 10
const data = ((errorCorrectionLevel.bit << 3) | mask)
let d = data << 10
while (Utils.getBCHDigit(d) - G15_BCH >= 0) {
d ^= (G15 << (Utils.getBCHDigit(d) - G15_BCH))

View file

@ -1,5 +1,5 @@
var EXP_TABLE = new Uint8Array(512)
var LOG_TABLE = new Uint8Array(256)
const EXP_TABLE = new Uint8Array(512)
const LOG_TABLE = new Uint8Array(256)
/**
* Precompute the log and anti-log tables for faster computation later
*
@ -9,8 +9,8 @@ var LOG_TABLE = new Uint8Array(256)
* ref {@link https://en.wikiversity.org/wiki/Reed%E2%80%93Solomon_codes_for_coders#Introduction_to_mathematical_fields}
*/
;(function initTables () {
var x = 1
for (var i = 0; i < 255; i++) {
let x = 1
for (let i = 0; i < 255; i++) {
EXP_TABLE[i] = x
LOG_TABLE[x] = i
@ -27,7 +27,7 @@ var LOG_TABLE = new Uint8Array(256)
// stay inside the bounds (because we will mainly use this table for the multiplication of
// two GF numbers, no more).
// @see {@link mul}
for (i = 255; i < 512; i++) {
for (let i = 255; i < 512; i++) {
EXP_TABLE[i] = EXP_TABLE[i - 255]
}
}())

View file

@ -1,5 +1,5 @@
var Mode = require('./mode')
var Utils = require('./utils')
const Mode = require('./mode')
const Utils = require('./utils')
function KanjiData (data) {
this.mode = Mode.KANJI
@ -19,13 +19,13 @@ KanjiData.prototype.getBitsLength = function getBitsLength () {
}
KanjiData.prototype.write = function (bitBuffer) {
var i
let i
// In the Shift JIS system, Kanji characters are represented by a two byte combination.
// These byte values are shifted from the JIS X 0208 values.
// JIS X 0208 gives details of the shift coded representation.
for (i = 0; i < this.data.length; i++) {
var value = Utils.toSJIS(this.data[i])
let value = Utils.toSJIS(this.data[i])
// For characters with Shift JIS values from 0x8140 to 0x9FFC:
if (value >= 0x8140 && value <= 0x9FFC) {

View file

@ -17,7 +17,7 @@ exports.Patterns = {
* Weighted penalty scores for the undesirable features
* @type {Object}
*/
var PenaltyScores = {
const PenaltyScores = {
N1: 3,
N2: 3,
N3: 40,
@ -53,19 +53,19 @@ exports.from = function from (value) {
* i is the amount by which the number of adjacent modules of the same color exceeds 5
*/
exports.getPenaltyN1 = function getPenaltyN1 (data) {
var size = data.size
var points = 0
var sameCountCol = 0
var sameCountRow = 0
var lastCol = null
var lastRow = null
const size = data.size
let points = 0
let sameCountCol = 0
let sameCountRow = 0
let lastCol = null
let lastRow = null
for (var row = 0; row < size; row++) {
for (let row = 0; row < size; row++) {
sameCountCol = sameCountRow = 0
lastCol = lastRow = null
for (var col = 0; col < size; col++) {
var module = data.get(row, col)
for (let col = 0; col < size; col++) {
let module = data.get(row, col)
if (module === lastCol) {
sameCountCol++
} else {
@ -97,12 +97,12 @@ exports.getPenaltyN1 = function getPenaltyN1 (data) {
* Points: N2 * (m - 1) * (n - 1)
*/
exports.getPenaltyN2 = function getPenaltyN2 (data) {
var size = data.size
var points = 0
const size = data.size
let points = 0
for (var row = 0; row < size - 1; row++) {
for (var col = 0; col < size - 1; col++) {
var last = data.get(row, col) +
for (let row = 0; row < size - 1; row++) {
for (let col = 0; col < size - 1; col++) {
const last = data.get(row, col) +
data.get(row, col + 1) +
data.get(row + 1, col) +
data.get(row + 1, col + 1)
@ -121,14 +121,14 @@ exports.getPenaltyN2 = function getPenaltyN2 (data) {
* Points: N3 * number of pattern found
*/
exports.getPenaltyN3 = function getPenaltyN3 (data) {
var size = data.size
var points = 0
var bitsCol = 0
var bitsRow = 0
const size = data.size
let points = 0
let bitsCol = 0
let bitsRow = 0
for (var row = 0; row < size; row++) {
for (let row = 0; row < size; row++) {
bitsCol = bitsRow = 0
for (var col = 0; col < size; col++) {
for (let col = 0; col < size; col++) {
bitsCol = ((bitsCol << 1) & 0x7FF) | data.get(row, col)
if (col >= 10 && (bitsCol === 0x5D0 || bitsCol === 0x05D)) points++
@ -149,12 +149,12 @@ exports.getPenaltyN3 = function getPenaltyN3 (data) {
* in the symbol from 50% in steps of 5%
*/
exports.getPenaltyN4 = function getPenaltyN4 (data) {
var darkCount = 0
var modulesCount = data.data.length
let darkCount = 0
const modulesCount = data.data.length
for (var i = 0; i < modulesCount; i++) darkCount += data.data[i]
for (let i = 0; i < modulesCount; i++) darkCount += data.data[i]
var k = Math.abs(Math.ceil((darkCount * 100 / modulesCount) / 5) - 10)
const k = Math.abs(Math.ceil((darkCount * 100 / modulesCount) / 5) - 10)
return k * PenaltyScores.N4
}
@ -189,10 +189,10 @@ function getMaskAt (maskPattern, i, j) {
* @param {BitMatrix} data BitMatrix data
*/
exports.applyMask = function applyMask (pattern, data) {
var size = data.size
const size = data.size
for (var col = 0; col < size; col++) {
for (var row = 0; row < size; row++) {
for (let col = 0; col < size; col++) {
for (let row = 0; row < size; row++) {
if (data.isReserved(row, col)) continue
data.xor(row, col, getMaskAt(pattern, row, col))
}
@ -206,16 +206,16 @@ exports.applyMask = function applyMask (pattern, data) {
* @return {Number} Mask pattern reference number
*/
exports.getBestMask = function getBestMask (data, setupFormatFunc) {
var numPatterns = Object.keys(exports.Patterns).length
var bestPattern = 0
var lowerPenalty = Infinity
const numPatterns = Object.keys(exports.Patterns).length
let bestPattern = 0
let lowerPenalty = Infinity
for (var p = 0; p < numPatterns; p++) {
for (let p = 0; p < numPatterns; p++) {
setupFormatFunc(p)
exports.applyMask(p, data)
// Calculate penalty
var penalty =
const penalty =
exports.getPenaltyN1(data) +
exports.getPenaltyN2(data) +
exports.getPenaltyN3(data) +

View file

@ -1,5 +1,5 @@
var VersionCheck = require('./version-check')
var Regex = require('./regex')
const VersionCheck = require('./version-check')
const Regex = require('./regex')
/**
* Numeric mode encodes data from the decimal digit set (0 - 9)
@ -130,7 +130,7 @@ function fromString (string) {
throw new Error('Param is not a string')
}
var lcStr = string.toLowerCase()
const lcStr = string.toLowerCase()
switch (lcStr) {
case 'numeric':

View file

@ -1,4 +1,4 @@
var Mode = require('./mode')
const Mode = require('./mode')
function NumericData (data) {
this.mode = Mode.NUMERIC
@ -18,7 +18,7 @@ NumericData.prototype.getBitsLength = function getBitsLength () {
}
NumericData.prototype.write = function write (bitBuffer) {
var i, group, value
let i, group, value
// The input data string is divided into groups of three digits,
// and each group is converted to its 10-bit binary equivalent.
@ -31,7 +31,7 @@ NumericData.prototype.write = function write (bitBuffer) {
// If the number of input digits is not an exact multiple of three,
// the final one or two digits are converted to 4 or 7 bits respectively.
var remainingNum = this.data.length - i
const remainingNum = this.data.length - i
if (remainingNum > 0) {
group = this.data.substr(i)
value = parseInt(group, 10)

View file

@ -1,4 +1,4 @@
var GF = require('./galois-field')
const GF = require('./galois-field')
/**
* Multiplies two polynomials inside Galois Field
@ -8,10 +8,10 @@ var GF = require('./galois-field')
* @return {Uint8Array} Product of p1 and p2
*/
exports.mul = function mul (p1, p2) {
var coeff = new Uint8Array(p1.length + p2.length - 1)
const coeff = new Uint8Array(p1.length + p2.length - 1)
for (var i = 0; i < p1.length; i++) {
for (var j = 0; j < p2.length; j++) {
for (let i = 0; i < p1.length; i++) {
for (let j = 0; j < p2.length; j++) {
coeff[i + j] ^= GF.mul(p1[i], p2[j])
}
}
@ -27,17 +27,17 @@ exports.mul = function mul (p1, p2) {
* @return {Uint8Array} Remainder
*/
exports.mod = function mod (divident, divisor) {
var result = new Uint8Array(divident)
let result = new Uint8Array(divident)
while ((result.length - divisor.length) >= 0) {
var coeff = result[0]
const coeff = result[0]
for (var i = 0; i < divisor.length; i++) {
for (let i = 0; i < divisor.length; i++) {
result[i] ^= GF.mul(divisor[i], coeff)
}
// remove all zeros from buffer head
var offset = 0
let offset = 0
while (offset < result.length && result[offset] === 0) offset++
result = result.slice(offset)
}
@ -53,8 +53,8 @@ exports.mod = function mod (divident, divisor) {
* @return {Uint8Array} Buffer containing polynomial coefficients
*/
exports.generateECPolynomial = function generateECPolynomial (degree) {
var poly = new Uint8Array([1])
for (var i = 0; i < degree; i++) {
let poly = new Uint8Array([1])
for (let i = 0; i < degree; i++) {
poly = exports.mul(poly, new Uint8Array([1, GF.exp(i)]))
}

View file

@ -1,17 +1,17 @@
var Utils = require('./utils')
var ECLevel = require('./error-correction-level')
var BitBuffer = require('./bit-buffer')
var BitMatrix = require('./bit-matrix')
var AlignmentPattern = require('./alignment-pattern')
var FinderPattern = require('./finder-pattern')
var MaskPattern = require('./mask-pattern')
var ECCode = require('./error-correction-code')
var ReedSolomonEncoder = require('./reed-solomon-encoder')
var Version = require('./version')
var FormatInfo = require('./format-info')
var Mode = require('./mode')
var Segments = require('./segments')
var isArray = require('isarray')
const Utils = require('./utils')
const ECLevel = require('./error-correction-level')
const BitBuffer = require('./bit-buffer')
const BitMatrix = require('./bit-matrix')
const AlignmentPattern = require('./alignment-pattern')
const FinderPattern = require('./finder-pattern')
const MaskPattern = require('./mask-pattern')
const ECCode = require('./error-correction-code')
const ReedSolomonEncoder = require('./reed-solomon-encoder')
const Version = require('./version')
const FormatInfo = require('./format-info')
const Mode = require('./mode')
const Segments = require('./segments')
const isArray = require('isarray')
/**
* QRCode for JavaScript
@ -46,17 +46,17 @@ var isArray = require('isarray')
* @param {Number} version QR Code version
*/
function setupFinderPattern (matrix, version) {
var size = matrix.size
var pos = FinderPattern.getPositions(version)
const size = matrix.size
const pos = FinderPattern.getPositions(version)
for (var i = 0; i < pos.length; i++) {
var row = pos[i][0]
var col = pos[i][1]
for (let i = 0; i < pos.length; i++) {
const row = pos[i][0]
const col = pos[i][1]
for (var r = -1; r <= 7; r++) {
for (let r = -1; r <= 7; r++) {
if (row + r <= -1 || size <= row + r) continue
for (var c = -1; c <= 7; c++) {
for (let c = -1; c <= 7; c++) {
if (col + c <= -1 || size <= col + c) continue
if ((r >= 0 && r <= 6 && (c === 0 || c === 6)) ||
@ -79,10 +79,10 @@ function setupFinderPattern (matrix, version) {
* @param {BitMatrix} matrix Modules matrix
*/
function setupTimingPattern (matrix) {
var size = matrix.size
const size = matrix.size
for (var r = 8; r < size - 8; r++) {
var value = r % 2 === 0
for (let r = 8; r < size - 8; r++) {
const value = r % 2 === 0
matrix.set(r, 6, value, true)
matrix.set(6, r, value, true)
}
@ -97,14 +97,14 @@ function setupTimingPattern (matrix) {
* @param {Number} version QR Code version
*/
function setupAlignmentPattern (matrix, version) {
var pos = AlignmentPattern.getPositions(version)
const pos = AlignmentPattern.getPositions(version)
for (var i = 0; i < pos.length; i++) {
var row = pos[i][0]
var col = pos[i][1]
for (let i = 0; i < pos.length; i++) {
const row = pos[i][0]
const col = pos[i][1]
for (var r = -2; r <= 2; r++) {
for (var c = -2; c <= 2; c++) {
for (let r = -2; r <= 2; r++) {
for (let c = -2; c <= 2; c++) {
if (r === -2 || r === 2 || c === -2 || c === 2 ||
(r === 0 && c === 0)) {
matrix.set(row + r, col + c, true, true)
@ -123,11 +123,11 @@ function setupAlignmentPattern (matrix, version) {
* @param {Number} version QR Code version
*/
function setupVersionInfo (matrix, version) {
var size = matrix.size
var bits = Version.getEncodedBits(version)
var row, col, mod
const size = matrix.size
const bits = Version.getEncodedBits(version)
let row, col, mod
for (var i = 0; i < 18; i++) {
for (let i = 0; i < 18; i++) {
row = Math.floor(i / 3)
col = i % 3 + size - 8 - 3
mod = ((bits >> i) & 1) === 1
@ -145,9 +145,9 @@ function setupVersionInfo (matrix, version) {
* @param {Number} maskPattern Mask pattern reference value
*/
function setupFormatInfo (matrix, errorCorrectionLevel, maskPattern) {
var size = matrix.size
var bits = FormatInfo.getEncodedBits(errorCorrectionLevel, maskPattern)
var i, mod
const size = matrix.size
const bits = FormatInfo.getEncodedBits(errorCorrectionLevel, maskPattern)
let i, mod
for (i = 0; i < 15; i++) {
mod = ((bits >> i) & 1) === 1
@ -182,19 +182,19 @@ function setupFormatInfo (matrix, errorCorrectionLevel, maskPattern) {
* @param {Uint8Array} data Data codewords
*/
function setupData (matrix, data) {
var size = matrix.size
var inc = -1
var row = size - 1
var bitIndex = 7
var byteIndex = 0
const size = matrix.size
let inc = -1
let row = size - 1
let bitIndex = 7
let byteIndex = 0
for (var col = size - 1; col > 0; col -= 2) {
for (let col = size - 1; col > 0; col -= 2) {
if (col === 6) col--
while (true) {
for (var c = 0; c < 2; c++) {
for (let c = 0; c < 2; c++) {
if (!matrix.isReserved(row, col - c)) {
var dark = false
let dark = false
if (byteIndex < data.length) {
dark = (((data[byteIndex] >>> bitIndex) & 1) === 1)
@ -231,7 +231,7 @@ function setupData (matrix, data) {
*/
function createData (version, errorCorrectionLevel, segments) {
// Prepare data buffer
var buffer = new BitBuffer()
const buffer = new BitBuffer()
segments.forEach(function (data) {
// prefix data with mode indicator (4 bits)
@ -251,9 +251,9 @@ function createData (version, errorCorrectionLevel, segments) {
})
// Calculate required number of bits
var totalCodewords = Utils.getSymbolTotalCodewords(version)
var ecTotalCodewords = ECCode.getTotalCodewordsCount(version, errorCorrectionLevel)
var dataTotalCodewordsBits = (totalCodewords - ecTotalCodewords) * 8
const totalCodewords = Utils.getSymbolTotalCodewords(version)
const ecTotalCodewords = ECCode.getTotalCodewordsCount(version, errorCorrectionLevel)
const dataTotalCodewordsBits = (totalCodewords - ecTotalCodewords) * 8
// Add a terminator.
// If the bit string is shorter than the total number of required bits,
@ -277,8 +277,8 @@ function createData (version, errorCorrectionLevel, segments) {
// Extend the buffer to fill the data capacity of the symbol corresponding to
// the Version and Error Correction Level by adding the Pad Codewords 11101100 (0xEC)
// and 00010001 (0x11) alternately.
var remainingByte = (dataTotalCodewordsBits - buffer.getLengthInBits()) / 8
for (var i = 0; i < remainingByte; i++) {
const remainingByte = (dataTotalCodewordsBits - buffer.getLengthInBits()) / 8
for (let i = 0; i < remainingByte; i++) {
buffer.put(i % 2 ? 0x11 : 0xEC, 8)
}
@ -296,41 +296,41 @@ function createData (version, errorCorrectionLevel, segments) {
*/
function createCodewords (bitBuffer, version, errorCorrectionLevel) {
// Total codewords for this QR code version (Data + Error correction)
var totalCodewords = Utils.getSymbolTotalCodewords(version)
const totalCodewords = Utils.getSymbolTotalCodewords(version)
// Total number of error correction codewords
var ecTotalCodewords = ECCode.getTotalCodewordsCount(version, errorCorrectionLevel)
const ecTotalCodewords = ECCode.getTotalCodewordsCount(version, errorCorrectionLevel)
// Total number of data codewords
var dataTotalCodewords = totalCodewords - ecTotalCodewords
const dataTotalCodewords = totalCodewords - ecTotalCodewords
// Total number of blocks
var ecTotalBlocks = ECCode.getBlocksCount(version, errorCorrectionLevel)
const ecTotalBlocks = ECCode.getBlocksCount(version, errorCorrectionLevel)
// Calculate how many blocks each group should contain
var blocksInGroup2 = totalCodewords % ecTotalBlocks
var blocksInGroup1 = ecTotalBlocks - blocksInGroup2
const blocksInGroup2 = totalCodewords % ecTotalBlocks
const blocksInGroup1 = ecTotalBlocks - blocksInGroup2
var totalCodewordsInGroup1 = Math.floor(totalCodewords / ecTotalBlocks)
const totalCodewordsInGroup1 = Math.floor(totalCodewords / ecTotalBlocks)
var dataCodewordsInGroup1 = Math.floor(dataTotalCodewords / ecTotalBlocks)
var dataCodewordsInGroup2 = dataCodewordsInGroup1 + 1
const dataCodewordsInGroup1 = Math.floor(dataTotalCodewords / ecTotalBlocks)
const dataCodewordsInGroup2 = dataCodewordsInGroup1 + 1
// Number of EC codewords is the same for both groups
var ecCount = totalCodewordsInGroup1 - dataCodewordsInGroup1
const ecCount = totalCodewordsInGroup1 - dataCodewordsInGroup1
// Initialize a Reed-Solomon encoder with a generator polynomial of degree ecCount
var rs = new ReedSolomonEncoder(ecCount)
const rs = new ReedSolomonEncoder(ecCount)
var offset = 0
var dcData = new Array(ecTotalBlocks)
var ecData = new Array(ecTotalBlocks)
var maxDataSize = 0
var buffer = new Uint8Array(bitBuffer.buffer)
let offset = 0
const dcData = new Array(ecTotalBlocks)
const ecData = new Array(ecTotalBlocks)
let maxDataSize = 0
const buffer = new Uint8Array(bitBuffer.buffer)
// Divide the buffer into the required number of blocks
for (var b = 0; b < ecTotalBlocks; b++) {
var dataSize = b < blocksInGroup1 ? dataCodewordsInGroup1 : dataCodewordsInGroup2
for (let b = 0; b < ecTotalBlocks; b++) {
const dataSize = b < blocksInGroup1 ? dataCodewordsInGroup1 : dataCodewordsInGroup2
// extract a block of data from buffer
dcData[b] = buffer.slice(offset, offset + dataSize)
@ -344,9 +344,9 @@ function createCodewords (bitBuffer, version, errorCorrectionLevel) {
// Create final data
// Interleave the data and error correction codewords from each block
var data = new Uint8Array(totalCodewords)
var index = 0
var i, r
const data = new Uint8Array(totalCodewords)
let index = 0
let i, r
// Add data codewords
for (i = 0; i < maxDataSize; i++) {
@ -377,15 +377,15 @@ function createCodewords (bitBuffer, version, errorCorrectionLevel) {
* @return {Object} Object containing symbol data
*/
function createSymbol (data, version, errorCorrectionLevel, maskPattern) {
var segments
let segments
if (isArray(data)) {
segments = Segments.fromArray(data)
} else if (typeof data === 'string') {
var estimatedVersion = version
let estimatedVersion = version
if (!estimatedVersion) {
var rawSegments = Segments.rawSplit(data)
const rawSegments = Segments.rawSplit(data)
// Estimate best version that can contain raw splitted segments
estimatedVersion = Version.getBestVersionForData(rawSegments, errorCorrectionLevel)
@ -399,7 +399,7 @@ function createSymbol (data, version, errorCorrectionLevel, maskPattern) {
}
// Get the min version that can contain data
var bestVersion = Version.getBestVersionForData(segments, errorCorrectionLevel)
const bestVersion = Version.getBestVersionForData(segments, errorCorrectionLevel)
// If no version is found, data cannot be stored
if (!bestVersion) {
@ -418,11 +418,11 @@ function createSymbol (data, version, errorCorrectionLevel, maskPattern) {
)
}
var dataBits = createData(version, errorCorrectionLevel, segments)
const dataBits = createData(version, errorCorrectionLevel, segments)
// Allocate matrix buffer
var moduleCount = Utils.getSymbolSize(version)
var modules = new BitMatrix(moduleCount)
const moduleCount = Utils.getSymbolSize(version)
const modules = new BitMatrix(moduleCount)
// Add function modules
setupFinderPattern(modules, version)
@ -477,9 +477,9 @@ exports.create = function create (data, options) {
throw new Error('No input text')
}
var errorCorrectionLevel = ECLevel.M
var version
var mask
let errorCorrectionLevel = ECLevel.M
let version
let mask
if (typeof options !== 'undefined') {
// Use higher error correction level as default

View file

@ -1,4 +1,4 @@
var Polynomial = require('./polynomial')
const Polynomial = require('./polynomial')
function ReedSolomonEncoder (degree) {
this.genPoly = undefined
@ -32,19 +32,19 @@ ReedSolomonEncoder.prototype.encode = function encode (data) {
// Calculate EC for this data block
// extends data size to data+genPoly size
var paddedData = new Uint8Array(data.length + this.degree)
const paddedData = new Uint8Array(data.length + this.degree)
paddedData.set(data)
// The error correction codewords are the remainder after dividing the data codewords
// by a generator polynomial
var remainder = Polynomial.mod(paddedData, this.genPoly)
const remainder = Polynomial.mod(paddedData, this.genPoly)
// return EC data blocks (last n byte, where n is the degree of genPoly)
// If coefficients number in remainder are less than genPoly degree,
// pad with 0s to the left to reach the needed number of coefficients
var start = this.degree - remainder.length
const start = this.degree - remainder.length
if (start > 0) {
var buff = new Uint8Array(this.degree)
const buff = new Uint8Array(this.degree)
buff.set(remainder, start)
return buff

View file

@ -1,12 +1,12 @@
var numeric = '[0-9]+'
var alphanumeric = '[A-Z $%*+\\-./:]+'
var kanji = '(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|' +
const numeric = '[0-9]+'
const alphanumeric = '[A-Z $%*+\\-./:]+'
let kanji = '(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|' +
'[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|' +
'[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|' +
'[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+'
kanji = kanji.replace(/u/g, '\\u')
var byte = '(?:(?![A-Z0-9 $%*+\\-./:]|' + kanji + ')(?:.|[\r\n]))+'
const byte = '(?:(?![A-Z0-9 $%*+\\-./:]|' + kanji + ')(?:.|[\r\n]))+'
exports.KANJI = new RegExp(kanji, 'g')
exports.BYTE_KANJI = new RegExp('[^A-Z0-9 $%*+\\-./:]+', 'g')
@ -14,9 +14,9 @@ exports.BYTE = new RegExp(byte, 'g')
exports.NUMERIC = new RegExp(numeric, 'g')
exports.ALPHANUMERIC = new RegExp(alphanumeric, 'g')
var TEST_KANJI = new RegExp('^' + kanji + '$')
var TEST_NUMERIC = new RegExp('^' + numeric + '$')
var TEST_ALPHANUMERIC = new RegExp('^[A-Z0-9 $%*+\\-./:]+$')
const TEST_KANJI = new RegExp('^' + kanji + '$')
const TEST_NUMERIC = new RegExp('^' + numeric + '$')
const TEST_ALPHANUMERIC = new RegExp('^[A-Z0-9 $%*+\\-./:]+$')
exports.testKanji = function testKanji (str) {
return TEST_KANJI.test(str)

View file

@ -1,11 +1,11 @@
var Mode = require('./mode')
var NumericData = require('./numeric-data')
var AlphanumericData = require('./alphanumeric-data')
var ByteData = require('./byte-data')
var KanjiData = require('./kanji-data')
var Regex = require('./regex')
var Utils = require('./utils')
var dijkstra = require('dijkstrajs')
const Mode = require('./mode')
const NumericData = require('./numeric-data')
const AlphanumericData = require('./alphanumeric-data')
const ByteData = require('./byte-data')
const KanjiData = require('./kanji-data')
const Regex = require('./regex')
const Utils = require('./utils')
const dijkstra = require('dijkstrajs')
/**
* Returns UTF8 byte length
@ -26,8 +26,8 @@ function getStringByteLength (str) {
* @return {Array} Array of object with segments data
*/
function getSegments (regex, mode, str) {
var segments = []
var result
const segments = []
let result
while ((result = regex.exec(str)) !== null) {
segments.push({
@ -49,10 +49,10 @@ function getSegments (regex, mode, str) {
* @return {Array} Array of object with segments data
*/
function getSegmentsFromString (dataStr) {
var numSegs = getSegments(Regex.NUMERIC, Mode.NUMERIC, dataStr)
var alphaNumSegs = getSegments(Regex.ALPHANUMERIC, Mode.ALPHANUMERIC, dataStr)
var byteSegs
var kanjiSegs
const numSegs = getSegments(Regex.NUMERIC, Mode.NUMERIC, dataStr)
const alphaNumSegs = getSegments(Regex.ALPHANUMERIC, Mode.ALPHANUMERIC, dataStr)
let byteSegs
let kanjiSegs
if (Utils.isKanjiModeEnabled()) {
byteSegs = getSegments(Regex.BYTE, Mode.BYTE, dataStr)
@ -62,7 +62,7 @@ function getSegmentsFromString (dataStr) {
kanjiSegs = []
}
var segs = numSegs.concat(alphaNumSegs, byteSegs, kanjiSegs)
const segs = numSegs.concat(alphaNumSegs, byteSegs, kanjiSegs)
return segs
.sort(function (s1, s2) {
@ -106,7 +106,7 @@ function getSegmentBitsLength (length, mode) {
*/
function mergeSegments (segs) {
return segs.reduce(function (acc, curr) {
var prevSeg = acc.length - 1 >= 0 ? acc[acc.length - 1] : null
const prevSeg = acc.length - 1 >= 0 ? acc[acc.length - 1] : null
if (prevSeg && prevSeg.mode === curr.mode) {
acc[acc.length - 1].data += curr.data
return acc
@ -134,9 +134,9 @@ function mergeSegments (segs) {
* @return {Array} Array of object with segments data
*/
function buildNodes (segs) {
var nodes = []
for (var i = 0; i < segs.length; i++) {
var seg = segs[i]
const nodes = []
for (let i = 0; i < segs.length; i++) {
const seg = segs[i]
switch (seg.mode) {
case Mode.NUMERIC:
@ -178,24 +178,24 @@ function buildNodes (segs) {
* @return {Object} Graph of all possible segments
*/
function buildGraph (nodes, version) {
var table = {}
var graph = { start: {} }
var prevNodeIds = ['start']
const table = {}
const graph = { start: {} }
let prevNodeIds = ['start']
for (var i = 0; i < nodes.length; i++) {
var nodeGroup = nodes[i]
var currentNodeIds = []
for (let i = 0; i < nodes.length; i++) {
const nodeGroup = nodes[i]
const currentNodeIds = []
for (var j = 0; j < nodeGroup.length; j++) {
var node = nodeGroup[j]
var key = '' + i + j
for (let j = 0; j < nodeGroup.length; j++) {
const node = nodeGroup[j]
const key = '' + i + j
currentNodeIds.push(key)
table[key] = { node: node, lastCount: 0 }
graph[key] = {}
for (var n = 0; n < prevNodeIds.length; n++) {
var prevNodeId = prevNodeIds[n]
for (let n = 0; n < prevNodeIds.length; n++) {
const prevNodeId = prevNodeIds[n]
if (table[prevNodeId] && table[prevNodeId].node.mode === node.mode) {
graph[prevNodeId][key] =
@ -215,7 +215,7 @@ function buildGraph (nodes, version) {
prevNodeIds = currentNodeIds
}
for (n = 0; n < prevNodeIds.length; n++) {
for (let n = 0; n < prevNodeIds.length; n++) {
graph[prevNodeIds[n]].end = 0
}
@ -231,8 +231,8 @@ function buildGraph (nodes, version) {
* @return {Segment} Segment
*/
function buildSingleSegment (data, modesHint) {
var mode
var bestMode = Mode.getBestModeForData(data)
let mode
const bestMode = Mode.getBestModeForData(data)
mode = Mode.from(modesHint, bestMode)
@ -299,14 +299,14 @@ exports.fromArray = function fromArray (array) {
* @return {Array} Array of segments
*/
exports.fromString = function fromString (data, version) {
var segs = getSegmentsFromString(data, Utils.isKanjiModeEnabled())
const segs = getSegmentsFromString(data, Utils.isKanjiModeEnabled())
var nodes = buildNodes(segs)
var graph = buildGraph(nodes, version)
var path = dijkstra.find_path(graph.map, 'start', 'end')
const nodes = buildNodes(segs)
const graph = buildGraph(nodes, version)
const path = dijkstra.find_path(graph.map, 'start', 'end')
var optimizedSegs = []
for (var i = 1; i < path.length - 1; i++) {
const optimizedSegs = []
for (let i = 1; i < path.length - 1; i++) {
optimizedSegs.push(graph.table[path[i]].node)
}

View file

@ -1,5 +1,5 @@
var toSJISFunction
var CODEWORDS_COUNT = [
let toSJISFunction
const CODEWORDS_COUNT = [
0, // Not used
26, 44, 70, 100, 134, 172, 196, 242, 292, 346,
404, 466, 532, 581, 655, 733, 815, 901, 991, 1085,
@ -36,7 +36,7 @@ exports.getSymbolTotalCodewords = function getSymbolTotalCodewords (version) {
* @return {Number} Encoded value
*/
exports.getBCHDigit = function (data) {
var digit = 0
let digit = 0
while (data !== 0) {
digit++

View file

@ -1,16 +1,16 @@
var Utils = require('./utils')
var ECCode = require('./error-correction-code')
var ECLevel = require('./error-correction-level')
var Mode = require('./mode')
var VersionCheck = require('./version-check')
var isArray = require('isarray')
const Utils = require('./utils')
const ECCode = require('./error-correction-code')
const ECLevel = require('./error-correction-level')
const Mode = require('./mode')
const VersionCheck = require('./version-check')
const isArray = require('isarray')
// Generator polynomial used to encode version information
var G18 = (1 << 12) | (1 << 11) | (1 << 10) | (1 << 9) | (1 << 8) | (1 << 5) | (1 << 2) | (1 << 0)
var G18_BCH = Utils.getBCHDigit(G18)
const G18 = (1 << 12) | (1 << 11) | (1 << 10) | (1 << 9) | (1 << 8) | (1 << 5) | (1 << 2) | (1 << 0)
const G18_BCH = Utils.getBCHDigit(G18)
function getBestVersionForDataLength (mode, length, errorCorrectionLevel) {
for (var currentVersion = 1; currentVersion <= 40; currentVersion++) {
for (let currentVersion = 1; currentVersion <= 40; currentVersion++) {
if (length <= exports.getCapacity(currentVersion, errorCorrectionLevel, mode)) {
return currentVersion
}
@ -25,10 +25,10 @@ function getReservedBitsCount (mode, version) {
}
function getTotalBitsFromDataArray (segments, version) {
var totalBits = 0
let totalBits = 0
segments.forEach(function (data) {
var reservedBits = getReservedBitsCount(data.mode, version)
const reservedBits = getReservedBitsCount(data.mode, version)
totalBits += reservedBits + data.getBitsLength()
})
@ -36,8 +36,8 @@ function getTotalBitsFromDataArray (segments, version) {
}
function getBestVersionForMixedData (segments, errorCorrectionLevel) {
for (var currentVersion = 1; currentVersion <= 40; currentVersion++) {
var length = getTotalBitsFromDataArray(segments, currentVersion)
for (let currentVersion = 1; currentVersion <= 40; currentVersion++) {
const length = getTotalBitsFromDataArray(segments, currentVersion)
if (length <= exports.getCapacity(currentVersion, errorCorrectionLevel, Mode.MIXED)) {
return currentVersion
}
@ -80,17 +80,17 @@ exports.getCapacity = function getCapacity (version, errorCorrectionLevel, mode)
if (typeof mode === 'undefined') mode = Mode.BYTE
// Total codewords for this QR code version (Data + Error correction)
var totalCodewords = Utils.getSymbolTotalCodewords(version)
const totalCodewords = Utils.getSymbolTotalCodewords(version)
// Total number of error correction codewords
var ecTotalCodewords = ECCode.getTotalCodewordsCount(version, errorCorrectionLevel)
const ecTotalCodewords = ECCode.getTotalCodewordsCount(version, errorCorrectionLevel)
// Total number of data codewords
var dataTotalCodewordsBits = (totalCodewords - ecTotalCodewords) * 8
const dataTotalCodewordsBits = (totalCodewords - ecTotalCodewords) * 8
if (mode === Mode.MIXED) return dataTotalCodewordsBits
var usableBits = dataTotalCodewordsBits - getReservedBitsCount(mode, version)
const usableBits = dataTotalCodewordsBits - getReservedBitsCount(mode, version)
// Return max number of storable codewords
switch (mode) {
@ -118,9 +118,9 @@ exports.getCapacity = function getCapacity (version, errorCorrectionLevel, mode)
* @return {Number} QR Code version
*/
exports.getBestVersionForData = function getBestVersionForData (data, errorCorrectionLevel) {
var seg
let seg
var ecl = ECLevel.from(errorCorrectionLevel, ECLevel.M)
const ecl = ECLevel.from(errorCorrectionLevel, ECLevel.M)
if (isArray(data)) {
if (data.length > 1) {
@ -154,7 +154,7 @@ exports.getEncodedBits = function getEncodedBits (version) {
throw new Error('Invalid QR Code version')
}
var d = version << 12
let d = version << 12
while (Utils.getBCHDigit(d) - G18_BCH >= 0) {
d ^= (G18 << (Utils.getBCHDigit(d) - G18_BCH))

View file

@ -1,4 +1,4 @@
var Utils = require('./utils')
const Utils = require('./utils')
function clearCanvas (ctx, canvas, size) {
ctx.clearRect(0, 0, canvas.width, canvas.height)
@ -19,8 +19,8 @@ function getCanvasElement () {
}
exports.render = function render (qrData, canvas, options) {
var opts = options
var canvasEl = canvas
let opts = options
let canvasEl = canvas
if (typeof opts === 'undefined' && (!canvas || !canvas.getContext)) {
opts = canvas
@ -32,10 +32,10 @@ exports.render = function render (qrData, canvas, options) {
}
opts = Utils.getOptions(opts)
var size = Utils.getImageWidth(qrData.modules.size, opts)
const size = Utils.getImageWidth(qrData.modules.size, opts)
var ctx = canvasEl.getContext('2d')
var image = ctx.createImageData(size, size)
const ctx = canvasEl.getContext('2d')
const image = ctx.createImageData(size, size)
Utils.qrToImageData(image.data, qrData, opts)
clearCanvas(ctx, canvasEl, size)
@ -45,7 +45,7 @@ exports.render = function render (qrData, canvas, options) {
}
exports.renderToDataURL = function renderToDataURL (qrData, canvas, options) {
var opts = options
let opts = options
if (typeof opts === 'undefined' && (!canvas || !canvas.getContext)) {
opts = canvas
@ -54,10 +54,10 @@ exports.renderToDataURL = function renderToDataURL (qrData, canvas, options) {
if (!opts) opts = {}
var canvasEl = exports.render(qrData, canvas, opts)
const canvasEl = exports.render(qrData, canvas, opts)
var type = opts.type || 'image/png'
var rendererOpts = opts.rendererOpts || {}
const type = opts.type || 'image/png'
const rendererOpts = opts.rendererOpts || {}
return canvasEl.toDataURL(type, rendererOpts.quality)
}

View file

@ -1,16 +1,16 @@
var fs = require('fs')
var PNG = require('pngjs').PNG
var Utils = require('./utils')
const fs = require('fs')
const PNG = require('pngjs').PNG
const Utils = require('./utils')
exports.render = function render (qrData, options) {
var opts = Utils.getOptions(options)
var pngOpts = opts.rendererOpts
var size = Utils.getImageWidth(qrData.modules.size, opts)
const opts = Utils.getOptions(options)
const pngOpts = opts.rendererOpts
const size = Utils.getImageWidth(qrData.modules.size, opts)
pngOpts.width = size
pngOpts.height = size
var pngImage = new PNG(pngOpts)
const pngImage = new PNG(pngOpts)
Utils.qrToImageData(pngImage.data, qrData, opts)
return pngImage
@ -24,7 +24,7 @@ exports.renderToDataURL = function renderToDataURL (qrData, options, cb) {
exports.renderToBuffer(qrData, options, function (err, output) {
if (err) cb(err)
var url = 'data:image/png;base64,'
let url = 'data:image/png;base64,'
url += output.toString('base64')
cb(null, url)
})
@ -36,8 +36,8 @@ exports.renderToBuffer = function renderToBuffer (qrData, options, cb) {
options = undefined
}
var png = exports.render(qrData, options)
var buffer = []
const png = exports.render(qrData, options)
const buffer = []
png.on('error', cb)
@ -58,7 +58,7 @@ exports.renderToFile = function renderToFile (path, qrData, options, cb) {
options = undefined
}
var stream = fs.createWriteStream(path)
const stream = fs.createWriteStream(path)
stream.on('error', cb)
stream.on('close', cb)
@ -66,6 +66,6 @@ exports.renderToFile = function renderToFile (path, qrData, options, cb) {
}
exports.renderToFileStream = function renderToFileStream (stream, qrData, options) {
var png = exports.render(qrData, options)
const png = exports.render(qrData, options)
png.pack().pipe(stream)
}

View file

@ -1,8 +1,8 @@
var Utils = require('./utils')
const Utils = require('./utils')
function getColorAttrib (color, attrib) {
var alpha = color.a / 255
var str = attrib + '="' + color.hex + '"'
const alpha = color.a / 255
const str = attrib + '="' + color.hex + '"'
return alpha < 1
? str + ' ' + attrib + '-opacity="' + alpha.toFixed(2).slice(1) + '"'
@ -10,21 +10,21 @@ function getColorAttrib (color, attrib) {
}
function svgCmd (cmd, x, y) {
var str = cmd + x
let str = cmd + x
if (typeof y !== 'undefined') str += ' ' + y
return str
}
function qrToPath (data, size, margin) {
var path = ''
var moveBy = 0
var newRow = false
var lineLength = 0
let path = ''
let moveBy = 0
let newRow = false
let lineLength = 0
for (var i = 0; i < data.length; i++) {
var col = Math.floor(i % size)
var row = Math.floor(i / size)
for (let i = 0; i < data.length; i++) {
const col = Math.floor(i % size)
const row = Math.floor(i / size)
if (!col && !newRow) newRow = true
@ -53,25 +53,25 @@ function qrToPath (data, size, margin) {
}
exports.render = function render (qrData, options, cb) {
var opts = Utils.getOptions(options)
var size = qrData.modules.size
var data = qrData.modules.data
var qrcodesize = size + opts.margin * 2
const opts = Utils.getOptions(options)
const size = qrData.modules.size
const data = qrData.modules.data
const qrcodesize = size + opts.margin * 2
var bg = !opts.color.light.a
const bg = !opts.color.light.a
? ''
: '<path ' + getColorAttrib(opts.color.light, 'fill') +
' d="M0 0h' + qrcodesize + 'v' + qrcodesize + 'H0z"/>'
var path =
const path =
'<path ' + getColorAttrib(opts.color.dark, 'stroke') +
' d="' + qrToPath(data, size, opts.margin) + '"/>'
var viewBox = 'viewBox="' + '0 0 ' + qrcodesize + ' ' + qrcodesize + '"'
const viewBox = 'viewBox="' + '0 0 ' + qrcodesize + ' ' + qrcodesize + '"'
var width = !opts.width ? '' : 'width="' + opts.width + '" height="' + opts.width + '" '
const width = !opts.width ? '' : 'width="' + opts.width + '" height="' + opts.width + '" '
var svgTag = '<svg xmlns="http://www.w3.org/2000/svg" ' + width + viewBox + ' shape-rendering="crispEdges">' + bg + path + '</svg>\n'
const svgTag = '<svg xmlns="http://www.w3.org/2000/svg" ' + width + viewBox + ' shape-rendering="crispEdges">' + bg + path + '</svg>\n'
if (typeof cb === 'function') {
cb(null, svgTag)

View file

@ -1,4 +1,4 @@
var svgTagRenderer = require('./svg-tag')
const svgTagRenderer = require('./svg-tag')
exports.render = svgTagRenderer.render
@ -8,10 +8,10 @@ exports.renderToFile = function renderToFile (path, qrData, options, cb) {
options = undefined
}
var fs = require('fs')
var svgTag = exports.render(qrData, options)
const fs = require('fs')
const svgTag = exports.render(qrData, options)
var xmlStr = '<?xml version="1.0" encoding="utf-8"?>' +
const xmlStr = '<?xml version="1.0" encoding="utf-8"?>' +
'<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">' +
svgTag

View file

@ -1,25 +1,25 @@
// var Utils = require('./utils')
// let Utils = require('./utils')
exports.render = function (qrData, options, cb) {
var size = qrData.modules.size
var data = qrData.modules.data
const size = qrData.modules.size
const data = qrData.modules.data
// var opts = Utils.getOptions(options)
// let opts = Utils.getOptions(options)
// use same scheme as https://github.com/gtanner/qrcode-terminal because it actually works! =)
var black = '\x1b[40m \x1b[0m'
var white = '\x1b[47m \x1b[0m'
const black = '\x1b[40m \x1b[0m'
const white = '\x1b[47m \x1b[0m'
var output = ''
var hMargin = Array(size + 3).join(white)
var vMargin = Array(2).join(white)
let output = ''
const hMargin = Array(size + 3).join(white)
const vMargin = Array(2).join(white)
output += hMargin + '\n'
for (var i = 0; i < size; ++i) {
for (let i = 0; i < size; ++i) {
output += white
for (var j = 0; j < size; j++) {
// var topModule = data[i * size + j]
// var bottomModule = data[(i + 1) * size + j]
for (let j = 0; j < size; j++) {
// let topModule = data[i * size + j]
// let bottomModule = data[(i + 1) * size + j]
output += data[i * size + j] ? black : white// getBlockChar(topModule, bottomModule)
}
@ -42,8 +42,8 @@ exports.renderToFile = function renderToFile (path, qrData, options, cb) {
options = undefined
}
var fs = require('fs')
var utf8 = exports.render(qrData, options)
let fs = require('fs')
let utf8 = exports.render(qrData, options)
fs.writeFile(path, utf8, cb)
}
*/

View file

@ -1,13 +1,13 @@
var Utils = require('./utils')
const Utils = require('./utils')
var BLOCK_CHAR = {
const BLOCK_CHAR = {
WW: ' ',
WB: '▄',
BB: '█',
BW: '▀'
}
var INVERTED_BLOCK_CHAR = {
const INVERTED_BLOCK_CHAR = {
BB: ' ',
BW: '▄',
WW: '█',
@ -22,27 +22,27 @@ function getBlockChar (top, bottom, blocks) {
}
exports.render = function (qrData, options, cb) {
var opts = Utils.getOptions(options)
var blocks = BLOCK_CHAR
const opts = Utils.getOptions(options)
let blocks = BLOCK_CHAR
if (opts.color.dark.hex === '#ffffff' || opts.color.light.hex === '#000000') {
blocks = INVERTED_BLOCK_CHAR
}
var size = qrData.modules.size
var data = qrData.modules.data
const size = qrData.modules.size
const data = qrData.modules.data
var output = ''
var hMargin = Array(size + (opts.margin * 2) + 1).join(blocks.WW)
let output = ''
let hMargin = Array(size + (opts.margin * 2) + 1).join(blocks.WW)
hMargin = Array((opts.margin / 2) + 1).join(hMargin + '\n')
var vMargin = Array(opts.margin + 1).join(blocks.WW)
const vMargin = Array(opts.margin + 1).join(blocks.WW)
output += hMargin
for (var i = 0; i < size; i += 2) {
for (let i = 0; i < size; i += 2) {
output += vMargin
for (var j = 0; j < size; j++) {
var topModule = data[i * size + j]
var bottomModule = data[(i + 1) * size + j]
for (let j = 0; j < size; j++) {
const topModule = data[i * size + j]
const bottomModule = data[(i + 1) * size + j]
output += getBlockChar(topModule, bottomModule, blocks)
}
@ -65,7 +65,7 @@ exports.renderToFile = function renderToFile (path, qrData, options, cb) {
options = undefined
}
var fs = require('fs')
var utf8 = exports.render(qrData, options)
const fs = require('fs')
const utf8 = exports.render(qrData, options)
fs.writeFile(path, utf8, cb)
}

View file

@ -7,7 +7,7 @@ function hex2rgba (hex) {
throw new Error('Color should be defined as hex string')
}
var hexCode = hex.slice().replace('#', '').split('')
let hexCode = hex.slice().replace('#', '').split('')
if (hexCode.length < 3 || hexCode.length === 5 || hexCode.length > 8) {
throw new Error('Invalid hex color: ' + hex)
}
@ -22,7 +22,7 @@ function hex2rgba (hex) {
// Add default alpha value
if (hexCode.length === 6) hexCode.push('F', 'F')
var hexValue = parseInt(hexCode.join(''), 16)
const hexValue = parseInt(hexCode.join(''), 16)
return {
r: (hexValue >> 24) & 255,
@ -37,12 +37,12 @@ exports.getOptions = function getOptions (options) {
if (!options) options = {}
if (!options.color) options.color = {}
var margin = typeof options.margin === 'undefined' ||
const margin = typeof options.margin === 'undefined' ||
options.margin === null ||
options.margin < 0 ? 4 : options.margin
var width = options.width && options.width >= 21 ? options.width : undefined
var scale = options.scale || 4
const width = options.width && options.width >= 21 ? options.width : undefined
const scale = options.scale || 4
return {
width: width,
@ -64,27 +64,27 @@ exports.getScale = function getScale (qrSize, opts) {
}
exports.getImageWidth = function getImageWidth (qrSize, opts) {
var scale = exports.getScale(qrSize, opts)
const scale = exports.getScale(qrSize, opts)
return Math.floor((qrSize + opts.margin * 2) * scale)
}
exports.qrToImageData = function qrToImageData (imgData, qr, opts) {
var size = qr.modules.size
var data = qr.modules.data
var scale = exports.getScale(size, opts)
var symbolSize = Math.floor((size + opts.margin * 2) * scale)
var scaledMargin = opts.margin * scale
var palette = [opts.color.light, opts.color.dark]
const size = qr.modules.size
const data = qr.modules.data
const scale = exports.getScale(size, opts)
const symbolSize = Math.floor((size + opts.margin * 2) * scale)
const scaledMargin = opts.margin * scale
const palette = [opts.color.light, opts.color.dark]
for (var i = 0; i < symbolSize; i++) {
for (var j = 0; j < symbolSize; j++) {
var posDst = (i * symbolSize + j) * 4
var pxColor = opts.color.light
for (let i = 0; i < symbolSize; i++) {
for (let j = 0; j < symbolSize; j++) {
let posDst = (i * symbolSize + j) * 4
let pxColor = opts.color.light
if (i >= scaledMargin && j >= scaledMargin &&
i < symbolSize - scaledMargin && j < symbolSize - scaledMargin) {
var iSrc = Math.floor((i - scaledMargin) / scale)
var jSrc = Math.floor((j - scaledMargin) / scale)
const iSrc = Math.floor((i - scaledMargin) / scale)
const jSrc = Math.floor((j - scaledMargin) / scale)
pxColor = palette[data[iSrc * size + jSrc] ? 1 : 0]
}

View file

@ -1,9 +1,9 @@
var canPromise = require('./can-promise')
var QRCode = require('./core/qrcode')
var PngRenderer = require('./renderer/png')
var Utf8Renderer = require('./renderer/utf8')
var TerminalRenderer = require('./renderer/terminal')
var SvgRenderer = require('./renderer/svg')
const canPromise = require('./can-promise')
const QRCode = require('./core/qrcode')
const PngRenderer = require('./renderer/png')
const Utf8Renderer = require('./renderer/utf8')
const TerminalRenderer = require('./renderer/terminal')
const SvgRenderer = require('./renderer/svg')
function checkParams (text, opts, cb) {
if (typeof text === 'undefined') {
@ -68,7 +68,7 @@ function render (renderFunc, text, params) {
if (!params.cb) {
return new Promise(function (resolve, reject) {
try {
var data = QRCode.create(text, params.opts)
const data = QRCode.create(text, params.opts)
return renderFunc(data, params.opts, function (err, data) {
return err ? reject(err) : resolve(data)
})
@ -79,7 +79,7 @@ function render (renderFunc, text, params) {
}
try {
var data = QRCode.create(text, params.opts)
const data = QRCode.create(text, params.opts)
return renderFunc(data, params.opts, params.cb)
} catch (e) {
params.cb(e)
@ -91,20 +91,20 @@ exports.create = QRCode.create
exports.toCanvas = require('./browser').toCanvas
exports.toString = function toString (text, opts, cb) {
var params = checkParams(text, opts, cb)
var renderer = getStringRendererFromType(params.opts.type)
const params = checkParams(text, opts, cb)
const renderer = getStringRendererFromType(params.opts.type)
return render(renderer.render, text, params)
}
exports.toDataURL = function toDataURL (text, opts, cb) {
var params = checkParams(text, opts, cb)
var renderer = getRendererFromType(params.opts.type)
const params = checkParams(text, opts, cb)
const renderer = getRendererFromType(params.opts.type)
return render(renderer.renderToDataURL, text, params)
}
exports.toBuffer = function toBuffer (text, opts, cb) {
var params = checkParams(text, opts, cb)
var renderer = getRendererFromType(params.opts.type)
const params = checkParams(text, opts, cb)
const renderer = getRendererFromType(params.opts.type)
return render(renderer.renderToBuffer, text, params)
}
@ -117,10 +117,10 @@ exports.toFile = function toFile (path, text, opts, cb) {
throw new Error('Too few arguments provided')
}
var params = checkParams(text, opts, cb)
var type = params.opts.type || getTypeFromFilename(path)
var renderer = getRendererFromType(type)
var renderToFile = renderer.renderToFile.bind(null, path)
const params = checkParams(text, opts, cb)
const type = params.opts.type || getTypeFromFilename(path)
const renderer = getRendererFromType(type)
const renderToFile = renderer.renderToFile.bind(null, path)
return render(renderToFile, text, params)
}
@ -130,8 +130,8 @@ exports.toFileStream = function toFileStream (stream, text, opts) {
throw new Error('Too few arguments provided')
}
var params = checkParams(text, opts, stream.emit.bind(stream, 'error'))
var renderer = getRendererFromType('png') // Only png support for now
var renderToFileStream = renderer.renderToFileStream.bind(null, stream)
const params = checkParams(text, opts, stream.emit.bind(stream, 'error'))
const renderer = getRendererFromType('png') // Only png support for now
const renderToFileStream = renderer.renderToFileStream.bind(null, stream)
render(renderToFileStream, text, params)
}

View file

@ -1,7 +1,7 @@
var spawn = require('child_process').spawn
var path = require('path')
const spawn = require('child_process').spawn
const path = require('path')
var opt = {
const opt = {
cwd: __dirname,
env: (function () {
process.env.NODE_PATH = './' + path.delimiter + './lib'

View file

@ -1,7 +1,7 @@
var test = require('tap').test
var { Canvas, createCanvas } = require('canvas')
var QRCode = require('lib')
var Helpers = require('test/helpers')
const test = require('tap').test
const { Canvas, createCanvas } = require('canvas')
const QRCode = require('lib')
const Helpers = require('test/helpers')
test('toCanvas - no promise available', function (t) {
Helpers.removeNativePromise()
@ -14,7 +14,7 @@ test('toCanvas - no promise available', function (t) {
}
}
}
var canvasEl = createCanvas(200, 200)
const canvasEl = createCanvas(200, 200)
t.throw(function () { QRCode.toCanvas() },
'Should throw if no arguments are provided')
@ -79,7 +79,7 @@ test('toCanvas', function (t) {
})
test('toCanvas with specified canvas element', function (t) {
var canvasEl = createCanvas(200, 200)
const canvasEl = createCanvas(200, 200)
t.plan(6)

View file

@ -1,8 +1,8 @@
var test = require('tap').test
var QRCode = require('lib')
var QRCodeBrowser = require('lib/browser')
var { createCanvas } = require('canvas')
var Helpers = require('test/helpers')
const test = require('tap').test
const QRCode = require('lib')
const QRCodeBrowser = require('lib/browser')
const { createCanvas } = require('canvas')
const Helpers = require('test/helpers')
test('toDataURL - no promise available', function (t) {
Helpers.removeNativePromise()
@ -37,7 +37,7 @@ test('toDataURL - no promise available', function (t) {
})
test('toDataURL - image/png', function (t) {
var expectedDataURL = [
const expectedDataURL = [
'data:image/png;base64,',
'iVBORw0KGgoAAAANSUhEUgAAAHQAAAB0CAYAAABUmhYnAAAAAklEQVR4AewaftIAAAKzSU',
'RBVO3BQW7kQAwEwSxC//9y7h55akCQxvYQjIj/scYo1ijFGqVYoxRrlGKNUqxRijVKsUYp',
@ -99,7 +99,7 @@ test('toDataURL - image/png', function (t) {
})
test('Canvas toDataURL - image/png', function (t) {
var expectedDataURL = [
const expectedDataURL = [
'data:image/png;base64,',
'iVBORw0KGgoAAAANSUhEUgAAAIQAAACECAYAAABRRIOnAAAABmJLR0QA/wD/AP+gvaeTAA',
'AC20lEQVR4nO3dQY7jMAwEwM1i///lzGUurYtWEEknQNV1EidjNGhFpuTX+/1+/4Fff5/+',
@ -126,7 +126,7 @@ test('Canvas toDataURL - image/png', function (t) {
t.throw(function () { QRCodeBrowser.toDataURL(function () {}) },
'Should throw if text is not provided')
var canvas = createCanvas(200, 200)
const canvas = createCanvas(200, 200)
QRCodeBrowser.toDataURL(canvas, 'i am a pony!', {
errorCorrectionLevel: 'H',
type: 'image/png'

View file

@ -1,15 +1,15 @@
var test = require('tap').test
var fs = require('fs')
var path = require('path')
var os = require('os')
var sinon = require('sinon')
var QRCode = require('lib')
var Helpers = require('test/helpers')
var StreamMock = require('test/mocks/writable-stream')
const test = require('tap').test
const fs = require('fs')
const path = require('path')
const os = require('os')
const sinon = require('sinon')
const QRCode = require('lib')
const Helpers = require('test/helpers')
const StreamMock = require('test/mocks/writable-stream')
test('toFile - no promise available', function (t) {
Helpers.removeNativePromise()
var fileName = path.join(os.tmpdir(), 'qrimage.png')
const fileName = path.join(os.tmpdir(), 'qrimage.png')
t.throw(function () { QRCode.toFile(fileName, 'some text') },
'Should throw if a callback is not provided')
@ -23,7 +23,7 @@ test('toFile - no promise available', function (t) {
})
test('toFile', function (t) {
var fileName = path.join(os.tmpdir(), 'qrimage.png')
const fileName = path.join(os.tmpdir(), 'qrimage.png')
t.throw(function () { QRCode.toFile('some text', function () {}) },
'Should throw if path is not provided')
@ -38,8 +38,8 @@ test('toFile', function (t) {
})
test('toFile png', function (t) {
var fileName = path.join(os.tmpdir(), 'qrimage.png')
var expectedBase64Output = [
const fileName = path.join(os.tmpdir(), 'qrimage.png')
const expectedBase64Output = [
'iVBORw0KGgoAAAANSUhEUgAAAHQAAAB0CAYAAABUmhYnAAAAAklEQVR4AewaftIAAAKzSU',
'RBVO3BQW7kQAwEwSxC//9y7h55akCQxvYQjIj/scYo1ijFGqVYoxRrlGKNUqxRijVKsUYp',
'1ijFGqVYoxRrlGKNUqxRijXKxUNJ+EkqdyShU+mS0Kl0SfhJKk8Ua5RijVKsUS5epvKmJD',
@ -99,7 +99,7 @@ test('toFile png', function (t) {
})
})
var fsStub = sinon.stub(fs, 'createWriteStream')
const fsStub = sinon.stub(fs, 'createWriteStream')
fsStub.returns(new StreamMock().forceErrorOnWrite())
QRCode.toFile(fileName, 'i am a pony!', {
@ -118,8 +118,8 @@ test('toFile png', function (t) {
})
test('toFile svg', function (t) {
var fileName = path.join(os.tmpdir(), 'qrimage.svg')
var expectedOutput = fs.readFileSync(
const fileName = path.join(os.tmpdir(), 'qrimage.svg')
const expectedOutput = fs.readFileSync(
path.join(__dirname, '/svg.expected.out'), 'UTF-8')
t.plan(6)
@ -165,8 +165,8 @@ test('toFile svg', function (t) {
})
test('toFile utf8', function (t) {
var fileName = path.join(os.tmpdir(), 'qrimage.txt')
var expectedOutput = [
const fileName = path.join(os.tmpdir(), 'qrimage.txt')
const expectedOutput = [
' ',
' ',
' █▀▀▀▀▀█ █ ▄█ ▀ █ █▀▀▀▀▀█ ',
@ -225,12 +225,12 @@ test('toFile utf8', function (t) {
})
test('toFile manual segments', function (t) {
var fileName = path.join(os.tmpdir(), 'qrimage.txt')
var segs = [
const fileName = path.join(os.tmpdir(), 'qrimage.txt')
const segs = [
{ data: 'ABCDEFG', mode: 'alphanumeric' },
{ data: '0123456', mode: 'numeric' }
]
var expectedOutput = [
const expectedOutput = [
' ',
' ',
' █▀▀▀▀▀█ ██▀██ █▀▀▀▀▀█ ',

View file

@ -1,7 +1,7 @@
var test = require('tap').test
var sinon = require('sinon')
var QRCode = require('lib')
var StreamMock = require('../mocks/writable-stream')
const test = require('tap').test
const sinon = require('sinon')
const QRCode = require('lib')
const StreamMock = require('../mocks/writable-stream')
test('toFileStream png', function (t) {
t.throw(function () { QRCode.toFileStream('some text') },
@ -10,8 +10,8 @@ test('toFileStream png', function (t) {
t.throw(function () { QRCode.toFileStream(new StreamMock()) },
'Should throw if text is not provided')
var fstream = new StreamMock()
var spy = sinon.spy(fstream, 'emit')
const fstream = new StreamMock()
const spy = sinon.spy(fstream, 'emit')
QRCode.toFileStream(fstream, 'i am a pony!')
@ -27,7 +27,7 @@ test('toFileStream png', function (t) {
})
test('toFileStream png with write error', function (t) {
var fstreamErr = new StreamMock().forceErrorOnWrite()
const fstreamErr = new StreamMock().forceErrorOnWrite()
QRCode.toFileStream(fstreamErr, 'i am a pony!')
t.plan(2)
@ -38,8 +38,8 @@ test('toFileStream png with write error', function (t) {
})
test('toFileStream png with qrcode error', function (t) {
var fstreamErr = new StreamMock()
var bigString = Array(200).join('i am a pony!')
const fstreamErr = new StreamMock()
const bigString = Array(200).join('i am a pony!')
t.plan(2)

View file

@ -1,9 +1,9 @@
var test = require('tap').test
var fs = require('fs')
var path = require('path')
var QRCode = require('lib')
var browser = require('lib/browser')
var Helpers = require('test/helpers')
const test = require('tap').test
const fs = require('fs')
const path = require('path')
const QRCode = require('lib')
const browser = require('lib/browser')
const Helpers = require('test/helpers')
test('toString - no promise available', function (t) {
Helpers.removeNativePromise()
@ -76,7 +76,7 @@ test('toString (browser)', function (t) {
})
test('toString svg', function (t) {
var file = path.join(__dirname, '/svgtag.expected.out')
const file = path.join(__dirname, '/svgtag.expected.out')
t.plan(6)
QRCode.toString('http://www.google.com', {
@ -121,7 +121,7 @@ test('toString svg', function (t) {
})
test('toString browser svg', function (t) {
var file = path.join(__dirname, '/svgtag.expected.out')
const file = path.join(__dirname, '/svgtag.expected.out')
t.plan(3)
@ -146,7 +146,7 @@ test('toString browser svg', function (t) {
})
test('toString utf8', function (t) {
var expectedUtf8 = [
const expectedUtf8 = [
' ',
' ',
' █▀▀▀▀▀█ █ ▄█ ▀ █ █▀▀▀▀▀█ ',
@ -212,7 +212,7 @@ test('toString utf8', function (t) {
})
test('toString terminal', function (t) {
var expectedTerminal = fs.readFileSync(path.join(__dirname, '/terminal.expected.out')) + ''
const expectedTerminal = fs.readFileSync(path.join(__dirname, '/terminal.expected.out')) + ''
t.plan(3)

View file

@ -1,4 +1,4 @@
var nativePromise = global.Promise
const nativePromise = global.Promise
exports.removeNativePromise = function () {
if (global.Promise) {

View file

@ -1,5 +1,5 @@
var stream = require('stream')
var util = require('util')
const stream = require('stream')
const util = require('util')
function WritableStream () {
stream.Writable.call(this)

View file

@ -1,5 +1,5 @@
var test = require('tap').test
var pattern = require('core/alignment-pattern')
const test = require('tap').test
const pattern = require('core/alignment-pattern')
/**
* Row/column coordinates of the center module of each alignment pattern.
@ -7,7 +7,7 @@ var pattern = require('core/alignment-pattern')
*
* @type {Array}
*/
var EXPECTED_POSITION_TABLE = [
const EXPECTED_POSITION_TABLE = [
[],
[6, 18],
[6, 22],
@ -53,17 +53,17 @@ var EXPECTED_POSITION_TABLE = [
test('Alignment pattern - Row/Col coords', function (t) {
t.plan(40)
for (var i = 1; i <= 40; i++) {
var pos = pattern.getRowColCoords(i)
for (let i = 1; i <= 40; i++) {
const pos = pattern.getRowColCoords(i)
t.deepEqual(pos, EXPECTED_POSITION_TABLE[i - 1], 'Should return correct coords')
}
})
test('Alignment pattern - Positions', function (t) {
for (var i = 1; i <= 40; i++) {
var pos = pattern.getPositions(i)
var expectedPos = EXPECTED_POSITION_TABLE[i - 1]
var expectedLength = (Math.pow(expectedPos.length, 2) || 3) - 3
for (let i = 1; i <= 40; i++) {
const pos = pattern.getPositions(i)
const expectedPos = EXPECTED_POSITION_TABLE[i - 1]
const expectedLength = (Math.pow(expectedPos.length, 2) || 3) - 3
t.equal(pos.length, expectedLength, 'Should return correct number of positions')

View file

@ -1,9 +1,9 @@
var test = require('tap').test
var BitBuffer = require('core/bit-buffer')
var AlphanumericData = require('core/alphanumeric-data')
var Mode = require('core/mode')
const test = require('tap').test
const BitBuffer = require('core/bit-buffer')
const AlphanumericData = require('core/alphanumeric-data')
const Mode = require('core/mode')
var testData = [
const testData = [
{
data: 'A',
length: 1,
@ -26,13 +26,13 @@ var testData = [
test('Alphanumeric Data', function (t) {
testData.forEach(function (data) {
var alphanumericData = new AlphanumericData(data.data)
const alphanumericData = new AlphanumericData(data.data)
t.equal(alphanumericData.mode, Mode.ALPHANUMERIC, 'Mode should be ALPHANUMERIC')
t.equal(alphanumericData.getLength(), data.length, 'Should return correct length')
t.equal(alphanumericData.getBitsLength(), data.bitLength, 'Should return correct bit length')
var bitBuffer = new BitBuffer()
const bitBuffer = new BitBuffer()
alphanumericData.write(bitBuffer)
t.deepEqual(bitBuffer.buffer, data.dataBit, 'Should write correct data to buffer')
})

View file

@ -1,18 +1,18 @@
var test = require('tap').test
var BitBuffer = require('core/bit-buffer')
const test = require('tap').test
const BitBuffer = require('core/bit-buffer')
test('Bit Buffer', function (t) {
var testData = 0x41 // 'A'
var expectedDataBits = [false, true, false, false, false, false, false, true]
const testData = 0x41 // 'A'
const expectedDataBits = [false, true, false, false, false, false, false, true]
var bitBuffer = new BitBuffer()
const bitBuffer = new BitBuffer()
t.equal(bitBuffer.getLengthInBits(), 0, 'Initial length should be 0')
bitBuffer.put(testData, 8)
t.equal(bitBuffer.getLengthInBits(), 8, 'Length should be 8')
for (var i = 0; i < 8; i++) {
for (let i = 0; i < 8; i++) {
t.deepEqual(bitBuffer.get(i), expectedDataBits[i], 'Should return correct bit value')
}

View file

@ -1,11 +1,11 @@
var test = require('tap').test
var BitMatrix = require('core/bit-matrix')
const test = require('tap').test
const BitMatrix = require('core/bit-matrix')
test('Bit Matrix', function (t) {
t.throw(function () { BitMatrix(0) }, 'Should throw if size is 0')
t.throw(function () { BitMatrix(-1) }, 'Should throw if size less than 0')
var bm = new BitMatrix(2)
const bm = new BitMatrix(2)
t.equal(bm.size, 2, 'Should have correct size')
t.equal(bm.data.length, 4, 'Should correctly set buffer size')

View file

@ -1,25 +1,25 @@
var test = require('tap').test
var BitBuffer = require('core/bit-buffer')
var ByteData = require('core/byte-data')
var Mode = require('core/mode')
const test = require('tap').test
const BitBuffer = require('core/bit-buffer')
const ByteData = require('core/byte-data')
const Mode = require('core/mode')
test('Byte Data', function (t) {
var text = '1234'
var textBitLength = 32
var textByte = [49, 50, 51, 52] // 1, 2, 3, 4
var utf8Text = '\u00bd + \u00bc = \u00be' // 9 char, 12 byte
const text = '1234'
const textBitLength = 32
const textByte = [49, 50, 51, 52] // 1, 2, 3, 4
const utf8Text = '\u00bd + \u00bc = \u00be' // 9 char, 12 byte
var byteData = new ByteData(text)
const byteData = new ByteData(text)
t.equal(byteData.mode, Mode.BYTE, 'Mode should be BYTE')
t.equal(byteData.getLength(), text.length, 'Should return correct length')
t.equal(byteData.getBitsLength(), textBitLength, 'Should return correct bit length')
var bitBuffer = new BitBuffer()
const bitBuffer = new BitBuffer()
byteData.write(bitBuffer)
t.deepEqual(bitBuffer.buffer, textByte, 'Should write correct data to buffer')
var byteDataUtf8 = new ByteData(utf8Text)
const byteDataUtf8 = new ByteData(utf8Text)
t.equal(byteDataUtf8.getLength(), 12, 'Should return correct length for utf8 chars')
t.end()

View file

@ -1,21 +1,21 @@
var test = require('tap').test
var Utils = require('core/utils')
var Version = require('core/version')
var ECLevel = require('core/error-correction-level')
var ECCode = require('core/error-correction-code')
var Mode = require('core/mode')
const test = require('tap').test
const Utils = require('core/utils')
const Version = require('core/version')
const ECLevel = require('core/error-correction-level')
const ECCode = require('core/error-correction-code')
const Mode = require('core/mode')
test('Error correction codewords', function (t) {
var levels = [ECLevel.L, ECLevel.M, ECLevel.Q, ECLevel.H]
const levels = [ECLevel.L, ECLevel.M, ECLevel.Q, ECLevel.H]
for (var v = 1; v <= 40; v++) {
var totalCodewords = Utils.getSymbolTotalCodewords(v)
var reservedByte = Math.ceil((Mode.getCharCountIndicator(Mode.BYTE, v) + 4) / 8)
for (let v = 1; v <= 40; v++) {
const totalCodewords = Utils.getSymbolTotalCodewords(v)
const reservedByte = Math.ceil((Mode.getCharCountIndicator(Mode.BYTE, v) + 4) / 8)
for (var l = 0; l < levels.length; l++) {
var dataCodewords = Version.getCapacity(v, levels[l], Mode.BYTE) + reservedByte
for (let l = 0; l < levels.length; l++) {
const dataCodewords = Version.getCapacity(v, levels[l], Mode.BYTE) + reservedByte
var expectedCodewords = totalCodewords - dataCodewords
const expectedCodewords = totalCodewords - dataCodewords
t.equal(ECCode.getTotalCodewordsCount(v, levels[l]), expectedCodewords,
'Should return correct codewords number')
@ -29,10 +29,10 @@ test('Error correction codewords', function (t) {
})
test('Error correction blocks', function (t) {
var levels = [ECLevel.L, ECLevel.M, ECLevel.Q, ECLevel.H]
const levels = [ECLevel.L, ECLevel.M, ECLevel.Q, ECLevel.H]
for (var v = 1; v <= 40; v++) {
for (var l = 0; l < levels.length; l++) {
for (let v = 1; v <= 40; v++) {
for (let l = 0; l < levels.length; l++) {
t.ok(ECCode.getBlocksCount(v, levels[l]), 'Should return a positive number')
}
}

View file

@ -1,13 +1,13 @@
var test = require('tap').test
var ECLevel = require('core/error-correction-level')
const test = require('tap').test
const ECLevel = require('core/error-correction-level')
var EC_LEVELS = [ECLevel.L, ECLevel.M, ECLevel.Q, ECLevel.H]
const EC_LEVELS = [ECLevel.L, ECLevel.M, ECLevel.Q, ECLevel.H]
test('Error level from input value', function (t) {
var values = [['l', 'low'], ['m', 'medium'], ['q', 'quartile'], ['h', 'high']]
const values = [['l', 'low'], ['m', 'medium'], ['q', 'quartile'], ['h', 'high']]
for (var l = 0; l < values.length; l++) {
for (var i = 0; i < values[l].length; i++) {
for (let l = 0; l < values.length; l++) {
for (let i = 0; i < values[l].length; i++) {
t.equal(ECLevel.from(values[l][i]), EC_LEVELS[l])
t.equal(ECLevel.from(values[l][i].toUpperCase()), EC_LEVELS[l])
}
@ -21,7 +21,7 @@ test('Error level from input value', function (t) {
})
test('Error level validity', function (t) {
for (var l = 0; l < EC_LEVELS.length; l++) {
for (let l = 0; l < EC_LEVELS.length; l++) {
t.ok(ECLevel.isValid(EC_LEVELS[l]), 'Should return true if error level is valid')
}

View file

@ -1,8 +1,8 @@
var test = require('tap').test
var pattern = require('core/finder-pattern')
const test = require('tap').test
const pattern = require('core/finder-pattern')
test('Finder pattern', function (t) {
for (var i = 1; i <= 40; i++) {
for (let i = 1; i <= 40; i++) {
t.equal(pattern.getPositions(i).length, 3, 'Should always return 3 pattern positions')
}

View file

@ -1,9 +1,9 @@
var test = require('tap').test
var FormatInfo = require('core/format-info')
var ECLevel = require('core/error-correction-level')
var MaskPattern = require('core/mask-pattern')
const test = require('tap').test
const FormatInfo = require('core/format-info')
const ECLevel = require('core/error-correction-level')
const MaskPattern = require('core/mask-pattern')
var EXPECTED_FORMAT_BITS = [
const EXPECTED_FORMAT_BITS = [
[0x77c4, 0x72f3, 0x7daa, 0x789d, 0x662f, 0x6318, 0x6c41, 0x6976],
[0x5412, 0x5125, 0x5e7c, 0x5b4b, 0x45f9, 0x40ce, 0x4f97, 0x4aa0],
[0x355f, 0x3068, 0x3f31, 0x3a06, 0x24b4, 0x2183, 0x2eda, 0x2bed],
@ -11,12 +11,12 @@ var EXPECTED_FORMAT_BITS = [
]
test('Format encoded info', function (t) {
var levels = [ECLevel.L, ECLevel.M, ECLevel.Q, ECLevel.H]
var patterns = Object.keys(MaskPattern.Patterns).length
const levels = [ECLevel.L, ECLevel.M, ECLevel.Q, ECLevel.H]
const patterns = Object.keys(MaskPattern.Patterns).length
for (var l = 0; l < levels.length; l++) {
for (var p = 0; p < patterns; p++) {
var bch = FormatInfo.getEncodedBits(levels[l], p)
for (let l = 0; l < levels.length; l++) {
for (let p = 0; p < patterns; p++) {
const bch = FormatInfo.getEncodedBits(levels[l], p)
t.equal(bch, EXPECTED_FORMAT_BITS[l][p], 'Should return correct bits')
}
}

View file

@ -1,10 +1,10 @@
var test = require('tap').test
var GF = require('core/galois-field')
const test = require('tap').test
const GF = require('core/galois-field')
test('Galois Field', function (t) {
t.throw(function () { GF.log(0) }, 'Should throw for log(n) with n < 1')
for (var i = 1; i < 255; i++) {
for (let i = 1; i < 255; i++) {
t.equal(GF.log(GF.exp(i)), i, 'log and exp should be one the inverse of the other')
t.equal(GF.exp(GF.log(i)), i, 'exp and log should be one the inverse of the other')
}
@ -13,7 +13,7 @@ test('Galois Field', function (t) {
t.equal(GF.mul(1, 0), 0, 'Should return 0 if second param is 0')
t.equal(GF.mul(0, 0), 0, 'Should return 0 if both params are 0')
for (var j = 1; j < 255; j++) {
for (let j = 1; j < 255; j++) {
t.equal(GF.mul(j, 255 - j), GF.mul(255 - j, j), 'Multiplication should be commutative')
}

View file

@ -1,24 +1,24 @@
var test = require('tap').test
var BitBuffer = require('core/bit-buffer')
var KanjiData = require('core/kanji-data')
var Mode = require('core/mode')
var toSJIS = require('helper/to-sjis')
const test = require('tap').test
const BitBuffer = require('core/bit-buffer')
const KanjiData = require('core/kanji-data')
const Mode = require('core/mode')
const toSJIS = require('helper/to-sjis')
require('core/utils').setToSJISFunction(toSJIS)
test('Kanji Data', function (t) {
var data = '漢字漾癶'
var length = 4
var bitLength = 52 // length * 13
const data = '漢字漾癶'
const length = 4
const bitLength = 52 // length * 13
var dataBit = [57, 250, 134, 174, 129, 134, 0]
const dataBit = [57, 250, 134, 174, 129, 134, 0]
var kanjiData = new KanjiData(data)
let kanjiData = new KanjiData(data)
t.equal(kanjiData.mode, Mode.KANJI, 'Mode should be KANJI')
t.equal(kanjiData.getLength(), length, 'Should return correct length')
t.equal(kanjiData.getBitsLength(), bitLength, 'Should return correct bit length')
var bitBuffer = new BitBuffer()
let bitBuffer = new BitBuffer()
kanjiData.write(bitBuffer)
t.deepEqual(bitBuffer.buffer, dataBit, 'Should write correct data to buffer')

View file

@ -1,15 +1,15 @@
var test = require('tap').test
var BitMatrix = require('core/bit-matrix')
var MaskPattern = require('core/mask-pattern')
const test = require('tap').test
const BitMatrix = require('core/bit-matrix')
const MaskPattern = require('core/mask-pattern')
test('Mask pattern - Pattern references', function (t) {
var patternsCount = Object.keys(MaskPattern.Patterns).length
const patternsCount = Object.keys(MaskPattern.Patterns).length
t.equals(patternsCount, 8, 'Should return 8 patterns')
t.end()
})
var expectedPattern000 = [
const expectedPattern000 = [
1, 0, 1, 0, 1, 0,
0, 1, 0, 1, 0, 1,
1, 0, 1, 0, 1, 0,
@ -18,7 +18,7 @@ var expectedPattern000 = [
0, 1, 0, 1, 0, 1
]
var expectedPattern001 = [
const expectedPattern001 = [
1, 1, 1, 1, 1, 1,
0, 0, 0, 0, 0, 0,
1, 1, 1, 1, 1, 1,
@ -27,7 +27,7 @@ var expectedPattern001 = [
0, 0, 0, 0, 0, 0
]
var expectedPattern010 = [
const expectedPattern010 = [
1, 0, 0, 1, 0, 0,
1, 0, 0, 1, 0, 0,
1, 0, 0, 1, 0, 0,
@ -36,7 +36,7 @@ var expectedPattern010 = [
1, 0, 0, 1, 0, 0
]
var expectedPattern011 = [
const expectedPattern011 = [
1, 0, 0, 1, 0, 0,
0, 0, 1, 0, 0, 1,
0, 1, 0, 0, 1, 0,
@ -45,7 +45,7 @@ var expectedPattern011 = [
0, 1, 0, 0, 1, 0
]
var expectedPattern100 = [
const expectedPattern100 = [
1, 1, 1, 0, 0, 0,
1, 1, 1, 0, 0, 0,
0, 0, 0, 1, 1, 1,
@ -54,7 +54,7 @@ var expectedPattern100 = [
1, 1, 1, 0, 0, 0
]
var expectedPattern101 = [
const expectedPattern101 = [
1, 1, 1, 1, 1, 1,
1, 0, 0, 0, 0, 0,
1, 0, 0, 1, 0, 0,
@ -63,7 +63,7 @@ var expectedPattern101 = [
1, 0, 0, 0, 0, 0
]
var expectedPattern110 = [
const expectedPattern110 = [
1, 1, 1, 1, 1, 1,
1, 1, 1, 0, 0, 0,
1, 1, 0, 1, 1, 0,
@ -72,7 +72,7 @@ var expectedPattern110 = [
1, 0, 0, 0, 1, 1
]
var expectedPattern111 = [
const expectedPattern111 = [
1, 0, 1, 0, 1, 0,
0, 0, 0, 1, 1, 1,
1, 0, 0, 0, 1, 1,
@ -100,19 +100,19 @@ test('MaskPattern from value', function (t) {
})
test('Mask pattern - Apply mask', function (t) {
var patterns = Object.keys(MaskPattern.Patterns).length
var expectedPatterns = [
const patterns = Object.keys(MaskPattern.Patterns).length
const expectedPatterns = [
expectedPattern000, expectedPattern001, expectedPattern010, expectedPattern011,
expectedPattern100, expectedPattern101, expectedPattern110, expectedPattern111
]
for (var p = 0; p < patterns; p++) {
var matrix = new BitMatrix(6)
for (let p = 0; p < patterns; p++) {
const matrix = new BitMatrix(6)
MaskPattern.applyMask(p, matrix)
t.deepEqual(matrix.data, new Uint8Array(expectedPatterns[p]), 'Should return correct pattern')
}
matrix = new BitMatrix(2)
const matrix = new BitMatrix(2)
matrix.set(0, 0, false, true)
matrix.set(0, 1, false, true)
matrix.set(1, 0, false, true)
@ -127,7 +127,7 @@ test('Mask pattern - Apply mask', function (t) {
})
test('Mask pattern - Penalty N1', function (t) {
var matrix = new BitMatrix(11)
let matrix = new BitMatrix(11)
matrix.data = [
1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1,
1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1,
@ -170,7 +170,7 @@ test('Mask pattern - Penalty N1', function (t) {
})
test('Mask pattern - Penalty N2', function (t) {
var matrix = new BitMatrix(8)
let matrix = new BitMatrix(8)
matrix.data = [
1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 0, 0, 0, 1, 1,
@ -205,7 +205,7 @@ test('Mask pattern - Penalty N2', function (t) {
})
test('Mask pattern - Penalty N3', function (t) {
var matrix = new BitMatrix(11)
const matrix = new BitMatrix(11)
matrix.data = [
0, 1, 1, 0, 0, 1, 0, 1, 1, 1, 1,
0, 0, 0, 0, 1, 0, 1, 1, 1, 0, 1,
@ -244,19 +244,19 @@ test('Mask pattern - Penalty N3', function (t) {
})
test('Mask pattern - Penalty N4', function (t) {
var matrix = new BitMatrix(10)
const matrix = new BitMatrix(10)
matrix.data = new Array(50).fill(1).concat(new Array(50).fill(0))
t.equals(MaskPattern.getPenaltyN4(matrix), 0,
'Should return correct penalty points')
var matrix2 = new BitMatrix(21)
const matrix2 = new BitMatrix(21)
matrix2.data = new Array(190).fill(1).concat(new Array(251).fill(0))
t.equals(MaskPattern.getPenaltyN4(matrix2), 10,
'Should return correct penalty points')
var matrix3 = new BitMatrix(10)
const matrix3 = new BitMatrix(10)
matrix3.data = new Array(22).fill(1).concat(new Array(78).fill(0))
t.equals(MaskPattern.getPenaltyN4(matrix3), 50,
@ -266,7 +266,7 @@ test('Mask pattern - Penalty N4', function (t) {
})
test('Mask pattern - Best mask', function (t) {
var matrix = new BitMatrix(11)
const matrix = new BitMatrix(11)
matrix.data = [
0, 1, 1, 0, 0, 1, 0, 1, 1, 1, 1,
0, 0, 0, 0, 1, 0, 1, 1, 1, 0, 1,
@ -281,7 +281,7 @@ test('Mask pattern - Best mask', function (t) {
1, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0
]
var mask = MaskPattern.getBestMask(matrix, function () {})
const mask = MaskPattern.getBestMask(matrix, function () {})
t.ok(!isNaN(mask), 'Should return a number')
t.ok(mask >= 0 && mask < 8,

View file

@ -1,8 +1,8 @@
var test = require('tap').test
var Mode = require('core/mode')
const test = require('tap').test
const Mode = require('core/mode')
test('Mode bits', function (t) {
var EXPECTED_BITS = {
const EXPECTED_BITS = {
numeric: 1,
alphanumeric: 2,
byte: 4,
@ -20,14 +20,14 @@ test('Mode bits', function (t) {
})
test('Char count bits', function (t) {
var EXPECTED_BITS = {
const EXPECTED_BITS = {
numeric: [10, 12, 14],
alphanumeric: [9, 11, 13],
byte: [8, 16, 16],
kanji: [8, 10, 12]
}
var v
let v
for (v = 1; v < 10; v++) {
t.equal(Mode.getCharCountIndicator(Mode.NUMERIC, v), EXPECTED_BITS.numeric[0])
t.equal(Mode.getCharCountIndicator(Mode.ALPHANUMERIC, v), EXPECTED_BITS.alphanumeric[0])
@ -60,7 +60,7 @@ test('Char count bits', function (t) {
test('Best mode', function (t) {
/* eslint-disable quote-props */
var EXPECTED_MODE = {
const EXPECTED_MODE = {
'12345': Mode.NUMERIC,
'abcde': Mode.BYTE,
'1234a': Mode.BYTE,
@ -94,14 +94,14 @@ test('Is valid', function (t) {
})
test('From value', function (t) {
var modes = [
const modes = [
{ name: 'numeric', mode: Mode.NUMERIC },
{ name: 'alphanumeric', mode: Mode.ALPHANUMERIC },
{ name: 'kanji', mode: Mode.KANJI },
{ name: 'byte', mode: Mode.BYTE }
]
for (var m = 0; m < modes.length; m++) {
for (let m = 0; m < modes.length; m++) {
t.equal(Mode.from(modes[m].name), modes[m].mode)
t.equal(Mode.from(modes[m].name.toUpperCase()), modes[m].mode)
t.equal(Mode.from(modes[m].mode), modes[m].mode)

View file

@ -1,9 +1,9 @@
var test = require('tap').test
var BitBuffer = require('core/bit-buffer')
var NumericData = require('core/numeric-data')
var Mode = require('core/mode')
const test = require('tap').test
const BitBuffer = require('core/bit-buffer')
const NumericData = require('core/numeric-data')
const Mode = require('core/mode')
var testData = [
const testData = [
{
data: 8,
length: 1,
@ -39,13 +39,13 @@ var testData = [
test('Numeric Data', function (t) {
testData.forEach(function (data) {
var numericData = new NumericData(data.data)
const numericData = new NumericData(data.data)
t.equal(numericData.mode, Mode.NUMERIC, 'Mode should be NUMERIC')
t.equal(numericData.getLength(), data.length, 'Should return correct length')
t.equal(numericData.getBitsLength(), data.bitLength, 'Should return correct bit length')
var bitBuffer = new BitBuffer()
const bitBuffer = new BitBuffer()
numericData.write(bitBuffer)
t.deepEqual(bitBuffer.buffer, data.dataBit, 'Should write correct data to buffer')
})

View file

@ -1,12 +1,12 @@
var test = require('tap').test
var Poly = require('core/polynomial')
const test = require('tap').test
const Poly = require('core/polynomial')
test('Generator polynomial', function (t) {
var result = Poly.generateECPolynomial(0)
const result = Poly.generateECPolynomial(0)
t.ok(result instanceof Uint8Array, 'Should return an Uint8Array')
t.deepEqual(result, new Uint8Array([1]), 'Should return coeff [1] for polynomial of degree 0')
for (var e = 2; e <= 68; e++) {
for (let e = 2; e <= 68; e++) {
t.equal(Poly.generateECPolynomial(e).length, e + 1, 'Should return a number of coefficients equal to (degree + 1)')
}
@ -14,10 +14,10 @@ test('Generator polynomial', function (t) {
})
test('Polynomial', function (t) {
var p1 = [0, 1, 2, 3, 4]
var p2 = [5, 6]
const p1 = [0, 1, 2, 3, 4]
const p2 = [5, 6]
var result = Poly.mul(p1, p2)
let result = Poly.mul(p1, p2)
t.ok(result instanceof Uint8Array, 'Should return an Uint8Array')
t.equal(result.length, 6, 'Should return correct number of coefficients')

View file

@ -1,15 +1,15 @@
var test = require('tap').test
var ECLevel = require('core/error-correction-level')
var Version = require('core/version')
var QRCode = require('core/qrcode')
var toSJIS = require('helper/to-sjis')
const test = require('tap').test
const ECLevel = require('core/error-correction-level')
const Version = require('core/version')
const QRCode = require('core/qrcode')
const toSJIS = require('helper/to-sjis')
test('QRCode interface', function (t) {
t.type(QRCode.create, 'function', 'Should have "create" function')
t.throw(function () { QRCode.create() }, 'Should throw if no data is provided')
t.notThrow(function () { QRCode.create('1234567') }, 'Should not throw')
var qr = QRCode.create('a123456A', {
let qr = QRCode.create('a123456A', {
version: 1,
maskPattern: 1,
errorCorrectionLevel: 'H'
@ -17,7 +17,7 @@ test('QRCode interface', function (t) {
t.equal(qr.modules.size, 21, 'Should return correct modules count')
t.equal(qr.maskPattern, 1, 'Should return correct mask pattern')
var darkModule = qr.modules.get(qr.modules.size - 8, 8)
const darkModule = qr.modules.get(qr.modules.size - 8, 8)
t.ok(darkModule, 'Should have a dark module at coords [size-8][8]')
t.throw(function () {
@ -46,16 +46,16 @@ test('QRCode interface', function (t) {
})
test('QRCode error correction', function (t) {
var qr
var ecValues = [
let qr
const ecValues = [
{ name: ['l', 'low'], level: ECLevel.L },
{ name: ['m', 'medium'], level: ECLevel.M },
{ name: ['q', 'quartile'], level: ECLevel.Q },
{ name: ['h', 'high'], level: ECLevel.H }
]
for (var l = 0; l < ecValues.length; l++) {
for (var i = 0; i < ecValues[l].name.length; i++) {
for (let l = 0; l < ecValues.length; l++) {
for (let i = 0; i < ecValues[l].name.length; i++) {
t.notThrow(function () {
qr = QRCode.create('ABCDEFG', { errorCorrectionLevel: ecValues[l].name[i] })
}, 'Should accept errorCorrectionLevel value: ' + ecValues[l].name[i])
@ -79,7 +79,7 @@ test('QRCode error correction', function (t) {
})
test('QRCode version', function (t) {
var qr = QRCode.create('data', { version: 9, errorCorrectionLevel: ECLevel.M })
let qr = QRCode.create('data', { version: 9, errorCorrectionLevel: ECLevel.M })
t.equal(qr.version, 9, 'Should create qrcode with correct version')
t.equal(qr.errorCorrectionLevel, ECLevel.M, 'Should set correct EC level')
@ -102,7 +102,7 @@ test('QRCode version', function (t) {
})
test('QRCode capacity', function (t) {
var qr
let qr
qr = QRCode.create([{ data: 'abcdefg', mode: 'byte' }])
t.equal(qr.version, 1, 'Should contain 7 byte characters')

View file

@ -1,8 +1,8 @@
var test = require('tap').test
var RS = require('core/reed-solomon-encoder')
const test = require('tap').test
const RS = require('core/reed-solomon-encoder')
test('Reed-Solomon encoder', function (t) {
var enc = new RS()
let enc = new RS()
t.notOk(enc.genPoly, 'Should have an undefined generator polynomial')
t.throw(function () { enc.encode([]) }, 'Should throw if generator polynomial is undefined')
@ -11,11 +11,11 @@ test('Reed-Solomon encoder', function (t) {
t.equal(enc.degree, 2, 'Should set correct degree value')
t.ok(enc.genPoly, 'Generator polynomial should be defined')
var result = enc.encode(new Uint8Array([48, 49, 50, 51, 52]))
const result = enc.encode(new Uint8Array([48, 49, 50, 51, 52]))
t.equal(result.length, 2, 'Should return a number of codewords equal to gen poly degree')
enc = new RS(2)
var genPoly = enc.genPoly
const genPoly = enc.genPoly
t.equal(enc.degree, 2, 'Should set correct degree value')
t.ok(genPoly, 'Generator polynomial should be defined')

View file

@ -1,5 +1,5 @@
var test = require('tap').test
var Regex = require('core/regex')
const test = require('tap').test
const Regex = require('core/regex')
test('Regex', function (t) {
t.ok(Regex.NUMERIC instanceof RegExp,

View file

@ -1,13 +1,13 @@
var test = require('tap').test
var Mode = require('core/mode')
var Segments = require('core/segments')
var NumericData = require('core/numeric-data')
var AlphanumericData = require('core/alphanumeric-data')
var ByteData = require('core/byte-data')
var toSJIS = require('helper/to-sjis')
var Utils = require('core/utils')
const test = require('tap').test
const Mode = require('core/mode')
const Segments = require('core/segments')
const NumericData = require('core/numeric-data')
const AlphanumericData = require('core/alphanumeric-data')
const ByteData = require('core/byte-data')
const toSJIS = require('helper/to-sjis')
const Utils = require('core/utils')
var testData = [
let testData = [
{
input: '1A1',
result: [{ data: '1A1', mode: Mode.ALPHANUMERIC }]
@ -135,7 +135,7 @@ var testData = [
}
]
var kanjiTestData = [
const kanjiTestData = [
{
input: '乂ЁЖぞβ',
result: [{ data: '乂ЁЖぞβ', mode: Mode.KANJI }]
@ -209,7 +209,7 @@ test('Segments optimization', function (t) {
})
test('Segments raw split', function (t) {
var splitted = [
const splitted = [
new ByteData('abc'),
new AlphanumericData('DEF'),
new NumericData('123')

View file

@ -1,11 +1,11 @@
var test = require('tap').test
var Utils = require('core/utils')
const test = require('tap').test
const Utils = require('core/utils')
/**
* QR Code sizes. Each element refers to a version
* @type {Array}
*/
var EXPECTED_SYMBOL_SIZES = [
const EXPECTED_SYMBOL_SIZES = [
21, 25, 29, 33, 37, 41, 45,
49, 53, 57, 61, 65, 69, 73,
77, 81, 85, 89, 93, 97, 101,
@ -18,7 +18,7 @@ test('Symbol size', function (t) {
t.throws(function () { Utils.getSymbolSize(0) }, 'Should throw if version is not in range')
t.throws(function () { Utils.getSymbolSize(41) }, 'Should throw if version is not in range')
for (var i = 1; i <= 40; i++) {
for (let i = 1; i <= 40; i++) {
t.equal(Utils.getSymbolSize(i), EXPECTED_SYMBOL_SIZES[i - 1], 'Should return correct symbol size')
}
@ -26,7 +26,7 @@ test('Symbol size', function (t) {
})
test('Symbol codewords', function (t) {
for (var i = 1; i <= 40; i++) {
for (let i = 1; i <= 40; i++) {
t.ok(Utils.getSymbolTotalCodewords(i), 'Should return positive number')
}
@ -34,7 +34,7 @@ test('Symbol codewords', function (t) {
})
test('BCH Digit', function (t) {
var testData = [
const testData = [
{ data: 0, bch: 0 },
{ data: 1, bch: 1 },
{ data: 2, bch: 2 },
@ -57,7 +57,7 @@ test('Set/Get SJIS function', function (t) {
t.notOk(Utils.isKanjiModeEnabled(),
'Kanji mode should be disabled if "toSJIS" function is not set')
var testFunc = function testFunc (c) {
const testFunc = function testFunc (c) {
return 'test_' + c
}

View file

@ -1,16 +1,16 @@
var test = require('tap').test
var Version = require('core/version')
var VersionCheck = require('core/version-check')
var ECLevel = require('core/error-correction-level')
var Mode = require('core/mode')
var NumericData = require('core/numeric-data')
var AlphanumericData = require('core/alphanumeric-data')
var KanjiData = require('core/kanji-data')
var ByteData = require('core/byte-data')
const test = require('tap').test
const Version = require('core/version')
const VersionCheck = require('core/version-check')
const ECLevel = require('core/error-correction-level')
const Mode = require('core/mode')
const NumericData = require('core/numeric-data')
const AlphanumericData = require('core/alphanumeric-data')
const KanjiData = require('core/kanji-data')
const ByteData = require('core/byte-data')
var EC_LEVELS = [ECLevel.L, ECLevel.M, ECLevel.Q, ECLevel.H]
const EC_LEVELS = [ECLevel.L, ECLevel.M, ECLevel.Q, ECLevel.H]
var EXPECTED_NUMERIC_CAPACITY = [
const EXPECTED_NUMERIC_CAPACITY = [
[41, 34, 27, 17], [77, 63, 48, 34], [127, 101, 77, 58], [187, 149, 111, 82],
[255, 202, 144, 106], [322, 255, 178, 139], [370, 293, 207, 154], [461, 365, 259, 202],
[552, 432, 312, 235], [652, 513, 364, 288], [772, 604, 427, 331], [883, 691, 489, 374],
@ -23,7 +23,7 @@ var EXPECTED_NUMERIC_CAPACITY = [
[6153, 4775, 3417, 2625], [6479, 5039, 3599, 2735], [6743, 5313, 3791, 2927], [7089, 5596, 3993, 3057]
]
var EXPECTED_ALPHANUMERIC_CAPACITY = [
const EXPECTED_ALPHANUMERIC_CAPACITY = [
[25, 20, 16, 10], [47, 38, 29, 20], [77, 61, 47, 35], [114, 90, 67, 50],
[154, 122, 87, 64], [195, 154, 108, 84], [224, 178, 125, 93], [279, 221, 157, 122],
[335, 262, 189, 143], [395, 311, 221, 174], [468, 366, 259, 200], [535, 419, 296, 227],
@ -36,7 +36,7 @@ var EXPECTED_ALPHANUMERIC_CAPACITY = [
[3729, 2894, 2071, 1591], [3927, 3054, 2181, 1658], [4087, 3220, 2298, 1774], [4296, 3391, 2420, 1852]
]
var EXPECTED_KANJI_CAPACITY = [
const EXPECTED_KANJI_CAPACITY = [
[10, 8, 7, 4], [20, 16, 12, 8], [32, 26, 20, 15], [48, 38, 28, 21],
[65, 52, 37, 27], [82, 65, 45, 36], [95, 75, 53, 39], [118, 93, 66, 52],
[141, 111, 80, 60], [167, 131, 93, 74], [198, 155, 109, 85], [226, 177, 125, 96],
@ -49,7 +49,7 @@ var EXPECTED_KANJI_CAPACITY = [
[1577, 1224, 876, 673], [1661, 1292, 923, 701], [1729, 1362, 972, 750], [1817, 1435, 1024, 784]
]
var EXPECTED_BYTE_CAPACITY = [
const EXPECTED_BYTE_CAPACITY = [
[17, 14, 11, 7], [32, 26, 20, 14], [53, 42, 32, 24], [78, 62, 46, 34],
[106, 84, 60, 44], [134, 106, 74, 58], [154, 122, 86, 64], [192, 152, 108, 84],
[230, 180, 130, 98], [271, 213, 151, 119], [321, 251, 177, 137], [367, 287, 203, 155],
@ -62,7 +62,7 @@ var EXPECTED_BYTE_CAPACITY = [
[2563, 1989, 1423, 1093], [2699, 2099, 1499, 1139], [2809, 2213, 1579, 1219], [2953, 2331, 1663, 1273]
]
var EXPECTED_VERSION_BITS = [
const EXPECTED_VERSION_BITS = [
0x07C94, 0x085BC, 0x09A99, 0x0A4D3, 0x0BBF6, 0x0C762, 0x0D847, 0x0E60D,
0x0F928, 0x10B78, 0x1145D, 0x12A17, 0x13532, 0x149A6, 0x15683, 0x168C9,
0x177EC, 0x18EC4, 0x191E1, 0x1AFAB, 0x1B08E, 0x1CC1A, 0x1D33F, 0x1ED75,
@ -94,8 +94,8 @@ test('Version capacity', function (t) {
t.throws(function () { Version.getCapacity(0) }, 'Should throw if version is not in range')
t.throws(function () { Version.getCapacity(41) }, 'Should throw if version is not in range')
for (var l = 0; l < EC_LEVELS.length; l++) {
for (var i = 1; i <= 40; i++) {
for (let l = 0; l < EC_LEVELS.length; l++) {
for (let i = 1; i <= 40; i++) {
t.equal(Version.getCapacity(i, EC_LEVELS[l], Mode.NUMERIC),
EXPECTED_NUMERIC_CAPACITY[i - 1][l], 'Should return correct numeric mode capacity')
@ -118,10 +118,10 @@ test('Version capacity', function (t) {
test('Version best match', function (t) {
function testBestVersionForCapacity (expectedCapacity, DataCtor) {
for (var v = 0; v < 40; v++) {
for (var l = 0; l < EC_LEVELS.length; l++) {
var capacity = expectedCapacity[v][l]
var data = new DataCtor(new Array(capacity + 1).join('-'))
for (let v = 0; v < 40; v++) {
for (let l = 0; l < EC_LEVELS.length; l++) {
const capacity = expectedCapacity[v][l]
const data = new DataCtor(new Array(capacity + 1).join('-'))
t.equal(Version.getBestVersionForData(data, EC_LEVELS[l]), v + 1, 'Should return best version')
t.equal(Version.getBestVersionForData([data], EC_LEVELS[l]), v + 1, 'Should return best version')
@ -135,10 +135,10 @@ test('Version best match', function (t) {
}
}
for (var i = 0; i < EC_LEVELS.length; i++) {
var exceededCapacity = expectedCapacity[39][i] + 1
var tooBigData = new DataCtor(new Array(exceededCapacity + 1).join('-'))
var tooBigDataArray = [
for (let i = 0; i < EC_LEVELS.length; i++) {
const exceededCapacity = expectedCapacity[39][i] + 1
const tooBigData = new DataCtor(new Array(exceededCapacity + 1).join('-'))
const tooBigDataArray = [
new DataCtor(new Array(Math.floor(exceededCapacity / 2)).join('-')),
new DataCtor(new Array(Math.floor(exceededCapacity / 2) + 1).join('-'))
]
@ -167,7 +167,7 @@ test('Version best match', function (t) {
})
test('Version encoded info', function (t) {
var v
let v
for (v = 0; v < 7; v++) {
t.throws(function () { Version.getEncodedBits(v) },
@ -175,7 +175,7 @@ test('Version encoded info', function (t) {
}
for (v = 7; v <= 40; v++) {
var bch = Version.getEncodedBits(v)
const bch = Version.getEncodedBits(v)
t.equal(bch, EXPECTED_VERSION_BITS[v - 7], 'Should return correct bits')
}

View file

@ -1,5 +1,5 @@
var test = require('tap').test
var toSJIS = require('helper/to-sjis')
const test = require('tap').test
const toSJIS = require('helper/to-sjis')
test('SJIS from char', function (t) {
t.notOk(toSJIS(''),

View file

@ -1,7 +1,7 @@
var test = require('tap').test
var { Canvas, createCanvas } = require('canvas')
var QRCode = require('core/qrcode')
var CanvasRenderer = require('renderer/canvas')
const test = require('tap').test
const { Canvas, createCanvas } = require('canvas')
const QRCode = require('core/qrcode')
const CanvasRenderer = require('renderer/canvas')
test('CanvasRenderer interface', function (t) {
t.type(CanvasRenderer.render, 'function',
@ -23,8 +23,8 @@ test('CanvasRenderer render', function (t) {
}
}
var sampleQrData = QRCode.create('sample text', { version: 2 })
var canvasEl
const sampleQrData = QRCode.create('sample text', { version: 2 })
let canvasEl
t.notThrow(function () { canvasEl = CanvasRenderer.render(sampleQrData) },
'Should not throw if canvas is not provided')
@ -55,8 +55,8 @@ test('CanvasRenderer render', function (t) {
})
test('CanvasRenderer render to provided canvas', function (t) {
var sampleQrData = QRCode.create('sample text', { version: 2 })
var canvasEl = createCanvas(200, 200)
const sampleQrData = QRCode.create('sample text', { version: 2 })
const canvasEl = createCanvas(200, 200)
t.notThrow(function () { CanvasRenderer.render(sampleQrData, canvasEl) },
'Should not throw with only qrData and canvas param')
@ -88,8 +88,8 @@ test('CanvasRenderer renderToDataURL', function (t) {
}
}
var sampleQrData = QRCode.create('sample text', { version: 2 })
var url
const sampleQrData = QRCode.create('sample text', { version: 2 })
let url
t.notThrow(function () { url = CanvasRenderer.renderToDataURL(sampleQrData) },
'Should not throw if canvas is not provided')
@ -108,7 +108,7 @@ test('CanvasRenderer renderToDataURL', function (t) {
t.equal(url.split(',')[0], 'data:image/png;base64',
'Should have correct header')
var b64png = url.split(',')[1]
const b64png = url.split(',')[1]
t.equal(b64png.length % 4, 0,
'Should have a correct length')
@ -117,9 +117,9 @@ test('CanvasRenderer renderToDataURL', function (t) {
})
test('CanvasRenderer renderToDataURL to provided canvas', function (t) {
var sampleQrData = QRCode.create('sample text', { version: 2 })
var canvasEl = createCanvas(200, 200)
var url
const sampleQrData = QRCode.create('sample text', { version: 2 })
const canvasEl = createCanvas(200, 200)
let url
t.notThrow(function () {
url = CanvasRenderer.renderToDataURL(sampleQrData, canvasEl)
@ -139,7 +139,7 @@ test('CanvasRenderer renderToDataURL to provided canvas', function (t) {
t.equal(url.split(',')[0], 'data:image/png;base64',
'Should have correct header')
var b64png = url.split(',')[1]
const b64png = url.split(',')[1]
t.equal(b64png.length % 4, 0,
'Should have a correct length')

View file

@ -1,10 +1,10 @@
var test = require('tap').test
var sinon = require('sinon')
var fs = require('fs')
var QRCode = require('core/qrcode')
var PngRenderer = require('renderer/png')
var PNG = require('pngjs').PNG
var StreamMock = require('../../mocks/writable-stream')
const test = require('tap').test
const sinon = require('sinon')
const fs = require('fs')
const QRCode = require('core/qrcode')
const PngRenderer = require('renderer/png')
const PNG = require('pngjs').PNG
const StreamMock = require('../../mocks/writable-stream')
test('PNG renderer interface', function (t) {
t.type(PngRenderer.render, 'function',
@ -23,8 +23,8 @@ test('PNG renderer interface', function (t) {
})
test('PNG render', function (t) {
var sampleQrData = QRCode.create('sample text', { version: 2 })
var png
const sampleQrData = QRCode.create('sample text', { version: 2 })
let png
t.notThrow(function () { png = PngRenderer.render(sampleQrData) },
'Should not throw with only qrData param')
@ -57,7 +57,7 @@ test('PNG render', function (t) {
})
test('PNG renderToDataURL', function (t) {
var sampleQrData = QRCode.create('sample text', { version: 2 })
const sampleQrData = QRCode.create('sample text', { version: 2 })
t.plan(6)
@ -79,7 +79,7 @@ test('PNG renderToDataURL', function (t) {
t.equal(url.split(',')[0], 'data:image/png;base64',
'Should have correct header')
var b64png = url.split(',')[1]
const b64png = url.split(',')[1]
t.equal(b64png.length % 4, 0,
'Should have a correct length')
}
@ -87,9 +87,9 @@ test('PNG renderToDataURL', function (t) {
})
test('PNG renderToFile', function (t) {
var sampleQrData = QRCode.create('sample text', { version: 2 })
var fileName = 'qrimage.png'
var fsStub = sinon.stub(fs, 'createWriteStream')
const sampleQrData = QRCode.create('sample text', { version: 2 })
const fileName = 'qrimage.png'
let fsStub = sinon.stub(fs, 'createWriteStream')
fsStub.returns(new StreamMock())
t.plan(6)
@ -126,7 +126,7 @@ test('PNG renderToFile', function (t) {
})
test('PNG renderToFileStream', function (t) {
var sampleQrData = QRCode.create('sample text', { version: 2 })
const sampleQrData = QRCode.create('sample text', { version: 2 })
t.notThrow(function () {
PngRenderer.renderToFileStream(new StreamMock(), sampleQrData)

View file

@ -1,20 +1,20 @@
var test = require('tap').test
var sinon = require('sinon')
var fs = require('fs')
var htmlparser = require('htmlparser2')
var QRCode = require('core/qrcode')
var SvgRenderer = require('renderer/svg')
const test = require('tap').test
const sinon = require('sinon')
const fs = require('fs')
const htmlparser = require('htmlparser2')
const QRCode = require('core/qrcode')
const SvgRenderer = require('renderer/svg')
function getExpectedViewbox (size, margin) {
var expectedQrCodeSize = size + margin * 2
const expectedQrCodeSize = size + margin * 2
return '0 0 ' + expectedQrCodeSize + ' ' + expectedQrCodeSize
}
function testSvgFragment (t, svgFragment, expectedTags) {
return new Promise(function (resolve, reject) {
var parser = new htmlparser.Parser({
const parser = new htmlparser.Parser({
onopentag: function (name, attribs) {
var tag = expectedTags.shift()
const tag = expectedTags.shift()
t.equal(tag.name, name,
'Should have a ' + tag.name + ' tag')
@ -40,7 +40,7 @@ function testSvgFragment (t, svgFragment, expectedTags) {
}
function buildTest (t, data, opts, expectedTags) {
var svg = SvgRenderer.render(data, opts)
const svg = SvgRenderer.render(data, opts)
return testSvgFragment(t, svg, expectedTags.slice())
}
@ -55,10 +55,10 @@ test('svgrender interface', function (t) {
})
test('Svg render', function (t) {
var tests = []
const tests = []
var data = QRCode.create('sample text', { version: 2 })
var size = data.modules.size
const data = QRCode.create('sample text', { version: 2 })
const size = data.modules.size
tests.push(buildTest(t, data, {
scale: 4,
@ -141,9 +141,9 @@ test('Svg render', function (t) {
})
test('Svg renderToFile', function (t) {
var sampleQrData = QRCode.create('sample text', { version: 2 })
var fileName = 'qrimage.svg'
var fsStub = sinon.stub(fs, 'writeFile').callsArg(2)
const sampleQrData = QRCode.create('sample text', { version: 2 })
const fileName = 'qrimage.svg'
let fsStub = sinon.stub(fs, 'writeFile').callsArg(2)
t.plan(5)

View file

@ -1,6 +1,6 @@
var test = require('tap').test
var QRCode = require('core/qrcode')
var TerminalRenderer = require('renderer/terminal')
const test = require('tap').test
const QRCode = require('core/qrcode')
const TerminalRenderer = require('renderer/terminal')
test('TerminalRenderer interface', function (t) {
t.type(TerminalRenderer.render, 'function',
@ -10,8 +10,8 @@ test('TerminalRenderer interface', function (t) {
})
test('TerminalRenderer render', function (t) {
var sampleQrData = QRCode.create('sample text', { version: 2 })
var str
const sampleQrData = QRCode.create('sample text', { version: 2 })
let str
t.notThrow(function () { str = TerminalRenderer.render(sampleQrData) },
'Should not throw with only qrData param')

View file

@ -1,8 +1,8 @@
var test = require('tap').test
var sinon = require('sinon')
var fs = require('fs')
var QRCode = require('core/qrcode')
var Utf8Renderer = require('renderer/utf8')
const test = require('tap').test
const sinon = require('sinon')
const fs = require('fs')
const QRCode = require('core/qrcode')
const Utf8Renderer = require('renderer/utf8')
test('Utf8Renderer interface', function (t) {
t.type(Utf8Renderer.render, 'function',
@ -12,8 +12,8 @@ test('Utf8Renderer interface', function (t) {
})
test('Utf8Renderer render', function (t) {
var sampleQrData = QRCode.create('sample text', { version: 2 })
var str
const sampleQrData = QRCode.create('sample text', { version: 2 })
let str
t.notThrow(function () { str = Utf8Renderer.render(sampleQrData) },
'Should not throw with only qrData param')
@ -32,9 +32,9 @@ test('Utf8Renderer render', function (t) {
})
test('Utf8 renderToFile', function (t) {
var sampleQrData = QRCode.create('sample text', { version: 2 })
var fileName = 'qrimage.txt'
var fsStub = sinon.stub(fs, 'writeFile').callsArg(2)
const sampleQrData = QRCode.create('sample text', { version: 2 })
const fileName = 'qrimage.txt'
let fsStub = sinon.stub(fs, 'writeFile').callsArg(2)
t.plan(5)

View file

@ -1,8 +1,8 @@
var test = require('tap').test
var Utils = require('renderer/utils')
const test = require('tap').test
const Utils = require('renderer/utils')
test('Utils getOptions', function (t) {
var defaultOptions = {
const defaultOptions = {
width: undefined,
scale: 4,
margin: 4,
@ -59,7 +59,7 @@ test('Utils getOptions', function (t) {
})
test('Utils getScale', function (t) {
var symbolSize = 21
const symbolSize = 21
t.equal(Utils.getScale(symbolSize, { scale: 5 }), 5,
'Should return correct scale value')
@ -74,7 +74,7 @@ test('Utils getScale', function (t) {
})
test('Utils getImageWidth', function (t) {
var symbolSize = 21
const symbolSize = 21
t.equal(Utils.getImageWidth(symbolSize, { scale: 5, margin: 0 }), 105,
'Should return correct width value')
@ -92,7 +92,7 @@ test('Utils qrToImageData', function (t) {
t.ok(Utils.qrToImageData,
'qrToImageData should be defined')
var sampleQrData = {
const sampleQrData = {
modules: {
data: [
1, 0, 1, 0,
@ -104,24 +104,24 @@ test('Utils qrToImageData', function (t) {
}
}
var margin = 4
var scale = 2
var width = 100
const margin = 4
const scale = 2
const width = 100
var color = {
const color = {
dark: { r: 255, g: 255, b: 255, a: 255 },
light: { r: 0, g: 0, b: 0, a: 255 }
}
var opts = {
const opts = {
margin: margin,
scale: scale,
color: color
}
var imageData = []
var expectedImageSize = (sampleQrData.modules.size + margin * 2) * scale
var expectedImageDataLength = Math.pow(expectedImageSize, 2) * 4
let imageData = []
const expectedImageSize = (sampleQrData.modules.size + margin * 2) * scale
let expectedImageDataLength = Math.pow(expectedImageSize, 2) * 4
Utils.qrToImageData(imageData, sampleQrData, opts)