Tengo que hacer una función que tome el diccionario (objeto) y la oración como parámetros y devuelva el valor de la clave adecuada y si falta una palabra en una función de diccionario debería arrojar un error "Error: valor faltante"
estos son ejemplos de salida:
translate({ "je": "yo", "suis": "soy", "pere": "padre", "ton": "tu"}, "je suis ton pere" ) // 'Yo soy tu padre '
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"}, "el perro es esponjoso" ) // 'Error: valor faltante'
mi código es así: y funciona pero se detiene en el índice 0, por lo que solo puedo obtener el primer resultado, que es "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) } } }No tengo idea de cómo terminar este ejercicio, por favor ayúdame.
Su código estaba casi bien. En su segundo ciclo, incrementó nuevamente i en lugar de j. Agregué un toLowerCase para cubrir palabras sensibles a mayúsculas y minúsculas
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(" "))