Reputation: 669
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"))
Upvotes: 0
Views: 41
Reputation: 37755
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"))
Upvotes: 2
Reputation: 3728
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'))
Upvotes: 2