Skip to content

Instantly share code, notes, and snippets.

@jordanhudgens
Created September 14, 2018 16:41
Show Gist options
  • Save jordanhudgens/83fc67bef86814d7a139c259d2bd7ae5 to your computer and use it in GitHub Desktop.
Save jordanhudgens/83fc67bef86814d7a139c259d2bd7ae5 to your computer and use it in GitHub Desktop.
class FlexibleCounter {
constructor(nums, op) {
this.nums = nums;
this.op = op;
this.operatorWhiteList = ["+", "*", "/", "-"];
}
result() {
if (this.operatorWhiteList.includes(this.op) && !this.nums.some(isNaN)) {
return this.nums.reduce((total, el) => eval(`${total} ${this.op} ${el}`));
} else {
return "There was an issue with the data";
}
}
}
const sum = new FlexibleCounter([1, 2, 3], "+");
sum.result(); // 6
const product = new FlexibleCounter([1, 2, 3], "/");
product.result(); // 0.166
const badData = new FlexibleCounter(["Sneaky code", 2, 3], "+");
badData.result(); // "There was an issue with the data"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment