To Be Or Not To Be Problem
#2704
Description
LeetCode Problem 2704.
Write a function expect that helps developers test their code. It should take in any value val and return an object with the following two functions.
toBe(val)accepts another value and returnstrueif the two values===each other. If they are not equal, it should throw an error"Not Equal".notToBe(val)accepts another value and returnstrueif the two values!==each other. If they are equal, it should throw an error"Equal".
Example 1:
Input: func = () => expect(5).toBe(5)
Output: {"value": true}
Explanation: 5 === 5 so this expression returns true.
Example 2:
Input: func = () => expect(5).toBe(null)
Output: {"error": "Not Equal"}
Explanation: 5 !== null so this expression throw the error "Not Equal".
Example 3:
Input: func = () => expect(5).notToBe(null)
Output: {"value": true}
Explanation: 5 !== null so this expression returns true.
Solution
Approach: Object of two checking functions
expect(val) returns an object whose two methods close over val. toBe compares with === and either returns true or throws Error("Not Equal"); notToBe is the mirror image with !== and Error("Equal"). Strict comparison matters: 5 === "5" is false, so expect(5).toBe("5") throws.
Complexity: Time O(1), space O(1).
var expect = function (val) {
return {
toBe: other => {
if (val !== other) throw new Error('Not Equal');
return true;
},
notToBe: other => {
if (val === other) throw new Error('Equal');
return true;
},
};
};