Back to Freecodecamp

Challenge 83: Signature Validation

curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68e39ed6106dac2f0a98fd65.md

latest2.0 KB
Original Source

--description--

Given a message string, a secret key string, and a signature number, determine if the signature is valid using this encoding method:

  • Letters in the message and secret key have these values:
    • a to z have values 1 to 26 respectively.
    • A to Z have values 27 to 52 respectively.
  • All other characters have no value.
  • Compute the signature by taking the sum of the message plus the sum of the secret key.

For example, given the message "foo" and the secret key "bar", the signature would be 57:

md
f (6) + o (15) + o (15) = 36
b (2) + a (1) + r (18) = 21
36 + 21 = 57

Check if the computed signature matches the provided signature.

--hints--

verify("foo", "bar", 57) should return true.

js
assert.isTrue(verify("foo", "bar", 57));

verify("foo", "bar", 54) should return false.

js
assert.isFalse(verify("foo", "bar", 54));

verify("freeCodeCamp", "Rocks", 238) should return true.

js
assert.isTrue(verify("freeCodeCamp", "Rocks", 238));

verify("Is this valid?", "No", 210) should return false.

js
assert.isFalse(verify("Is this valid?", "No", 210));

verify("Is this valid?", "Yes", 233) should return true.

js
assert.isTrue(verify("Is this valid?", "Yes", 233));

verify("Check out the freeCodeCamp podcast,", "in the mobile app", 514) should return true.

js
assert.isTrue(verify("Check out the freeCodeCamp podcast,", "in the mobile app", 514));

--seed--

--seed-contents--

js
function verify(message, key, signature) {

  return message;
}

--solutions--

js
function verify(message, key, signature) {
  function charValue(ch) {
    if (ch >= 'a' && ch <= 'z') return ch.charCodeAt(0) - 'a'.charCodeAt(0) + 1;
    if (ch >= 'A' && ch <= 'Z') return ch.charCodeAt(0) - 'A'.charCodeAt(0) + 27;
    return 0;
  }

  function computeSum(str) {
    let sum = 0;
    for (let ch of str) {
      sum += charValue(ch);
    }
    return sum;
  }

  const total = computeSum(message) + computeSum(key);
  return total === signature;
}