🔗LC2704 🟢 Easy 🧩 Pattern – Closures
📅 Day 3/30 Days of JavaScript
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 returnstrue
if the two values===
each other. If they are not equal, it should throw an error"Not Equal"
.notToBe(val)
accepts another value and returnstrue
if the two values!==
each other. If they are equal, it should throw an error"Equal"
.
Example
Input: func = () => expect(5).toBe(5)
Output: {"value": true}
Explanation: 5 === 5 so this expression returns true.
Input: func = () => expect(5).notToBe(null)
Output: {"value": true}
Explanation: 5 !== null so this expression returns true.
Solution
Here, we need to understand how we are returning an object that has two functions as its properties forming a closure to access the val (argument).
/**
* @param {string} val
* @return {Object}
*/
var expect = function (val) {
return {
toBe: (value) => {
if (value === val) {
return true;
} else {
throw new Error("Not Equal");
}
},
notToBe: (value) => {
if (value !== val) {
return true;
} else {
throw new Error("Equal");
}
},
}
}
/**
* expect(5).toBe(5); // true
* expect(5).notToBe(5); // throws "Equal"
*/