
/**
* @param {string} val
* @return {Object}
*/
var expect = function(val) {
return {
x : val,
notToBe : function(key){
if (this.x === key) {
throw new Error("Equal");
}
return true;
},
toBe : function(key){
if (this.x !== key) {
throw new Error("Not Equal");
}
return true;
}
}
};
The problem was about writing a function that returns an object with two functions
1. toBe returns true when two given numbers are equal otherwise throw error with a message 'Not Equal'
2. notToBe returns true when two given number are not equal otherwise throw error with a message 'Equal'
The function expect, above the code, acts as a factory function, a function returning an object (in this case, with two functions).
Its time complexity is O(1) as it only creates an object and does not perform any iterative or recurssive action.
The space complexity is also O(1) as it only creates exactly one object with two methods regardless the size or the complexity of input value. Therefore, the amount of memory to execute this function does not need to scale the size, resulting in constant space complexity.
Higer-Order Function
Factory Function
Method Chaining
The problem and the answer themselves are very simple.
Yet, it taught me a fundemental javascript.
Coding might be simple but explaining how code works technically is another challenge.
Keep learning, own the technique