-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathCore__Int.res
68 lines (54 loc) · 2.2 KB
/
Core__Int.res
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
module Constants = {
@inline let minValue = -2147483648
@inline let maxValue = 2147483647
}
let equal = (a: int, b: int) => a === b
let compare = (a: int, b: int) =>
a < b ? Core__Ordering.less : a > b ? Core__Ordering.greater : Core__Ordering.equal
@send external toExponential: int => string = "toExponential"
@send external toExponentialWithPrecision: (int, ~digits: int) => string = "toExponential"
@send external toFixed: int => string = "toFixed"
@send external toFixedWithPrecision: (int, ~digits: int) => string = "toFixed"
@send external toPrecision: int => string = "toPrecision"
@send external toPrecisionWithPrecision: (int, ~digits: int) => string = "toPrecision"
@send external toString: int => string = "toString"
@send external toStringWithRadix: (int, ~radix: int) => string = "toString"
@send external toLocaleString: int => string = "toLocaleString"
external toFloat: int => float = "%identity"
external fromFloat: float => int = "%intoffloat"
let fromString = (~radix=?, x) => {
let maybeInt = switch radix {
| Some(radix) => Core__Float.parseIntWithRadix(x, ~radix)
| None => Core__Float.parseInt(x)
}
if Core__Float.isNaN(maybeInt) {
None
} else if maybeInt > Constants.maxValue->toFloat || maybeInt < Constants.minValue->toFloat {
None
} else {
let asInt = fromFloat(maybeInt)
Some(asInt)
}
}
external mod: (int, int) => int = "%modint"
type rangeOptions = {step?: int, inclusive?: bool}
let rangeWithOptions = (start, end, options) => {
let isInverted = start > end
let step = switch options.step {
| None => isInverted ? -1 : 1
| Some(0) if start !== end =>
Core__Error.raise(Core__Error.makeRangeError("Incorrect range arguments"))
| Some(n) => n
}
let length = if isInverted === (step >= 0) {
0 // infinite because step goes in opposite direction of end
} else if step == 0 {
options.inclusive === Some(true) ? 1 : 0
} else {
let range = isInverted ? start - end : end - start
let range = options.inclusive === Some(true) ? range + 1 : range
ceil(float(range) /. float(abs(step)))->Core__Float.toInt
}
Core__Array.fromInitializer(~length, i => start + i * step)
}
let range = (start, end) => rangeWithOptions(start, end, {})