Skip to content

Commit b0ffbd2

Browse files
committed
Add safeDivide to stdlib
1 parent f63ec12 commit b0ffbd2

1 file changed

Lines changed: 22 additions & 1 deletion

File tree

src/libs/stdlib.ts

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,4 +32,25 @@ inline function getDigit(a, b) {
3232
//Returns 1 if the input is an integer, and 0 otherwise.
3333
inline function isInt(a) {
3434
state = a == floor(a);
35-
}`;
35+
}
36+
37+
//Safely divides a number (a/b), such that if b is 0 (a/0), it will return 0 instead of undefined.
38+
//Normally, if you divide a number by 0 (even if inside a statement that doesn't run) it will return
39+
//undefined for the entire function. This solves that issue. Use this anywhere that the divisor may
40+
//be 0.
41+
inline function safeDivide(a, b) {
42+
if(b == 0) {
43+
state = 0;
44+
} else {
45+
//This double check is needed because it will run, and needs to divide by a non-zero number. 1 is a "safe" value, but it's being used arbitrarily here.
46+
//No matter what number is used, it won't ever appear, unless it results in undefined (which will only happen if the value is 0 or infinity).
47+
if(b == 0) {
48+
state = 1;
49+
} else {
50+
state = b;
51+
}
52+
53+
state = a/state;
54+
}
55+
}
56+
`;

0 commit comments

Comments
 (0)