Problem overview
The method safeLookup receives scores, an object used as a dictionary from names to scores, and a name. It returns the score of that name, or 0 when the name is not a key of the object.
With {"Ana": 90, "Ben": 75, "Cara": 88} and "Ben", the answer is 75. With "Dan", who is not in the object, the answer is 0. An empty object has no keys, so every name gives 0. Names must match exactly: "ana" is not "Ana".
Approach
Reading a key that does not exist is not an error in JavaScript and TypeScript. scores["Dan"] quietly gives undefined, so returning it directly would break the promise of a number. The method needs to ask first whether the key is there.
The in operator does that: name in scores is true when scores has a key spelled like the value of name. The method uses it in an if. When the key exists it returns the stored score and ends. Otherwise it falls through to a final return 0.
Step by step
- Test the key. Write an
ifwith the conditionname in scores, and inside it returnscores[name]. The brackets use the variable's value as the key. - Return 0 after the
if. This line is reached only when the condition was false, because areturninside theifhas already ended the method.
The solution in TypeScript
class Solution {
safeLookup(scores: { [key: string]: number }, name: string): number {
if (name in scores) {
return scores[name];
}
return 0;
}
}
Details worth knowing:
- The key goes on the left of
in.name in scoreschecks keys. It never checks values, so it is not like asking whether an array contains a value. - A score of 0 is still a key. With
{"Ana": 0},"Ana" in scoresistrueand the method returns 0 from the first branch. Writingscores[name] || 99instead would give 99 for that entry, because 0 is falsy. The??operator only replacesundefinedandnull, soscores[name] ?? 0is another correct way to write the method in one line. inalso sees inherited names. Every object inherits properties such astoString, so"toString" in scoresistrueeven for{}, andsafeLookup({}, "toString")returns a function. A name like that is not a real key. To count only the object's own keys, useObject.hasOwn(scores, name). It givesfalsefor"toString"andtruefor"Ana"in{"Ana": 0}. For ordinary names like the ones in this lesson,inis enough.- Types are erased. The
numberreturn type is not checked at run time.
Complexity
Time: O(1) on average. The membership test and the read are each a single lookup.
Space: O(1). Nothing new is allocated.
Edge cases and common mistakes
- Empty object.
{}has no keys, so the method returns 0. - Different case.
"ana"is not a key of{"Ana": 90}, so the answer is 0. - Returning the lookup directly.
return scores[name]givesundefinedfor a missing name, where the answer must be 0. - Treating 0 as missing. A real score of 0 must come back as 0 through the stored value. Testing the value for truthiness instead of testing the key can hide that.
- Swapping the operands.
scores in nameis a type error, and it throws aTypeErrorat run time becausenameis a string, not an object.
Testing
{"Ana": 90, "Ben": 75, "Cara": 88}with"Ben"gives75.- The same object with
"Dan"gives0. {}with"Ana"gives0.{"Ana": 90}with"ana"gives0.
