Created
March 12, 2020 16:20
-
-
Save zelding/3c1ba671dc581f4494bb73823a3b3095 to your computer and use it in GitHub Desktop.
my take on fraction for StoneStory RPG script language aka stonescript
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
//stonescript 2.9.2 | |
// Fraction class 0.0.1 | |
// based on the works of Boo | |
// This has to go in your /Components folder | |
// | |
// functions that start with an Uppercase letter should be considered public | |
// others are private / internal, and you should call them outside | |
var numerator = 0 | |
var denominator = 1 | |
var safety_threshold = 32768 | |
// initialize the object | |
// @var int num | |
// @var int denom | |
func Init(num, denom) | |
numerator = num | |
denominator = denom | |
? denominator = 0 | |
denominator = 1 | |
simplify() | |
// add an other fraction to this one | |
// @var Fraction frac | |
func Add(frac) | |
var gcd = Gcd(denominator, frac.denominator) | |
numerator = numerator * gcd + frac.numerator * gcd | |
denominator = denominator * gcd + frac.denominator * gcd | |
simplify() | |
// @var Fraction frac | |
func Subtract(frac) | |
var copy = frac.Clone() | |
copy.MultiplyByInt(-1) | |
Add(copy) | |
// @var int number | |
func MultiplyByInt(number) | |
numerator = numerator * number | |
simplify() | |
// @var Fraction frac | |
func Multiply(frac) | |
numerator = numerator * frac.numerator | |
denominator = denominator * frac.denominator | |
simplify() | |
// @var Fraction frac | |
func Divide(frac) | |
var inverse = frac.Inverse() | |
Multipy(inverse) | |
// returns a copy | |
func Clone() | |
var f = new Components/Fraction | |
f.numerator = numerator | |
f.denominator = denominator | |
return f | |
func Inverse() | |
var copy = Clone() | |
// just filp the sides ;) | |
copy.Init(denominator, numerator) | |
return copy | |
func ToString() | |
return numerator + "/" + denominator | |
// "divide" both numerator and denominator by a single integer | |
// @internal you shouldn't use it outside | |
// @var int number | |
func reduce(number) | |
numerator = numerator / number | |
denominator = denominator / number | |
func gcd(a, b) | |
? a = 0 | |
return b | |
// yey recursion | |
return gcd(b % a, a) | |
func simplify() | |
? denominator < 0 | |
reduce(-1) | |
var gcd = gcd(numerator, denominator) | |
numerator = numerator / gcd | |
denominator = denominator / gcd |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment