I have to make a function that takes dictionary (object) and sentence as parameteres and returns adequete key's value and if there is missing word in a dictionary function should throw an error "Error: missing value"
these are examples of output:
translate({ "je": "I", "suis": "am", "pere": "father", "ton": "your"}, "je suis ton pere" ) // 'I am your father'
translate({ "the": "le", "cute": "mignon", "your": "ton", "dog": "chien", "is": "est"}, "the dog is cute" ) // 'le chien est mignon'
translate({ "the": "le", "cute": "mignon", "your": "ton", "dog": "chien", "is": "est"}, "the dog is fluffy" ) // 'Error: missing value'
my code is like that: and its working but it stops at index 0, so i can get only first result which is "I"
let dictionary = {
"je": "I",
"suis": "am",
"pere": "father",
"ton": "your"
}
let dictKeys = Object.keys(dictionary)
let translated = []
for(let i=0; i < sentence.length; i++){
for(let j=0; j < dictKeys.length; i++){
if(sentence[i] == dictKeys[j]){
translated.push(dictionary[dictKeys[j]])
console.log(translated)
}
}
}
i have no idea how to finish this exercise, please help me
Your code was almost fine. In your second loop, you incremented again i instead of j. I added a toLowerCase to cover case sensitive words
let dictionary = {
"je": "I",
"suis": "am",
"pere": "father",
"ton": "your"
}
let dictKeys = Object.keys(dictionary)
let translated = []
let missing = []
let sentence = "Je suis ton ami abc gfukgv".split(" ")
for (let i = 0; i < sentence.length; i++) {
if (!dictKeys.includes(sentence[i].toLowerCase())) {
missing.push(sentence[i])
//console.error(`"${sentence[i]}" word is missing from dictionary`)
}
for (let j = 0; j < dictKeys.length; j++) {
if (sentence[i].toLowerCase() == dictKeys[j].toLowerCase()) {
translated.push(dictionary[dictKeys[j]])
}
}
}
missing.length > 0 ? console.error(`The following words are missing from the dictionary: ${missing.join(", ")}`) : null
console.log(translated.join(" "))