0

I am writing a function letters(text) that takes a string with uneven number of characters and makes a dictionary that gives each letter a numerical value based on their place in the string. Instead of enumerating the letters with their index, this function gives them values starting from -(lengthOfString/2) to (lengthOfString/2) so that middle character is always zero.

>>>letters("stack")
{"S": -2, "T": -1, "A": 0, "C": 1, "K": 2}

I am fairly new to JavaScript and even tough my code does its job, I don't think it is the right way to do it. Also I need to check if the text only contains letters, has an uneven amount of letters and doesn't include the same letter twice. I couldn't find a way to throw an assertion error and how to formulate the last condition.

function letters(text){

    text= text.toUpperCase();
    if(text.length % 2 !== 1 && /^[a-zA-Z]+$/.test(text)){

    }
    const len = text.length;
    const limit = parseInt(len/2);
    var list = text.split("");
    var dict = {};

    for (let j = -limit; j<=limit; j++){
        list.push(j)
    }
    for (var range = 0; range < list.length/2;range++ ) {
        dict[list[range]] = [];
        dict[list[range]].push(list[range + list.length / 2]);
    }
  
    return dict
}
console.log(letters("stack"))

2
  • What happens if there are repeated characters, eg ann? Or is that not an input that will be encountered for this problem? Commented Apr 21, 2020 at 4:00
  • The function won't accept the input and throw an Assertion Error that says "invalid text" Commented Apr 21, 2020 at 4:10

2 Answers 2

2

You can simply:

const letters = (txt) => {
  if(txt.length%2==0){throw "even length exeption";return}
  let out = {}
  for (var x = 0; x < txt.length; x++)
  {
    out[txt.charAt(x)] = x - (txt.length-1)/2
    
  }
  return out
}

console.log(letters('stack'))
console.log(letters('stackk'))

Sign up to request clarification or add additional context in comments.

Comments

2

You can add test for repeated words using Set and also can remove the last loop

function letters(text) {
  text = text.toUpperCase();
  let repeated = new Set([...text]).size !== text.length
  if ( text.length % 2 === 0 || /[^A-Z]/.test(text) || repeated) {
    return "Invalid text"
  }

  const limit = parseInt(text.length / 2);
  var dict = {};

  for (let j = -limit, range = 0; range < text.length; j++, range++) {
    dict[text[range]] = j
  }
  return dict
}
console.log(letters("stack"))
console.log(letters("Ana"))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.