Last active
June 25, 2022 14:25
-
-
Save ellipizle/a8730ffc8ca68c2abfc4dd5bacb5ff0e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package mathema | |
import "errors" | |
type Config struct{ | |
ExtraPoint float64 | |
IsExtra bool | |
} | |
type Calculate struct{ | |
config Config | |
} | |
func NewCalculate(config Config) *Calculate{ | |
return &Calculate{config: config} | |
} | |
func (cal *Calculate) Calculate(operator string, firstValue, secondValue float64) (float64,error){ | |
if operator == ""{ | |
return 0,errors.New("Invalid operator") | |
} | |
if cal.config.IsExtra { | |
result, err := Compute(operator,firstValue,secondValue) | |
if err != nil{ | |
return 0,err | |
} | |
return result + cal.config.ExtraPoint,nil | |
} | |
return Compute(operator,firstValue,secondValue) | |
} | |
func Compute(operator string,firstValue,secondValue float64)(float64,error){ | |
switch operator { | |
case "+": | |
return firstValue +secondValue,nil | |
case "-": | |
return firstValue -secondValue,nil | |
case "*": | |
return firstValue*secondValue,nil | |
case "/": | |
return firstValue /secondValue,nil | |
} | |
return 0,errors.New("provided operator not supported") | |
} | |
// mathema can used with main like belong | |
package main | |
import ( | |
"github.com/ellipizle/mathema" | |
"fmt" | |
) | |
func main(){ | |
config := mathema.Config{ExtraPoint:20,IsExtra:true} | |
calculator := mathema.NewCalculator(config) | |
res, err:=calculator.Calculate("+",5,5) | |
if err != nil { | |
fmt.Println(err) | |
} | |
fmt.Println(res) | |
} | |
// your task is to modify the mathema package | |
// 1. the calculate can be called by using configuration | |
// 2. calculate can be called by not using configuration | |
// such that a user can use the package like below | |
package main | |
import ( | |
"github.com/ellipizle/mathema" | |
"fmt" | |
) | |
func main(){ | |
config := mathema.Config{ExtraPoint:20,IsExtra:true,Operator:"+"} | |
calculator := mathema.NewCalculator(config) | |
result, err:=calculator.Calculate(5,5) | |
if err != nil { | |
fmt.Println(err) | |
} | |
//should be 30 | |
fmt.Println(result) | |
result2,err := mathema.Calculate("-",15,5) | |
if err != nil { | |
fmt.Println(err) | |
} | |
//should be 10 | |
fmt.Println(result2) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment