Refactor and improve tree.js to use the SOLID principles.
The current Node API breaks the SOLID interface segregation principle:
constNode=(operator,value,left,right)=>{..};It forces to pass an empty string for the operator parameter and null for the left and right nodes for the leaf (value) nodes and null for the value parameter for internal (operation) nodes:
constvalueNode1=Node("",4,null,null);constvalueNode2=Node("",2,null,null);constdivisionNode=Node("÷",null,valueNode1,valueNode2);We can see that the each type of node accepts completely opposite parameters so their interfaces have to be segregated to make them smaller and more reasonable.
With the interfaces segregated, we no longer have to pass redundant properties to each type of node:
constvalueNode1=Value(4);constvalueNode2=Value(2);constdivisionNode=Divide(valueNode1,valueNode2);Both the switch statement in the result method
switch(operator){case"+":
returnleft.result()+right.result();case"-":
returnleft.result()-right.result();case"x":
returnleft.result() \*right.result();case"÷":
returnleft.result()/right.result();default:
returnvalue;}and the switch statement in the toString method
switch(operator){case"+":
return`(${left.toString()} + ${right.toString()})`;case"-":
return`(${left.toString()} - ${right.toString()})`;case"x":
return`(${left.toString()} x ${right.toString()})`;case"÷":
return`(${left.toString()} ÷ ${right.toString()})`;default:
returnvalue.toString();}violate the SOLID open/closed principle.
To add a new expression (outside of the Node class), we have to modify the existing code (inside the Node class) - so it's not "closed off" and easily extendable. This also causes code to be harder to read, maintain and be more error-prone.
Instead of having these switch statements based on type (operator), they can be broken off in small, individual classes. To enforce class compatibility and for polymorphism to work, an interface containing both result and toString methods has to be implemented:
interfaceIResultable{result: ()=>number;}interfaceIPrintable{toString: ()=>string;}New node classes "implementing" both interfaces:
constValue=(value)=>({
value,result: ()=>value,toString: ()=>`${value}`,});constAdd=(left,right)=>({
left,
right,result: ()=>left.result()+right.result(),toString: ()=>`(${left.toString()} + ${right.toString()})`,});constSubtract=(left,right)=>({
left,
right,result: ()=>left.result()-right.result(),toString: ()=>`(${left.toString()} - ${right.toString()})`,});constMultiply=(left,right)=>({
left,
right,result: ()=>left.result()*right.result(),toString: ()=>`(${left.toString()} * ${right.toString()})`,});constDivide=(left,right)=>({
left,
right,result: ()=>left.result()/right.result(),toString: ()=>`(${left.toString()} ÷ ${right.toString()})`,});consttree=Divide(Add(Value(7),Multiply(Subtract(Value(3),Value(2)),Value(5))),Value(6));The initial Node API implementation is missing any kind of encapsulation, exposing implementation details as every property and method is available:
return{
operator,
value,
left,
right,
result,
toString,};The previously implemented interfaces indicate which methods need to be exposed for a consistent API, hiding the implementation details with the help of a closure:
constValue=(value)=>({result: ()=>value,toString: ()=>`${value}`,});constAdd=(left,right)=>({result: ()=>left.result()+right.result(),toString: ()=>`(${left.toString()} + ${right.toString()})`,});constSubtract=(left,right)=>({result: ()=>left.result()-right.result(),toString: ()=>`(${left.toString()} - ${right.toString()})`,});constMultiply=(left,right)=>({result: ()=>left.result()*right.result(),toString: ()=>`(${left.toString()} * ${right.toString()})`,});constDivide=(left,right)=>({result: ()=>left.result()/right.result(),toString: ()=>`(${left.toString()} ÷ ${right.toString()})`,});Both the initial Node implementation and the one above violate the single responsibility principle of SOLID. The classes handle both the calculation logic (result) and the printing logic (toString). To avoid having to make changes to the classes when the printing logic changes, the printing logic should be factored out to a seperate module:
constprintValue=(value)=>`${value}`;constprintExpression=(left,right,operation)=>`(${left.toString()}${operation}${right.toString()})`;module.exports={
printValue,
printExpression,};Importing and using the printing module means that if the printing logic changes, no changes to the classes will be required.
const{ printValue, printExpression }=require("./print");constValue=(value)=>({result: ()=>value,toString: ()=>printValue(value),});constAdd=(left,right)=>({result: ()=>left.result()+right.result(),toString: ()=>printExpression(left,right,"+"),});constSubtract=(left,right)=>({result: ()=>left.result()-right.result(),toString: ()=>printExpression(left,right,"-"),});constMultiply=(left,right)=>({result: ()=>left.result()*right.result(),toString: ()=>printExpression(left,right,"*"),});constDivide=(left,right)=>({result: ()=>left.result()/right.result(),toString: ()=>printExpression(left,right,"÷"),});Although the responsibility of calculation is now separated from printing with the help of the printing module, the two responsibilities are still coupled together as changing the printing method altogether will still cause changes to the class.
To avoid this, we can make the dependency easily switchable with a higher-order function:
// Import or define new printing functions.constmakeValue=(toString)=>(value)=>({result: ()=>value,toString: ()=>toString(value),});constmakeAdd=(toString)=>(left,right)=>({result: ()=>left.result()+right.result(),toString: ()=>toString(left,right,"+"),});constmakeSubtract=(toString)=>(left,right)=>({result: ()=>left.result()-right.result(),toString: ()=>toString(left,right,"-"),});constmakeMultiply=(toString)=>(left,right)=>({result: ()=>left.result()*right.result(),toString: ()=>toString(left,right,"x"),});constmakeDivide=(toString)=>(left,right)=>({result: ()=>left.result()/right.result(),toString: ()=>toString(left,right,"÷"),});// Pass the printing functions to the higher-order functions to create the classes.constValue=makeValue(printValue);constAdd=makeAdd(printExpression);constSubtract=makeSubtract(printExpression);constMultiply=makeMultiply(printExpression);constDivide=makeDivide(printExpression);// The API hasn't changed.consttree=Divide(Add(Value(7),Multiply(Subtract(Value(3),Value(2)),Value(5))),Value(6));Following point 4 and point 5, for input validaiton we can create a separate validation module:
const{ number }=require("../utils");constvalidateValue=(value)=>{if(!number.isNumber(value)){thrownewError(`The value "${value}" is not a numerical value!`);}};constvalidateExpression=(left,right,operation)=>{if(!left?.result||!right?.result){thrownewError(`The operation "${operation}" is missing an operand!`);}};constvalidateDivide=(left,right,operation)=>{validateExpression(left,right,operation);if(right.result()===0){thrownewError(`The right-hand side operand "${right.toString()}" for Divide must be non-zero!`);}};module.exports={
validateValue,
validateExpression,
validateDivide,};Which then gets imported and injected through the same higher-order functions:
const{
validateValue,
validateExpressio,
validateDivide,}=require("./validation");constmakeValue=(validateValue,toString)=>(value)=>{validateValue(value);return{result: ()=>value,toString: ()=>toString(value),};};constmakeAdd=(validateExpression,toString)=>(left,right)=>{constoperation="+";validateExpression(left,right,operation);return{result: ()=>left.result()+right.result(),toString: ()=>toString(left,right,operation),};};constmakeSubtract=(validateExpression,toString)=>(left,right)=>{constoperation="-";validateExpression(left,right,operation);return{result: ()=>left.result()-right.result(),toString: ()=>toString(left,right,operation),};};constmakeMultiply=(validateExpression,toString)=>(left,right)=>{constoperation="x";validateExpression(left,right,operation);return{result: ()=>left.result()*right.result(),toString: ()=>toString(left,right,operation),};};constmakeDivide=(validateDivide,toString)=>(left,right)=>{constoperation="÷";validateDivide(left,right,operation);return{result: ()=>left.result()/right.result(),toString: ()=>toString(left,right,operation),};};// Pass in the additional argument for validation to the higher-order functions.constValue=makeValue(validateValue,printValue);constAdd=makeAdd(validateExpression,printExpression);constSubtract=makeSubtract(validateExpression,printExpression);constMultiply=makeMultiply(validateExpression,printExpression);constDivide=makeDivide(validateDivide,printExpression);// The API hasn't changed.consttree=Divide(Add(Value(7),Multiply(Subtract(Value(3),Value(2)),Value(5))),Value(6));See test.js for the test cases.
Main:
node index.js
Tests:
node test.js