Hi guys, I’m just doing Missing Letter and I thought I’d figured it out, but the ternary operator at the end that I thought would print undefined if all letters were present, just returns a curly brace? When a letter is missing it’s fine.
Any ideas?
Your code so far
function fearNotLetter(str) {
const firstLetter = str.charCodeAt(0);
const lastLetter = (str.length + firstLetter);
let total = ((str.length + 1) / 2) * (firstLetter + lastLetter);
let sum = 0;
for (let value of str) {
sum += value.charCodeAt(0);
}
console.log(sum)
return total === sum ? undefined : String.fromCharCode(total - sum);
}
fearNotLetter("abcdefghijklmnopqrstuvwxyz");
Your browser information:
User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36.
Interesting approach to the problem. The issue you are having is because total is not === to the sum in the situations where all the letters are present, so it is returning String.fromCharCode(total-sum) instead of undefined. One possible solution could be checking if (lastletter === total-sum) in the ternary instead of (total===sum).
Ah, cool! Thanks Lucas! That should have been obvious to me!
I was trying to find a way without for loops, but instead I confused myself so much that I had to use one.
I’ve just had a search on why to avoid for…in and regular for loops, but I can’t seem to find any evidence against for…of.
I think it looks like they are good for functional programming because they’re less likely to give unexpected results?
Are these types of loops good to use, or should I try to find another way, like recursion?
Unless you are dealing with huge amounts of data I wouldn’t worry too much about which type of loop you use, the differences aren’t very significant so I’d focus on readability first and then come back to refactor if you find a function is slowing your code down.
If you do plan on working with large amounts of data it may be helpful to research Big O notation in JavaScript.
In general I’d only be super concerned about time complexity/performance when dealing with nested loops, which can cause significant performance losses.
I’m not an expert on the subject by any means but from what I’ve read it seems like in most cases recursion is less performant than iteration in JS if a single iteration solution is possible. If I understand it correctly this may change once more browsers add support for tail call recursion optimization. http://2ality.com/2015/06/tail-call-optimization.html
Thank you for the info. I definitely want to adopt and learn best practices the first time, instead of having to re-learn. I’ll research Big O notation so!
Cheers