I'm working on a project where I want to create a API that can be used to do some mathmatical calculations.
Here are the important aspects:
- I used the revealing module pattern
- I added method chaining (sort of like in JQuery)
- No Prototypes used (I don't see a advantage here)
My questions are the following:
- Is it a mistake to not use prototypes ? I'm sort of thinking about the benefits I could gain by using them but I don't see any.
- Is the error handling the correct way or should I do it differently ?
- Does the code look viable and suitable for a API ?
- Is there a other way of doing the method chaining ?
I'm also open for general suggestion to improve the code further which wasn't mentioned in the questions.
Edit: I haven't mentioned that I don't have a problem with using prototypes, I do understand the prototype inheritance and I also welcome any suggestion that is written with it.
Here is the code
function type(entity) {
return Object.prototype.toString.call(entity).slice(8, -1);
}
function isNumber(entity) {
return type(entity) === "Number";
}
let gMath = (function() {
let currentNumber;
let gotNumber = false;
let number = function(number) {
let numberType = type(number);
if (isNumber(number) && !gotNumber) {
currentNumber = gotNumber ? undefined : number;
gotNumber = true;
} else if (gotNumber) {
console.log("Error! Cannot define 2 numbers. Only use .number() once or call .getNumber() to clear the current one.");
} else if (type(number) === "String") {
console.log(`This function only accepts Numbers as arguments. You passed in: "${numberType}"`);
} else{
console.log(`This function only accepts Numbers as arguments. You passed in: ${numberType}`);
}
return this;
}
let scatter = function(range) {
currentNumber = Math.floor((currentNumber + (Math.random() * range * 2) - range) + 1);
return this;
}
let randomize = function(number) {
currentNumber = Math.floor(Math.random() * currentNumber);
return this;
}
let atleast = function(number) {
currentNumber = currentNumber < number ? number : currentNumber;
return this;
}
let add = function(number) {
currentNumber += number;
return this;
}
let subtract = function(number) {
currentNumber -= number;
return this;
}
let show = function() {
console.log(currentNumber);
return this;
}
let getNumber = function() {
gotNumber = false;
return currentNumber;
}
let isCurrentNumber = function() {
console.log("Currently the gotNumber variable is: " + gotNumber);
}
return {
// chainable
scatter,
number,
atleast,
randomize,
add,
subtract,
show,
// non-chainable
getNumber,
isCurrentNumber
}
})();
let a = gMath.number(10)
.scatter(50)
.getNumber();
console.log(a) // --> logs a Number between -40 and 60