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"))
ann? Or is that not an input that will be encountered for this problem?