Objects everywhere
Well, you've probably heard before about objects in JavaScript and how they are important in order to understand the language.
Objects make JS extremely readable and useful because of its model "key":"value". But the thing I want to stand out is that the "value" section accepts not only a simple string, rather another object, that in turn, may be another object and so on. For instance:
const character = {
name:"Arthur Morgan",
age:24,
face: {
hairSize:5,
eyesColor: "blue",
}
}
This snippet shows that face is an object as well as character. It's perfectly fine to do so, and lots of complex APIs deals with data like that, grouping over and over when it matters.
But the real power of objects relies on functions, and this Leet Code problem deals with it, as well as give us the gist of how test libraries work under the hood. Basically you need a function that validates wether a value is equal as the expected or is not: toBe() and notToBe(). To do so, we can return an object with those functions. By the way, using arrow functions makes it prettier and direct.
Here is the answer.
function expect(val) {
function toBe(anotherValue) {
if (val === anotherValue) {
return true;
}
throw Error("Not Equal");
}
function notToBe(anotherValue) {
if (val !== anotherValue) {
return true;
}
throw Error("Equal");
}
return {
toBe: (anotherValue) => toBe(anotherValue),
notToBe: (anotherValue) => notToBe(anotherValue),
};
}
We can quickly see it running using another object: the famous console and its function log.
console.log(expect(5).toBe(null)); // give us an error "Not Equal", because 5 is not null
Note that the fact of returning an object give us the freedom to use expect() and then, right after, .toBe(). That is because we return an object and imediatelly access the property toBe, which is a function.
This Leet code problem is an excellent way to see how objects and functions can work together and build awesome stuff in JavaScript. I hope you liked :)
Top comments (0)