TheAlgorithms/JavaScript · error · TypeError

Argument str should be String

Error message

Argument str should be String

What it means

Thrown by isCorrectFormat() when the plaintext str is not a string. Affine cipher operates character-by-character via charCodeAt, so a non-string would either coerce incorrectly or throw deeper; the guard fails fast with a clear message.

Source

Thrown at Ciphers/AffineCipher.js:45

  for (let x = 1; x < m; x++) {
    if (mod(a * x, m) === 1) return x
  }
}

/**
 * Argument validation
 * @param {String} str - String to be checked
 * @param {Number} a - A coefficient to be checked
 * @param {Number} b - B coefficient to be checked
 * @return {Boolean} Result of the checking
 */
function isCorrectFormat(str, a, b) {
  if (typeof a !== 'number' || typeof b !== 'number') {
    throw new TypeError('Coefficient a, b should be number')
  }

  if (typeof str !== 'string') {
    throw new TypeError('Argument str should be String')
  }

  if (!CoPrimeCheck(a, 26)) {
    throw new Error(a + ' is not coprime of 26')
  }

  return true
}

/**
 * Find character index based on ASCII order
 * @param {String} char - Character index to be found
 * @return {Boolean} Character index
 */
function findCharIndex(char) {
  return char.toUpperCase().charCodeAt(0) - 'A'.charCodeAt(0)
}

View on GitHub (pinned to 5c39e87a9a)

Solutions

  1. Pass a real string: encrypt('hello', a, b).
  2. Decode buffers: Buffer.from(...).toString('utf8').
  3. Stringify objects: JSON.stringify(obj) if that is the intent.

Example fix

// before
encrypt(buffer, a, b) // Buffer
// after
encrypt(buffer.toString('utf8'), a, b)
Defensive patterns

Strategy: type-guard

Validate before calling

function ensureString(v) {
  return typeof v === 'string' ? v : String(v);
}
// encrypt(ensureString(text), a, b)

Type guard

/** @param {unknown} s @returns {s is string} */
const isString = s => typeof s === 'string';

Try / catch

try { return encrypt(text, a, b); }
catch (e) {
  if (e instanceof TypeError && /str should be String/.test(e.message)) {
    return encrypt(String(text), a, b);
  }
  throw e;
}

Prevention

When it happens

Trigger: Passing a number, object, array, null, undefined, or Buffer where the plaintext string is expected.

Common situations: Passing a Buffer/Uint8Array from a file read instead of decoded text, or forgetting to JSON.stringify an object before encrypting.

Related errors


AI-assisted analysis of TheAlgorithms/JavaScript@5c39e87a9a (2026-08-13). Data as JSON: /api/errors/0fa75deac06c570f. Report an issue: GitHub.