Skip to content

Instantly share code, notes, and snippets.

@failpunk
Created March 19, 2019 21:20
Show Gist options
  • Save failpunk/1f2a52d711145b2001ca4675a1fd245c to your computer and use it in GitHub Desktop.
Save failpunk/1f2a52d711145b2001ca4675a1fd245c to your computer and use it in GitHub Desktop.
This is a simple javascript test exercise.
class FluidCalc {
constructor() {
// Array of operation objects
this.operations = [];
// Stores the first number in the chain
this.first_number = null;
// The latest operation in the chain
this.current_operation = null;
}
one() {
this.process_number(1);
return this;
}
two() {
this.process_number(2);
return this;
}
three() {
this.process_number(3);
return this;
}
plus() {
this.current_operation = '+';
return this;
}
minus() {
this.current_operation = '-';
return this;
}
times() {
this.current_operation = '*';
return this;
}
/**
* Called for each number method of the class;
* Determine if this is the first number the chain, otherwise bundle number into an operator object using
* the latest operator used.
*/
process_number(n) {
if (this.first_number === null) {
this.first_number = n;
return;
}
// Operator Object
let operation = {
op: this.current_operation, // operation (+, -, *, etc...)
value: n // value to apply operation to.
};
this.operations.push(operation);
// Clear the last number used so we can deliniate the start of the next operation.
this.current_number = null;
}
/**
* Given a starting value, this method will apply the operation specified in the object passed in using the value in the object.
*/
perform_operation(value, operation) {
if (operation.op === '+') {
return value + operation.value;
}
if (operation.op === '-') {
return value - operation.value;
}
if (operation.op === '*') {
return value * operation.value;
}
}
/**
* Calculate a final value by iterating over the array of operations and appying each to the final result.
*/
equals() {
// Our operation starts with the first number passed in.
let final_value = this.first_number;
this.operations.forEach(item => {
final_value = this.perform_operation(final_value, item);
});
return final_value;
}
}
/** ----------------------------------- */
let calculator_obj = new FluidCalc();
let test = calculator_obj
.one()
.plus()
.two()
.minus()
.three();
console.log(test.equals());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment