```res prelude
@@ -20,11 +21,10 @@ canonical: "/docs/manual/v12.0.0/async-await"
ReScript comes with `async` / `await` support to make asynchronous, `Promise` based code easier to read and write. This feature is very similar to its JS equivalent, so if you are already familiar with JS' `async` / `await`, you will feel right at home.
-## How it looks
+## How it looks
Let's start with a quick example to show-case the syntax:
-
```res
@@ -46,7 +46,9 @@ let logUserDetails = async (userId: string) => {
```js
async function logUserDetails(userId) {
var email = await GlobalAPI.fetchUserMail(userId);
- await GlobalAPI.sendAnalytics("User details have been logged for " + userId + "");
+ await GlobalAPI.sendAnalytics(
+ "User details have been logged for " + userId + "",
+ );
console.log("Email address for user " + userId + ": " + email + "");
}
```
@@ -65,7 +67,6 @@ You will probably notice that this looks very similar to `async` / `await` in JS
- A function returning a `promise<'a>` is equivalent to an `async` function returning a value `'a` (important for writing signature files and bindings)
- `promise` values and types returned from an `async` function don't auto-collapse into a "flat promise" like in JS (more on this later)
-
## Types and `async` functions
### `async` function type signatures
@@ -158,7 +159,7 @@ let authenticate = async () => {
let checkAuth = async () => {
switch await authenticate() {
| _ => Console.log("ok")
- | exception JsExn(e) =>
+ | exception JsExn(e) =>
switch JsExn.message(e) {
| Some(msg) => Console.log("JS error thrown: " ++ msg)
| None => Console.log("Some other exception has been thrown")
@@ -224,12 +225,11 @@ async function fetchData(param) {
try {
val = await GlobalAPI.fetchUserMail("user1");
val$1 = await GlobalAPI.fetchUserMail("user2");
- }
- catch (raw_err){
+ } catch (raw_err) {
var err = Caml_js_exceptions.internalToOCamlException(raw_err);
if (err.RE_EXN_ID === "JsError") {
console.log("Some error occurred", err._1);
- return ;
+ return;
}
throw err;
}
@@ -323,4 +323,3 @@ let login = async (email: string, password: string) => {
}
}
```
-
diff --git a/pages/docs/manual/v12.0.0/attribute.mdx b/pages/docs/manual/v12.0.0/attribute.mdx
index cea6170a2..3a11f007d 100644
--- a/pages/docs/manual/v12.0.0/attribute.mdx
+++ b/pages/docs/manual/v12.0.0/attribute.mdx
@@ -16,6 +16,7 @@ let mode = "dev"
let mode2 = mode
```
+
```js
var mode2 = "dev";
```
@@ -52,9 +53,11 @@ type student = {
let customDouble = foo => foo * 2
@deprecated("Use SomeOther.customTriple instead")
-let customTriple = foo => foo * 3
+let customTriple = foo => foo * 3
```
+
```js
+
```
@@ -77,8 +80,9 @@ There's a second category of attributes, called "extension points" (a remnant te
```res
%raw("var a = 1")
```
+
```js
-var a = 1
+var a = 1;
```
@@ -87,4 +91,4 @@ Extension points are attributes that don't _annotate_ an item; they _are_ the it
Extension points start with `%`. A standalone extension point (akin to a standalone regular attribute) starts with `%%`.
-For a list of all extension points and their usage, please refer to the [Syntax Lookup](/syntax-lookup) page.
\ No newline at end of file
+For a list of all extension points and their usage, please refer to the [Syntax Lookup](/syntax-lookup) page.
diff --git a/pages/docs/manual/v12.0.0/bind-to-global-js-values.mdx b/pages/docs/manual/v12.0.0/bind-to-global-js-values.mdx
index 17d5954a2..a13e2bd44 100644
--- a/pages/docs/manual/v12.0.0/bind-to-global-js-values.mdx
+++ b/pages/docs/manual/v12.0.0/bind-to-global-js-values.mdx
@@ -16,6 +16,7 @@ Some JS values, like `setTimeout`, live in the global scope. You can bind to the
@val external setTimeout: (unit => unit, int) => float = "setTimeout"
@val external clearTimeout: float => unit = "clearTimeout"
```
+
```js
// Empty output
```
@@ -46,6 +47,7 @@ type timerId
let id = setTimeout(() => Console.log("hello"), 100)
clearTimeout(id)
```
+
```js
var id = setTimeout(function (param) {
console.log("hello");
@@ -70,6 +72,7 @@ If you want to bind to a value inside a global module, e.g. `Math.random`, attac
@scope("Math") @val external random: unit => float = "random"
let someNumber = random()
```
+
```js
var someNumber = Math.random();
```
@@ -84,6 +87,7 @@ you can bind to an arbitrarily deep object by passing a tuple to `scope`:
@val @scope(("window", "location", "ancestorOrigins"))
external length: int = "length"
```
+
```js
// Empty output
```
@@ -106,6 +110,7 @@ switch %external(__DEV__) {
| None => Console.log("production mode")
}
```
+
```js
var match = typeof __DEV__ === "undefined" ? undefined : __DEV__;
@@ -130,8 +135,9 @@ switch %external(__filename) {
| None => Console.log("non-node environment")
};
```
+
```js
-var match = typeof (__filename) === "undefined" ? undefined : (__filename);
+var match = typeof __filename === "undefined" ? undefined : __filename;
if (match !== undefined) {
console.log(match);
diff --git a/pages/docs/manual/v12.0.0/bind-to-js-function.mdx b/pages/docs/manual/v12.0.0/bind-to-js-function.mdx
index 1f0fe26a7..2d83189f1 100644
--- a/pages/docs/manual/v12.0.0/bind-to-js-function.mdx
+++ b/pages/docs/manual/v12.0.0/bind-to-js-function.mdx
@@ -15,6 +15,7 @@ Binding a JS function is like binding any other value:
@module("path") external dirname: string => string = "dirname"
let root = dirname("/User/github") // returns "User"
```
+
```js
var Path = require("path");
var root = Path.dirname("/User/github");
@@ -32,10 +33,10 @@ ReScript has [labeled arguments](function.md#labeled-arguments) (that can also b
// MyGame.js
function draw(x, y, border) {
- // suppose `border` is optional and defaults to false
+ // suppose `border` is optional and defaults to false
}
-draw(10, 20)
-draw(20, 20, true)
+draw(10, 20);
+draw(20, 20, true);
```
It'd be nice if on ReScript's side, we can bind & call `draw` while labeling things a bit:
@@ -49,6 +50,7 @@ external draw: (~x: int, ~y: int, ~border: bool=?) => unit = "draw"
draw(~x=10, ~y=20, ~border=true)
draw(~x=10, ~y=20)
```
+
```js
var MyGame = require("MyGame");
@@ -71,6 +73,7 @@ external draw: (~x: int, ~y: int, ~border: bool=?) => unit = "draw"
draw(~x=10, ~y=20)
draw(~y=20, ~x=10)
```
+
```js
var MyGame = require("MyGame");
@@ -93,6 +96,7 @@ type document // abstract type for a document object
let el = getElementById(doc, "myId")
```
+
```js
var el = document.getElementById("myId");
```
@@ -122,18 +126,20 @@ type sessionResult
@send
@scope(("checkout", "sessions"))
-external createCheckoutSession: (stripe, createSession) =>
- Promise.t
= "create"
+external createCheckoutSession: (stripe, createSession) =>
+Promise.t = "create"
-let stripe = make("sk_...")
+let stripe = make("sk\_...")
let session = stripe->createCheckoutSession({})
-```
+
+````
```js
import Stripe from "stripe";
var stripe = new Stripe("sk_...");
var session = stripe.checkout.sessions.create({});
-```
+````
+
## Variadic Function Arguments
@@ -148,6 +154,7 @@ external join: array => string = "join"
let v = join(["a", "b"])
```
+
```js
var Path = require("path");
var v = Path.join("a", "b");
@@ -172,6 +179,7 @@ If you can exhaustively enumerate the many forms an overloaded JS function can t
@module("MyGame") external drawDog: (~giveName: string) => unit = "draw"
@module("MyGame") external draw: (string, ~useRandomAnimal: bool) => unit = "draw"
```
+
```js
// Empty output
```
@@ -212,6 +220,7 @@ external padLeft: (
padLeft("Hello World", #Int(4))
padLeft("Hello World", #Str("Message from ReScript: "))
```
+
```js
padLeft("Hello World", 4);
padLeft("Hello World", "Message from ReScript: ");
@@ -239,6 +248,7 @@ external readFileSync: (
readFileSync(~name="xx.txt", #useAscii)
```
+
```js
var Fs = require("fs");
Fs.readFileSync("xx.txt", "ascii");
@@ -266,6 +276,7 @@ external testIntType: (
=> int = "testIntType"
testIntType(#inBinary)
```
+
```js
testIntType(21);
```
@@ -316,11 +327,12 @@ let register = rl =>
->on(#close(event => ()))
->on(#line(line => Console.log(line)));
```
+
```js
function register(rl) {
return rl
- .on("close", function($$event) {})
- .on("line", function(line) {
+ .on("close", function ($$event) {})
+ .on("line", function (line) {
console.log(line);
});
}
@@ -347,6 +359,7 @@ processOnExit(exitCode =>
Console.log("error code: " ++ Int.toString(exitCode))
);
```
+
```js
process.on("exit", function (exitCode) {
console.log("error code: " + exitCode.toString());
@@ -355,7 +368,7 @@ process.on("exit", function (exitCode) {
-The `@as("exit")` and the placeholder `_` argument together indicates that you want the first argument to compile to the string `"exit"`. You can also use any JSON literal with `as`: `` @as(json`true`) ``, `` @as(json`{"name": "John"}`) ``, etc.
+The `@as("exit")` and the placeholder `_` argument together indicates that you want the first argument to compile to the string `"exit"`. You can also use any JSON literal with `as`: ``@as(json`true`)``, ``@as(json`{"name": "John"}`)``, etc.
## Ignore arguments
@@ -382,9 +395,9 @@ doSomething("test");
Many JS libraries have callbacks which rely on this (the source), for example:
```js
-x.onload = function(v) {
- console.log(this.response + v)
-}
+x.onload = function (v) {
+ console.log(this.response + v);
+};
```
Here, `this` would point to `x` (actually, it depends on how `onload` is called, but we digress). It's not correct to declare `x.onload` of type `(. unit) -> unit`. Instead, we introduced a special attribute, `this`, which allows us to type `x` as so:
@@ -398,6 +411,7 @@ type x
@get external resp: x => int = "response"
setOnload(x, @this (o, v) => Console.log(resp(o) + v))
```
+
```js
x.onload = function (v) {
var o = this;
@@ -430,6 +444,7 @@ let test = dom => {
}
}
```
+
```js
function test(dom) {
var elem = dom.getElementById("haha");
@@ -440,7 +455,6 @@ function test(dom) {
return 2;
}
}
-
```
@@ -475,7 +489,7 @@ let filename = "index.res"
let result = await sh`ls ${filename}`
```
-```js
+```js
import * as $$Bun from "bun";
var filename = "index.res";
var result = await $$Bun.$`ls ${filename}`;
diff --git a/pages/docs/manual/v12.0.0/bind-to-js-object.mdx b/pages/docs/manual/v12.0.0/bind-to-js-object.mdx
index c6fcc831c..f6d5df135 100644
--- a/pages/docs/manual/v12.0.0/bind-to-js-object.mdx
+++ b/pages/docs/manual/v12.0.0/bind-to-js-object.mdx
@@ -36,6 +36,7 @@ type person = {
let johnName = john.name
```
+
```js
var MySchool = require("MySchool");
@@ -57,9 +58,10 @@ type action = {
let action = {type_: "ADD_USER"}
```
+
```js
var action = {
- type: "ADD_USER"
+ type: "ADD_USER",
};
```
@@ -81,15 +83,11 @@ let value = {foo: 7, bar: "baz"}
```
```js
-var value = [
- 7,
- "baz"
-];
+var value = [7, "baz"];
```
-
### Bind Using ReScript Object
Alternatively, you can use [ReScript object](object.md) to model a JS object too:
@@ -107,6 +105,7 @@ type person = {
let johnName = john["name"]
```
+
```js
var MySchool = require("MySchool");
@@ -126,7 +125,9 @@ type textarea
@set external setName: (textarea, string) => unit = "name"
@get external getName: textarea => string = "name"
```
+
```js
+
```
@@ -145,6 +146,7 @@ let i32arr = create(3)
i32arr->set(0, 42)
Console.log(i32arr->get(0))
```
+
```js
var i32arr = new Int32Array(3);
i32arr[0] = 42;
@@ -174,6 +176,7 @@ type t
let date = createDate()
```
+
```js
var date = new Date();
```
@@ -189,6 +192,7 @@ type t
@new @module external book: unit => t = "Book"
let myBook = book()
```
+
```js
var Book = require("Book");
var myBook = new Book();
diff --git a/pages/docs/manual/v12.0.0/build-configuration-schema.mdx b/pages/docs/manual/v12.0.0/build-configuration-schema.mdx
index a9c454341..c4484b9a7 100644
--- a/pages/docs/manual/v12.0.0/build-configuration-schema.mdx
+++ b/pages/docs/manual/v12.0.0/build-configuration-schema.mdx
@@ -15,7 +15,7 @@ export const Docson = dynamic(
{
ssr: false,
loading: () => Loading...
,
- }
+ },
);
export default function BuildConfigurationSchemaPage() {
diff --git a/pages/docs/manual/v12.0.0/build-external-stdlib.mdx b/pages/docs/manual/v12.0.0/build-external-stdlib.mdx
index 66123a3dd..50e98c884 100644
--- a/pages/docs/manual/v12.0.0/build-external-stdlib.mdx
+++ b/pages/docs/manual/v12.0.0/build-external-stdlib.mdx
@@ -10,6 +10,7 @@ canonical: "/docs/manual/v12.0.0/build-external-stdlib"
**Since 9.0**
Your ReScript project depends on the `rescript` package as a [`devDependency`](https://docs.npmjs.com/specifying-dependencies-and-devdependencies-in-a-package-json-file), which includes our compiler, build system and runtime like `Belt`. However, you had to move it to `dependency` in `package.json` if you publish your code:
+
- To Docker or other low-storage deployment devices.
- For pure JS/TS consumers who probably won't install `rescript` in their own project.
@@ -33,7 +34,7 @@ Then add this to `rescript.json`:
```json
{
// ...
- "external-stdlib" : "@rescript/std"
+ "external-stdlib": "@rescript/std"
}
```
diff --git a/pages/docs/manual/v12.0.0/control-flow.mdx b/pages/docs/manual/v12.0.0/control-flow.mdx
index 600684cb4..ac7248ab8 100644
--- a/pages/docs/manual/v12.0.0/control-flow.mdx
+++ b/pages/docs/manual/v12.0.0/control-flow.mdx
@@ -23,6 +23,7 @@ let message = if isMorning {
"Hello!"
}
```
+
```js
var message = isMorning ? "Good morning!" : "Hello!";
```
@@ -38,6 +39,7 @@ if showMenu {
displayMenu()
}
```
+
```js
if (showMenu) {
displayMenu();
@@ -57,9 +59,10 @@ if showMenu {
()
}
```
+
```js
if (showMenu) {
- displayMenu()
+ displayMenu();
}
```
@@ -82,6 +85,7 @@ We also have ternary sugar, but **we encourage you to prefer if-else when possib
```res
let message = isMorning ? "Good morning!" : "Hello!"
```
+
```js
var message = isMorning ? "Good morning!" : "Hello!";
```
@@ -101,8 +105,9 @@ for i in startValueInclusive to endValueInclusive {
Console.log(i)
}
```
+
```js
-for(var i = startValueInclusive; i <= endValueInclusive; ++i){
+for (var i = startValueInclusive; i <= endValueInclusive; ++i) {
console.log(i);
}
```
@@ -117,8 +122,9 @@ for x in 1 to 3 {
Console.log(x)
}
```
+
```js
-for(var x = 1; x <= 3; ++x){
+for (var x = 1; x <= 3; ++x) {
console.log(x);
}
```
@@ -134,8 +140,9 @@ for i in startValueInclusive downto endValueInclusive {
Console.log(i)
}
```
+
```js
-for(var i = startValueInclusive; i >= endValueInclusive; --i){
+for (var i = startValueInclusive; i >= endValueInclusive; --i) {
console.log(i);
}
```
@@ -150,8 +157,9 @@ for x in 3 downto 1 {
Console.log(x)
}
```
+
```js
-for(var x = 3; x >= 1; --x){
+for (var x = 3; x >= 1; --x) {
console.log(x);
}
```
@@ -169,6 +177,7 @@ while testCondition {
// body here
}
```
+
```js
while (testCondition) {
// body here
@@ -194,18 +203,19 @@ while !break.contents {
}
}
```
+
```js
var $$break = {
- contents: false
+ contents: false,
};
-while(!$$break.contents) {
+while (!$$break.contents) {
if (Math.random() > 0.3) {
$$break.contents = true;
} else {
console.log("Still running");
}
-};
+}
```
diff --git a/pages/docs/manual/v12.0.0/converting-from-js.mdx b/pages/docs/manual/v12.0.0/converting-from-js.mdx
index 37ed1e330..56bf51e6f 100644
--- a/pages/docs/manual/v12.0.0/converting-from-js.mdx
+++ b/pages/docs/manual/v12.0.0/converting-from-js.mdx
@@ -7,6 +7,7 @@ canonical: "/docs/manual/v12.0.0/converting-from-js"
# Converting from JS
ReScript offers a unique project conversion methodology which:
+
- Ensures minimal disruption to your teammates (very important!).
- Remove the typical friction of verifying conversion's correctness and performance guarantees.
- Doesn't force you to search for pre-made binding libraries made by others. **ReScript doesn't need the equivalent of TypeScript's `DefinitelyTyped`**.
@@ -20,7 +21,7 @@ Run `npm install rescript` on your project, then imitate our [New Project](insta
Let's work on converting a file called `src/main.js`.
```js
-const school = require('school');
+const school = require("school");
const defaultId = 10;
@@ -52,11 +53,12 @@ function queryResult(usePayload, payload) {
}
`)
```
+
```js
// Generated by ReScript, PLEASE EDIT WITH CARE
-'use strict';
+"use strict";
-const school = require('school');
+const school = require("school");
const defaultId = 10;
@@ -107,6 +109,7 @@ function queryResult(usePayload, payload) {
}
`)
```
+
```js
// Generated by ReScript, PLEASE EDIT WITH CARE
'use strict';
@@ -148,7 +151,9 @@ let queryResult = (usePayload, payload) => {
}
}
```
+
```js
+
```
@@ -178,7 +183,9 @@ let queryResult = (usePayload, payload) => {
}
}
```
+
```js
+
```
@@ -200,9 +207,10 @@ let queryResult = (usePayload, payload) => {
}
}
```
+
```js
// Generated by ReScript, PLEASE EDIT WITH CARE
-'use strict';
+"use strict";
var School = require("school");
@@ -255,9 +263,10 @@ let queryResult = (usePayload, payload) => {
}
}
```
+
```js
// Generated by ReScript, PLEASE EDIT WITH CARE
-'use strict';
+"use strict";
var School = require("school");
@@ -279,6 +288,7 @@ exports.queryResult = queryResult;
We've:
+
- introduced an opaque types for `school` and `student` to prevent misuse of their values
- typed the payload as a record with only the `student` field
- typed `getStudentById` as the sole method of `student`
diff --git a/pages/docs/manual/v12.0.0/dict.mdx b/pages/docs/manual/v12.0.0/dict.mdx
index 07569fe66..110461383 100644
--- a/pages/docs/manual/v12.0.0/dict.mdx
+++ b/pages/docs/manual/v12.0.0/dict.mdx
@@ -25,28 +25,21 @@ let d2 = Dict.fromArray([("A", 5), ("B", 6)])
```js
let d = {
A: 5,
- B: 6
+ B: 6,
};
let d2 = Object.fromEntries([
- [
- "A",
- 5
- ],
- [
- "B",
- 6
- ]
+ ["A", 5],
+ ["B", 6],
]);
-
```
A few things to note here:
-* Using the first class `dict{}` syntax compiles cleanly to a JavaScript object directly
-* Using `Dict.fromArray` is useful when you need to create a dictionary programatically
+- Using the first class `dict{}` syntax compiles cleanly to a JavaScript object directly
+- Using `Dict.fromArray` is useful when you need to create a dictionary programatically
## Access
@@ -74,7 +67,7 @@ let dict{"C": ?c} = d
let d = {
A: 5,
B: 6,
- C: 7
+ C: 7,
};
let a = d["A"];
@@ -85,11 +78,13 @@ let b$1 = b !== undefined ? b : undefined;
let c = d.C;
```
+
> In the Destructuring example, we're using the `?` optional pattern match syntax to pull out the `C` key value as an optional, regardless of if the dict has it or not.
## Pattern matching
+
Dictionaries have first class support for pattern matching. Read more in the [dedicated guide on pattern matching and destructring in ReScript](pattern-matching-destructuring.md#match-on-dictionaries).
## Updating and setting values
@@ -107,7 +102,7 @@ d->Dict.set("C", 7)
```js
let d = {
A: 5,
- B: 6
+ B: 6,
};
d["C"] = 7;
@@ -151,10 +146,9 @@ function decodeUser(json) {
if (typeof email === "string") {
return {
name: name,
- email: email
+ email: email,
};
}
-
}
```
diff --git a/pages/docs/manual/v12.0.0/editor-code-analysis.mdx b/pages/docs/manual/v12.0.0/editor-code-analysis.mdx
index cce661ff3..b2aa4f457 100644
--- a/pages/docs/manual/v12.0.0/editor-code-analysis.mdx
+++ b/pages/docs/manual/v12.0.0/editor-code-analysis.mdx
@@ -28,7 +28,7 @@ ReScript’s language design allows for accurate and efficient dead code analysi
### Deactivation
-- Run: `> ReScript: Stop Code Analyzer`
+- Run: `> ReScript: Stop Code Analyzer`
- Or click “Stop Code Analyzer” in the status bar
### Result
@@ -100,7 +100,6 @@ Removing these often uncovers further unused logic.
Components never referenced in production should be removed, unless explicitly preserved.
-
## Keeping Some Dead Code
### Use `@dead` and `@live`
diff --git a/pages/docs/manual/v12.0.0/editor-plugins.mdx b/pages/docs/manual/v12.0.0/editor-plugins.mdx
index 331b6e2b0..02b1aceba 100644
--- a/pages/docs/manual/v12.0.0/editor-plugins.mdx
+++ b/pages/docs/manual/v12.0.0/editor-plugins.mdx
@@ -9,7 +9,6 @@ canonical: "/docs/manual/v12.0.0/editor-plugins"
This section is about the editor plugin for ReScript. It adds syntax highlighting, autocomplete, type hints, formatting, code navigation, code analysis for `.res` and `.resi` files.
-
## Plugins
- [VSCode](https://marketplace.visualstudio.com/items?itemName=chenglou92.rescript-vscode)
@@ -24,7 +23,6 @@ We don't officially support these; use them at your own risk!
- [IDEA](https://github.com/reasonml-editor/reasonml-idea-plugin)
- [Emacs](https://github.com/jjlee/rescript-mode)
-
## Code analysis
The code analysis provides extra checks for your ReScript project, such as detecting dead code and unhandled exceptions. It's powered by [reanalyze](https://github.com/rescript-association/reanalyze), which is built into the extension — no separate install required.
@@ -51,30 +49,38 @@ Look [here](editor-code-analysis) for a more detailed guide about how to use the
- Doesn't support cross-package dead code analysis in monorepos. Run it per package instead.
## Editor features
+
Below are features and configurations of the editor tooling that might be good to know about.
### Pipe completions
+
Pipes (`->`) are a huge and important part of the ReScript language, for many reasons. Because of that, extra care has gone into the editor experience for using pipes.
#### Default pipe completion rules for non-builtin types
+
By default, using `->` will give completions from the module where the type of the expression you're piping on is defined. So, if you're piping on something of the type `SomeModule.t` (like `someValue->`) then you'll get completions for all functions defined in `SomeModule` that take the type `t` as the first unlabelled argument.
#### Pipe completions for builtin types
+
For builtin types, completion will automatically happen based on the _standard library module_ for that type. So, `array` types will get completions from the `Array` module, `string` gets completions from `String`, and so on.
There is a way to enhance this behavior via configuration, described further down in this document.
### Dot completion enhancements
+
In ReScript, using a dot (`.`) normally means "access record field". But, because using `.` to trigger completions is so pervasive in for example JavaScript, we extend `.` to trigger completions in more scenarios than just for record field access.
This behavior has the following important implications:
+
- Improves discoverability (E.g. using a `.` will reveal important pipe completions)
- Enables a more natural completion flow for people used to JavaScript, where dots power more completions naturally
Below is a list of all the scenarios where using dots trigger completion in addition to the normal record field completion.
#### Objects
+
When writing a `.` on something that's a [structural object](object.md), you'll get completions for those object properties. Example:
+
```res
let obj = {
"first": true,
@@ -89,6 +95,7 @@ let x = obj.
```
#### Pipe completions for anything
+
When writing `.` on _anything_, the editor will try to do pipe completion for the value on the left of the `.`. Example:
```res
@@ -103,12 +110,14 @@ let x = arr.
```
### `@editor.completeFrom` for drawing completions from additional modules
+
You can configure any type you have control over to draw pipe completions from additional modules, in addition to the main module where the type is defined, via the `@editor.completeFrom` decorator. This is useful in many different scenarios:
-* When you, for various reasons, need to have your type definition separate from its "main module". Could be because of cyclic dependencies, a need for the type to be in a recursive type definition chain, and so on.
-* You have separate modules with useful functions for your type but that you don't want to (or can't) include in the main module of that type.
+- When you, for various reasons, need to have your type definition separate from its "main module". Could be because of cyclic dependencies, a need for the type to be in a recursive type definition chain, and so on.
+- You have separate modules with useful functions for your type but that you don't want to (or can't) include in the main module of that type.
Let's look at an example:
+
```res
// Types.res
// In this example types need to live separately in their own file, for various reasons
@@ -125,6 +134,7 @@ module HtmlInput = {
In the example above, if we try and pipe on something of the type `Types.htmlInput`, we'll get no completions because there are no functions in `Types` that take `htmlInput` as its first unlabelled argument. But, better DX would be for the editor to draw completions from our util functions for `htmlInput` in the `Utils.HtmlInput` module.
With `@editor.completeFrom`, we can fix this. Let's look at an updated example:
+
```res
// Types.res
@editor.completeFrom(Utils.HtmlInput)
@@ -143,21 +153,26 @@ Now when piping on a value of the type `Types.htmlInput`, the editor tooling wil
> You can point out multiple modules to draw completions from for a type either by repeating `@editor.completeFrom` with a single module path each time, or by passing an array with all the module paths you want to include, like `@editor.completeFrom([Utils.HtmlInput, HtmlInputUtils])`.
### Configuring the editor via `editor` in `rescript.json`
+
There's certain configuration you can do for the editor on a per project basis in `rescript.json`. Below lists all of the configuration available.
#### `autocomplete` for pipe completion
-The `autocomplete` property of `editor` in `rescript.json` let's you map types to modules _on the project level_ that you want the editor to leverage when doing autocomplete for pipes.
+
+The `autocomplete` property of `editor` in `rescript.json` let's you map types to modules _on the project level_ that you want the editor to leverage when doing autocomplete for pipes.
This is useful in scenarios like:
-* You have your own util module(s) for builtin types. Maybe you have an `ArrayExtra` with helpers for arrays that you want to get completions from whenever dealing with arrays.
-* You have your own util module(s) for types you don't control yourself (and therefore can't use `@editor.completeFrom`), like from external packages you install.
+
+- You have your own util module(s) for builtin types. Maybe you have an `ArrayExtra` with helpers for arrays that you want to get completions from whenever dealing with arrays.
+- You have your own util module(s) for types you don't control yourself (and therefore can't use `@editor.completeFrom`), like from external packages you install.
To configure, you pass `autocomplete` an object where the keys are the _path to the type_ you want to target, and then an array of the path to each module you want to include for consideration for pipe completions.
Let's take two examples.
##### Enhancing completion for builtin types
+
First, let's look at including our own `ArrayExtra` in all completions for `array`:
+
```json
{
"editor": {
@@ -169,6 +184,7 @@ First, let's look at including our own `ArrayExtra` in all completions for `arra
```
Now, when using pipes on arrays, you'll get completions both from the standard library array functions, and also from your own `ArrayExtra` module.
+
```res
let x = [1, 2, 3]->
@@ -181,12 +197,14 @@ let x = [1, 2, 3]->
```
##### Enhancing completion for non-builtin types
+
Now, let's look at an example of when you have a non-builtin type that you don't have control over.
In this example, imagine this:
-* We're writing an app using `fastify`
-* We're using an external package that provides the necessary bindings in a `Fastify` module
-* We've got our own extra file `FastifyExtra` that has various custom util functions that operate on the main type `Fastify.t`
+
+- We're writing an app using `fastify`
+- We're using an external package that provides the necessary bindings in a `Fastify` module
+- We've got our own extra file `FastifyExtra` that has various custom util functions that operate on the main type `Fastify.t`
We now want the editor to always suggest completions from the `FastifyExtra` module, in addition to the regular completions from the main `Fastify` module.
diff --git a/pages/docs/manual/v12.0.0/embed-raw-javascript.mdx b/pages/docs/manual/v12.0.0/embed-raw-javascript.mdx
index b42675f4c..fb81f44e0 100644
--- a/pages/docs/manual/v12.0.0/embed-raw-javascript.mdx
+++ b/pages/docs/manual/v12.0.0/embed-raw-javascript.mdx
@@ -21,11 +21,12 @@ function greet(m) {
}
`)
```
+
```js
// look ma, regular JavaScript!
var message = "hello";
function greet(m) {
- console.log(m)
+ console.log(m);
}
```
@@ -49,10 +50,11 @@ let add = %raw(`
Console.log(add(1, 2))
```
+
```js
-var add = function(a, b) {
+var add = function (a, b) {
console.log("hello from raw JavaScript!");
- return a + b
+ return a + b;
};
console.log(add(1, 2));
@@ -61,6 +63,7 @@ console.log(add(1, 2));
The above code:
+
- declared a ReScript variable `add`,
- with the raw JavaScript value of a function declaration,
- then called that function in ReScript.
@@ -79,10 +82,11 @@ let f = (x, y) => {
x + y
}
```
+
```js
function f(x, y) {
debugger;
- return x + y | 0;
+ return (x + y) | 0;
}
```
diff --git a/pages/docs/manual/v12.0.0/equality-comparison.mdx b/pages/docs/manual/v12.0.0/equality-comparison.mdx
index d3dc3f302..f932f9fda 100644
--- a/pages/docs/manual/v12.0.0/equality-comparison.mdx
+++ b/pages/docs/manual/v12.0.0/equality-comparison.mdx
@@ -9,7 +9,8 @@ canonical: "/docs/manual/v12.0.0/equality-comparison"
ReScript has shallow equality `===`, deep equality `==`, and comparison operators `>`, `>=`, `<`, and `<=`.
## Shallow equality
-The shallow equality operator `===` compares two values and either compiles to `===` or a `bool` if the equality is known to the compiler.
+
+The shallow equality operator `===` compares two values and either compiles to `===` or a `bool` if the equality is known to the compiler.
It behaves the same as the strict equality operator `===` in JavaScript.
Using `===` will never add a runtime cost.
@@ -23,10 +24,11 @@ let t3 = { "foo": "bar" } === { "foo": "bar"} // false
let doStringsMatch = (s1: string, s2: string) => s1 === s2
```
+
```js
var t1 = true;
var t2 = "foo" === "foo";
-var t3 = ({ foo: "bar" }) === ({ foo: "bar" });
+var t3 = { foo: "bar" } === { foo: "bar" };
function doStringsMatch(s1, s2) {
return s1 === s2;
@@ -36,9 +38,10 @@ function doStringsMatch(s1, s2) {
## Deep equality
+
ReScript has the deep equality operator `==` to check deep equality of two items, which is very different from the loose equality operator like `==` in JavaScript.
-When using `==` in ReScript it will never compile to `==` in JavaScript,
+When using `==` in ReScript it will never compile to `==` in JavaScript,
it will either compile to `===`, a runtime call to an internal function that deeply compares the equality, or a `bool` if the equality is known to the compiler.
@@ -50,6 +53,7 @@ let t3 = { "foo": "bar" } == { "foo": "bar"} // true
let doStringsMatch = (s1: string, s2: string) => s1 == s2
```
+
```js
import * as Caml_obj from "./stdlib/caml_obj.js";
@@ -61,6 +65,7 @@ function doStringsMatch(s1, s2) {
return s1 === s2;
}
```
+
`==` will compile to `===` (or a `bool` if the compiler can determine equality) when:
@@ -69,27 +74,31 @@ function doStringsMatch(s1, s2) {
- Comparing variants or polymorphic variants that do not have constructor values
`==` will compile to a runtime check for deep equality when:
+
- Comparing `array`, `tuple`, `list`, `object`, `record`, or regular expression `Re.t`
- Comparing variants or polymorphic variants that have constructor values
> When using `==` pay close attention to the JavaScript output if you're not sure what `==` will compile to.
## Comparison
+
ReScript has operators for comparing values that compile to the the same operator in JS, a runtime check using an internal function, or a `bool` if the equality is known to the compiler,
-| operator | comparison |
-| --- | ----------- |
-| `>` | greater than |
-| `>=` | greater than or equal |
-| `<` | less than |
-| `<=` | less than or equal |
+| operator | comparison |
+| -------- | --------------------- |
+| `>` | greater than |
+| `>=` | greater than or equal |
+| `<` | less than |
+| `<=` | less than or equal |
Comparison can be done on any type.
An operator will compile to the same operator (or a `bool` if the compiler can determine equality) when:
+
- Comparing `int`, `float`, `string`, `char`, `bool`
An operator will compile to a runtime check for deep equality when:
+
- Comparing `array`, `tuple`, `list`, `object`, `record`, or regular expression (`Re.t`)
- Comparing variants or polymorphic variants
@@ -101,6 +110,7 @@ let t1 = 1 > 10
let compareArray = (a: array, b: array) => a > b
let compareOptions = (a: option, b: option) => a < b
```
+
```js
import * as Caml_obj from "./stdlib/caml_obj.js";
@@ -114,12 +124,14 @@ var compareArray = Caml_obj.greaterthan;
var compareOptions = Caml_obj.lessthan;
```
+
## Performance of runtime equality checks
+
The runtime equality check ReScript uses is quite fast and should be adequate for almost all use cases.
For small objects it can be 2x times faster than alternative deep compare functions such as Lodash's [`_.isEqual`](https://lodash.com/docs/4.17.15#isEqual).
For larger objects instead of using `==` you could manually use a faster alternative such as [fast-deep-compare](https://www.npmjs.com/package/fast-deep-equal), or write a custom comparator function.
-[This repo](https://github.com/jderochervlk/rescript-perf) has benchmarks comparing results of different libraries compared to ReScript's built-in equality function.
\ No newline at end of file
+[This repo](https://github.com/jderochervlk/rescript-perf) has benchmarks comparing results of different libraries compared to ReScript's built-in equality function.
diff --git a/pages/docs/manual/v12.0.0/exception.mdx b/pages/docs/manual/v12.0.0/exception.mdx
index 176c48c9e..38f277677 100644
--- a/pages/docs/manual/v12.0.0/exception.mdx
+++ b/pages/docs/manual/v12.0.0/exception.mdx
@@ -17,15 +17,18 @@ exception InputClosed(string)
// later on
throw(InputClosed("The stream has closed!"))
```
+
```js
import * as Primitive_exceptions from "./stdlib/Primitive_exceptions.js";
-let InputClosed = /* @__PURE__ */Primitive_exceptions.create("Playground.InputClosed");
+let InputClosed = /* @__PURE__ */ Primitive_exceptions.create(
+ "Playground.InputClosed",
+);
throw {
RE_EXN_ID: InputClosed,
_1: "The stream has closed!",
- Error: new Error()
+ Error: new Error(),
};
```
@@ -55,6 +58,7 @@ let result =
| Not_found => 0 // Default value if getItem throws
}
```
+
```js
import * as Primitive_exceptions from "./stdlib/Primitive_exceptions.js";
@@ -64,7 +68,7 @@ function getItem(item) {
}
throw {
RE_EXN_ID: "Not_found",
- Error: new Error()
+ Error: new Error(),
};
}
@@ -96,6 +100,7 @@ switch list{1, 2, 3}->List.getExn(4) {
| exception Not_found => Console.log("No such item found!")
}
```
+
```js
import * as Stdlib_List from "./stdlib/Stdlib_List.js";
import * as Primitive_exceptions from "./stdlib/Primitive_exceptions.js";
@@ -105,16 +110,19 @@ let exit = 0;
let item;
try {
- item = Stdlib_List.getExn({
- hd: 1,
- tl: {
- hd: 2,
+ item = Stdlib_List.getExn(
+ {
+ hd: 1,
tl: {
- hd: 3,
- tl: /* [] */0
- }
- }
- }, 4);
+ hd: 2,
+ tl: {
+ hd: 3,
+ tl: /* [] */ 0,
+ },
+ },
+ },
+ 4,
+ );
exit = 1;
} catch (raw_exn) {
let exn = Primitive_exceptions.internalToException(raw_exn);
@@ -149,7 +157,8 @@ let divide = (a, b) =>
try divide(2, 0)->Console.log catch {
| Invalid_argument(msg) => Console.log(msg) // Denominator is zero
}
-```
+
+````
```js
import * as Primitive_int from "./stdlib/Primitive_int.js";
@@ -176,7 +185,7 @@ try {
throw msg;
}
}
-```
+````
@@ -212,29 +221,18 @@ function decodeUser(json) {
let match = json["name"];
let match$1 = json["age"];
if (typeof match === "string" && typeof match$1 === "number") {
- return [
- match,
- match$1 | 0
- ];
+ return [match, match$1 | 0];
}
throw {
RE_EXN_ID: "Assert_failure",
- _1: [
- "playground.res",
- 6,
- 11
- ],
- Error: new Error()
+ _1: ["playground.res", 6, 11],
+ Error: new Error(),
};
}
throw {
RE_EXN_ID: "Assert_failure",
- _1: [
- "playground.res",
- 8,
- 9
- ],
- Error: new Error()
+ _1: ["playground.res", 8, 9],
+ Error: new Error(),
};
}
@@ -257,7 +255,6 @@ try {
Exception thrown to signal that the given arguments do not make sense. This
exception takes a string as an argument.
-
```res example
let isValidEmail = email => {
@@ -270,14 +267,14 @@ let isValidEmail = email => {
}
}
-
let isValid = try isValidEmail("rescript.org") catch {
| Failure(msg) => {
- Console.error(msg)
- false
- }
+Console.error(msg)
+false
}
-```
+}
+
+````
```js
import * as Primitive_exceptions from "./stdlib/Primitive_exceptions.js";
@@ -308,7 +305,7 @@ try {
throw msg;
}
}
-```
+````
@@ -316,7 +313,6 @@ try {
Exception thrown by integer division and remainder operations when their second argument is zero.
-
```res example
// ReScript throws `Division_by_zero` if the denominator is zero
@@ -325,7 +321,8 @@ let result = try Some(10 / 0) catch {
}
Console.log(result) // None
-```
+
+````
```js
import * as Primitive_int from "./stdlib/Primitive_int.js";
@@ -345,7 +342,7 @@ try {
}
console.log(result);
-```
+````
@@ -353,22 +350,21 @@ console.log(result);
To distinguish between JavaScript exceptions and ReScript exceptions, ReScript namespaces JS exceptions under the `JsExn(payload)` variant. To catch an exception thrown from the JS side:
-
Throw an exception from JS:
```js
// Example.js
exports.someJsFunctionThatThrows = () => {
- throw new Error("A Glitch in the Matrix!");
-}
+ throw new Error("A Glitch in the Matrix!");
+};
```
Then catch it from ReScript:
```res
// import the method in Example.js
-@module("./Example")
+@module("./Example")
external someJsFunctionThatThrows: () => unit = "someJsFunctionThatThrows"
try {
@@ -399,6 +395,7 @@ let myTest = () => {
JsError.throwWithMessage("Hello!")
}
```
+
```js
import * as Stdlib_JsError from "./stdlib/Stdlib_JsError.js";
@@ -414,9 +411,9 @@ Then you can catch it from the JS side:
```js
// after importing `myTest`...
try {
- myTest()
+ myTest();
} catch (e) {
- console.log(e.message) // "Hello!"
+ console.log(e.message); // "Hello!"
}
```
@@ -431,6 +428,7 @@ let myTest = () => {
JsExn.throw("some non-error value!")
}
```
+
```js
function myTest() {
throw "some non-error value!";
@@ -444,9 +442,9 @@ Then you can catch it from the JS side:
```js
// after importing `myTest`...
try {
- myTest()
+ myTest();
} catch (message) {
- console.log(message) // "Hello!"
+ console.log(message); // "Hello!"
}
```
@@ -463,16 +461,19 @@ let myTest = () => {
throw(BadArgument({myMessage: "Oops!"}))
}
```
+
```js
import * as Primitive_exceptions from "./stdlib/Primitive_exceptions.js";
-let BadArgument = /* @__PURE__ */Primitive_exceptions.create("Playground.BadArgument");
+let BadArgument = /* @__PURE__ */ Primitive_exceptions.create(
+ "Playground.BadArgument",
+);
function myTest() {
throw {
RE_EXN_ID: BadArgument,
myMessage: "Oops!",
- Error: new Error()
+ Error: new Error(),
};
}
```
@@ -484,10 +485,10 @@ Then, in your JS:
```js
// after importing `myTest`...
try {
- myTest()
+ myTest();
} catch (e) {
- console.log(e.myMessage) // "Oops!"
- console.log(e.Error.stack) // the stack trace
+ console.log(e.myMessage); // "Oops!"
+ console.log(e.Error.stack); // the stack trace
}
```
diff --git a/pages/docs/manual/v12.0.0/extensible-variant.mdx b/pages/docs/manual/v12.0.0/extensible-variant.mdx
index 51b834fd3..7e7b0f2fb 100644
--- a/pages/docs/manual/v12.0.0/extensible-variant.mdx
+++ b/pages/docs/manual/v12.0.0/extensible-variant.mdx
@@ -21,6 +21,7 @@ type t +=
| Point(float, float)
| Line(float, float, float, float)
```
+
```js
var Caml_exceptions = require("./stdlib/caml_exceptions.js");
@@ -33,18 +34,16 @@ var Line = Caml_exceptions.create("Playground.Line");
-The `..` in the type declaration above defines an extensible variant `type t`. The `+=` operator is then used to add constructors to the given type.
+The `..` in the type declaration above defines an extensible variant `type t`. The `+=` operator is then used to add constructors to the given type.
**Note:** Don't forget the leading `type` keyword when using the `+=` operator!
## Pattern Matching Caveats
-Extensible variants are open-ended, so the compiler will not be able to exhaustively pattern match all available cases. You will always need to provide a default `_` case for every `switch` expression.
-
+Extensible variants are open-ended, so the compiler will not be able to exhaustively pattern match all available cases. You will always need to provide a default `_` case for every `switch` expression.
-
```res
let print = v =>
switch v {
@@ -54,6 +53,7 @@ let print = v =>
| _ => Console.log("Other")
}
```
+
```js
function print(v) {
if (v.RE_EXN_ID === Point) {
@@ -62,7 +62,7 @@ function print(v) {
console.log("Line", [v._1, v._2, v._3, v._4]);
} else {
console.log("Other");
- }
+ }
}
```
@@ -72,4 +72,4 @@ function print(v) {
**Fun fact:** In ReScript, [exceptions](./exception) are actually extensible variants under the hood, so `exception UserError(string)` is equivalent to `type exn += UserError(string)`. It's one of the very few use-case where extensible variants make sense.
-We usually recommend sticking with common [variants](./variant) as much as possible to reap the benefits of exhaustive pattern matching.
\ No newline at end of file
+We usually recommend sticking with common [variants](./variant) as much as possible to reap the benefits of exhaustive pattern matching.
diff --git a/pages/docs/manual/v12.0.0/external.mdx b/pages/docs/manual/v12.0.0/external.mdx
index 829da3879..7ce926d65 100644
--- a/pages/docs/manual/v12.0.0/external.mdx
+++ b/pages/docs/manual/v12.0.0/external.mdx
@@ -9,6 +9,7 @@ canonical: "/docs/manual/v12.0.0/external"
`external` is the primary ReScript feature for bringing in and using JavaScript values.
`external` is like a let binding, but:
+
- The right side of `=` isn't a value; it's the name of the JS value you're referring to.
- The type for the binding is mandatory, since we need to know what the type of that JS value is.
- Can only exist at the top level of a file or module.
@@ -18,6 +19,7 @@ canonical: "/docs/manual/v12.0.0/external"
```res example
@val external setTimeout: (unit => unit, int) => float = "setTimeout"
```
+
```js
// Empty output
```
@@ -60,8 +62,9 @@ let loc = document["location"]
// set a property
document["location"]["href"] = "rescript-lang.org"
```
+
```js
-document.addEventListener("mouseup", function(_event) {
+document.addEventListener("mouseup", function (_event) {
console.log("clicked!");
});
diff --git a/pages/docs/manual/v12.0.0/function.mdx b/pages/docs/manual/v12.0.0/function.mdx
index 8138b32a7..4adf3a2d7 100644
--- a/pages/docs/manual/v12.0.0/function.mdx
+++ b/pages/docs/manual/v12.0.0/function.mdx
@@ -15,6 +15,7 @@ ReScript functions are declared with an arrow and return an expression, just lik
```res prelude
let greet = (name) => "Hello " ++ name
```
+
```js
function greet(name) {
return "Hello " + name;
@@ -30,6 +31,7 @@ This declares a function and assigns to it the name `greet`, which you can call
```res example
greet("world!") // "Hello world!"
```
+
```js
greet("world!");
```
@@ -44,9 +46,10 @@ Multi-arguments functions have arguments separated by comma:
let add = (x, y, z) => x + y + z
add(1, 2, 3) // 6
```
+
```js
function add(x, y, z) {
- return (x + y | 0) + z | 0;
+ return (((x + y) | 0) + z) | 0;
}
```
@@ -62,6 +65,7 @@ let greetMore = (name) => {
part1 ++ " " ++ name
}
```
+
```js
function greetMore(name) {
return "Hello " + name;
@@ -85,6 +89,7 @@ let addCoordinates = (x, y) => {
// ...
addCoordinates(5, 6) // which is x, which is y?
```
+
```js
function addCoordinates(x, y) {
// use x and y here
@@ -106,6 +111,7 @@ let addCoordinates = (~x, ~y) => {
// ...
addCoordinates(~x=5, ~y=6)
```
+
```js
function addCoordinates(x, y) {
// use x and y here
@@ -123,6 +129,7 @@ You can provide the arguments in **any order**:
```res
addCoordinates(~y=6, ~x=5)
```
+
```js
addCoordinates(5, 6);
```
@@ -142,6 +149,7 @@ let drawCircle = (~radius as r, ~color as c) => {
drawCircle(~radius=10, ~color="red")
```
+
```js
function drawCircle(r, c) {
setColor(c);
@@ -164,6 +172,7 @@ let drawCircle = (~radius as r: int, ~color as c: string) => {
// code here
}
```
+
```js
function drawCircle(r, c) {
// code here
@@ -188,6 +197,7 @@ let drawCircle = (~color, ~radius=?) => {
}
}
```
+
```js
var Caml_option = require("./stdlib/caml_option.js");
@@ -225,6 +235,7 @@ let drawCircle: (~color: color, ~radius: int=?) => unit =
}
}
```
+
```js
function drawCircle(color, radius) {
setColor(color);
@@ -257,12 +268,14 @@ let result =
| Some(r) => drawCircle(~color, ~radius=r)
}
```
+
```js
var r = payloadRadius;
-var result = r !== undefined
- ? drawCircle(color, Caml_option.valFromOption(r))
- : drawCircle(color);
+var result =
+ r !== undefined
+ ? drawCircle(color, Caml_option.valFromOption(r))
+ : drawCircle(color);
```
@@ -274,6 +287,7 @@ This quickly gets tedious. We provide a shortcut:
```res
let result = drawCircle(~color, ~radius=?payloadRadius)
```
+
```js
var result = drawCircle(1, undefined);
```
@@ -294,6 +308,7 @@ let drawCircle = (~radius=1, ~color) => {
startAt(radius, radius)
}
```
+
```js
function drawCircle(radiusOpt, color) {
var radius = radiusOpt !== undefined ? radiusOpt : 1;
@@ -313,12 +328,13 @@ ReScript chooses the sane default of preventing a function to be called recursiv
```res example
let rec neverTerminate = () => neverTerminate()
```
+
```js
function neverTerminate(_param) {
- while(true) {
+ while (true) {
_param = undefined;
- continue ;
- };
+ continue;
+ }
}
```
@@ -337,9 +353,10 @@ let rec listHas = (list, item) =>
| list{a, ...rest} => a === item || listHas(rest, item)
}
```
+
```js
function listHas(_list, item) {
- while(true) {
+ while (true) {
var list = _list;
if (!list) {
return false;
@@ -348,8 +365,8 @@ function listHas(_list, item) {
return true;
}
_list = list.tl;
- continue ;
- };
+ continue;
+ }
}
```
@@ -368,19 +385,20 @@ Mutually recursive functions start like a single recursive function using the
let rec callSecond = () => callFirst()
and callFirst = () => callSecond()
```
+
```js
function callSecond(_param) {
- while(true) {
+ while (true) {
_param = undefined;
- continue ;
- };
+ continue;
+ }
}
function callFirst(_param) {
- while(true) {
+ while (true) {
_param = undefined;
- continue ;
- };
+ continue;
+ }
}
```
@@ -390,7 +408,7 @@ function callFirst(_param) {
**Since 11.0**
-To partially apply a function, use the explicit `...` syntax.
+To partially apply a function, use the explicit `...` syntax.
```res
@@ -400,13 +418,14 @@ let addFive = add(5, ...)
```js
function add(a, b) {
- return a + b | 0;
+ return (a + b) | 0;
}
function addFive(extra) {
- return 5 + extra | 0;
+ return (5 + extra) | 0;
}
```
+
## Async/Await
@@ -420,16 +439,18 @@ The output looks like idiomatic JS:
let getUserName = async (userId) => userId
let greetUser = async (userId) => {
- let name = await getUserName(userId)
+ let name = await getUserName(userId)
"Hello " ++ name ++ "!"
}
```
+
```js
async function greetUser(userId) {
var name = await getUserName(userId);
return "Hello " + name + "!";
}
```
+
The return type of `getUser` is inferred to be `promise`.
@@ -456,30 +477,31 @@ let someAsyncFn = async () => {
}
}
```
+
```js
-var SomeReScriptException = /* @__PURE__ */Caml_exceptions.create("Example.SomeReScriptException");
+var SomeReScriptException = /* @__PURE__ */ Caml_exceptions.create(
+ "Example.SomeReScriptException",
+);
async function someAsyncFn(param) {
var data;
try {
data = await somethingThatMightThrow(undefined);
- }
- catch (raw_exn){
+ } catch (raw_exn) {
var exn = Caml_js_exceptions.internalToOCamlException(raw_exn);
if (exn.RE_EXN_ID === "JsError") {
- return ;
+ return;
}
if (exn.RE_EXN_ID === SomeReScriptException) {
- return ;
+ return;
}
throw exn;
}
return data;
}
```
-
-
+
## The ignore() Function
diff --git a/pages/docs/manual/v12.0.0/generate-converters-accessors.mdx b/pages/docs/manual/v12.0.0/generate-converters-accessors.mdx
index a066c4421..18f4f865d 100644
--- a/pages/docs/manual/v12.0.0/generate-converters-accessors.mdx
+++ b/pages/docs/manual/v12.0.0/generate-converters-accessors.mdx
@@ -7,6 +7,7 @@ canonical: "/docs/manual/v12.0.0/generate-converters-accessors"
# Generate Converters & Helpers
**Note**: if you're looking for:
+
- `@deriving(jsConverter)` for records
- `@deriving({jsConverter: newType})` for records
- `@deriving(abstract)` for records
@@ -42,14 +43,14 @@ type action =
```js
function submit(param_0) {
- return /* Submit */[param_0];
+ return /* Submit */ [param_0];
}
-var click = /* Click */0;
+var click = /* Click */ 0;
-var cancel = /* Cancel */1;
+var cancel = /* Cancel */ 1;
-exports.click = click;
+exports.click = click;
exports.submit = submit;
exports.cancel = cancel;
```
@@ -59,6 +60,7 @@ exports.cancel = cancel;
Variants constructors with payloads generate functions, payload-less constructors generate plain integers (the internal representation of variants).
**Note**:
+
- The generated accessors are lower-cased.
- You can now use these helpers on the JavaScript side! But don't rely on their actual values please.
@@ -79,7 +81,6 @@ Please note that in case you just want to _pipe a payload into a constructor_, y
Use `@deriving(accessors)` on a record type to create accessors for its record field names.
-
```res
@@ -101,11 +102,11 @@ function name(param) {
var pets = [
{
- name: "bob"
+ name: "bob",
},
{
- name: "bob2"
- }
+ name: "bob2",
+ },
];
console.log(Belt_Array.map(pets, name).join("&"));
diff --git a/pages/docs/manual/v12.0.0/import-export.mdx b/pages/docs/manual/v12.0.0/import-export.mdx
index 213d779e0..b913fec82 100644
--- a/pages/docs/manual/v12.0.0/import-export.mdx
+++ b/pages/docs/manual/v12.0.0/import-export.mdx
@@ -16,9 +16,10 @@ Unlike JavaScript, ReScript doesn't have or need import statements:
// Inside School.res
let studentMessage = Student.message
```
+
```js
var Student = require("./Student.res.js");
-var studentMessage = Student.message
+var studentMessage = Student.message;
```
diff --git a/pages/docs/manual/v12.0.0/import-from-export-to-js.mdx b/pages/docs/manual/v12.0.0/import-from-export-to-js.mdx
index 520ab5f0e..0f547f797 100644
--- a/pages/docs/manual/v12.0.0/import-from-export-to-js.mdx
+++ b/pages/docs/manual/v12.0.0/import-from-export-to-js.mdx
@@ -36,10 +36,12 @@ Use the `module` [external](external.md):
@module("path") external dirname: string => string = "dirname"
let root = dirname("/User/github") // returns "User"
```
+
```js
import * as Path from "path";
var root = Path.dirname("/User/github");
```
+
```js
var Path = require("path");
var root = Path.dirname("/User/github");
@@ -65,10 +67,12 @@ By omitting the string argument to `module`, you bind to the whole JS module:
@module external leftPad: (string, int) => string = "./leftPad"
let paddedResult = leftPad("hi", 5)
```
+
```js
import * as LeftPad from "./leftPad";
var paddedResult = LeftPad("hi", 5);
```
+
```js
var LeftPad = require("./leftPad");
var paddedResult = LeftPad("hi", 5);
@@ -88,6 +92,7 @@ Use the value `default` on the right hand side:
@module("./student") external studentName: string = "default"
Console.log(studentName)
```
+
```js
import Student from "./student";
var studentName = Student;
@@ -107,7 +112,8 @@ var studentName = Student;
external myJson: JSON.t = "default"
Console.log(myJson)
-```
+
+````
```javascript
import MyJsonJson from "./myJson.json" with {"type": "json", "some-exotic-identifier": "someValue"};
@@ -115,12 +121,14 @@ import MyJsonJson from "./myJson.json" with {"type": "json", "some-exotic-identi
var myJson = MyJsonJson;
console.log(myJson);
-```
+````
+
This above imports the local `./myJson.json` file, adding import attributes.
This is how it works:
+
1. Instead of passing a string or tuple to `@module`, pass a record.
2. This record should have a `from` key. The value of that is where you want the module to be imported from (just like the regular string to `@module` is).
3. It should also have a `with` key, with another record where you put all the import attributes you want emitted.
@@ -129,9 +137,11 @@ Notice `\"some-exotic-identifier"` - you'll need to escape any key that's not a
Also notice `type_`. Since `type` is a reserved keyword in ReScript, you can use `type_` instead. It will be output as `type` in the JavaScript code.
## Dynamic Import
+
Leveraging JavaScript's [dynamic `import`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/import) to reduce bundle size and lazy load code as needed is easy in ReScript. It's also a little bit more convenient than in regular JavaScript because you don't need to keep track of file paths manually with ReScript's module system.
### Dynamically Importing Parts of a Module
+
Use the `import` function to dynamically import a specific part of a module. Put whatever `let` binding you want to import in there, and you'll get a `promise` back resolving to that specific binding.
Let's look at an example. Imagine the following file `MathUtils.res`:
@@ -150,9 +160,10 @@ let main = async () => {
let add = await import(MathUtils.add)
let onePlusOne = add(1, 1)
- Console.log(onePlusOne)
+Console.log(onePlusOne)
}
-```
+
+````
```javascript
async function main() {
var add = await import("./MathUtils.mjs").then(function(m) {
@@ -162,21 +173,25 @@ async function main() {
var onePlusOne = add(1, 1);
console.log(onePlusOne);
}
-```
+````
+
### Dynamically Importing an Entire Module
+
The syntax for importing a whole module looks a little different, since we are operating on the module syntax level; instead of using `import`, you may simply `await` the module itself:
+
```rescript
// App.res
let main = async () => {
module Utils = await MathUtils
- let twoPlusTwo = Utils.add(2, 2)
- Console.log(twoPlusTwo)
+let twoPlusTwo = Utils.add(2, 2)
+Console.log(twoPlusTwo)
}
-```
+
+````
```javascript
async function main() {
var Utils = await import("./MathUtils.mjs");
@@ -184,7 +199,8 @@ async function main() {
var twoPlusTwo = Utils.add(2, 2);
console.log(twoPlusTwo);
}
-```
+````
+
## Export To JavaScript
@@ -204,7 +220,7 @@ export default name = "Al";
```js
// teacher.js
-import studentName from 'student.js';
+import studentName from "student.js";
```
A JavaScript default export is really just syntax sugar for a named export implicitly called `default` (now you know!). So to export a default value from ReScript, you can just do:
@@ -215,6 +231,7 @@ A JavaScript default export is really just syntax sugar for a named export impli
// ReScriptStudent.res
let default = "Bob"
```
+
```js
var $$default = "Bob";
@@ -223,13 +240,11 @@ exports.default = $$default;
// informal transpiler-compatible marker of a default export compiled from JavaScript module
exports.__esModule = true;
```
+
```js
var $$default = "Bob";
-export {
- $$default,
- $$default as default,
-}
+export { $$default, $$default as default };
```
@@ -238,7 +253,7 @@ You can then import this default export as usual on the JS side:
```js
// teacher2.js
-import studentName from 'ReScriptStudent.js';
+import studentName from "ReScriptStudent.js";
```
If your JavaScript's default import is transpiled by Babel/Webpack/Jest into CommonJS `require`s, we've taken care of that too! See the CommonJS output tab for `__esModule`.
diff --git a/pages/docs/manual/v12.0.0/inlining-constants.mdx b/pages/docs/manual/v12.0.0/inlining-constants.mdx
index c9e9dea31..1c321c02b 100644
--- a/pages/docs/manual/v12.0.0/inlining-constants.mdx
+++ b/pages/docs/manual/v12.0.0/inlining-constants.mdx
@@ -9,16 +9,16 @@ canonical: "/docs/manual/v12.0.0/inlining-constants"
Sometimes, in the JavaScript output, you might want a certain value to be forcefully inlined. For example:
```js
-if (process.env.mode === 'development') {
- console.log("Dev-only code here!")
+if (process.env.mode === "development") {
+ console.log("Dev-only code here!");
}
```
The reason is that your JavaScript bundler (e.g. Webpack) might turn that into:
```js
-if ('production' === 'development') {
- console.log("Dev-only code here!")
+if ("production" === "development") {
+ console.log("Dev-only code here!");
}
```
@@ -37,6 +37,7 @@ if (process["env"]["mode"] === mode) {
Console.log("Dev-only code here!")
}
```
+
```js
var mode = "development";
@@ -61,6 +62,7 @@ if (process["env"]["mode"] === mode) {
Console.log("Dev-only code here!")
}
```
+
```js
if (process.env.mode === "development") {
console.log("Dev-only code here!");
diff --git a/pages/docs/manual/v12.0.0/installation.mdx b/pages/docs/manual/v12.0.0/installation.mdx
index baa53d270..bad0c1aef 100644
--- a/pages/docs/manual/v12.0.0/installation.mdx
+++ b/pages/docs/manual/v12.0.0/installation.mdx
@@ -5,6 +5,7 @@ canonical: "/docs/manual/v12.0.0/installation"
---
# Installation
+
## Prerequisites
- [Node.js](https://nodejs.org/) version >= 20
@@ -28,18 +29,23 @@ You can start it with any of the aforementioned package managers or `npx`.
```sh example
npm create rescript-app@latest
```
+
```sh
npx create-rescript-app
```
+
```sh
yarn create rescript-app
```
+
```sh
pnpm create rescript-app
```
+
```sh
bun create rescript-app
```
+
- Follow the steps of the setup.
@@ -54,7 +60,7 @@ bun create rescript-app
That compiles your ReScript into JavaScript, then uses Node.js to run said JavaScript.
-**When taking your first steps with ReScript, we recommend you use our unique workflow of keeping a tab open for the generated JS file** (`.res.js`/`.res.mjs`), so that you can learn how ReScript transforms into JavaScript. Not many languages output clean JavaScript code you can inspect and learn from! With our [VS Code extension](https://marketplace.visualstudio.com/items?itemName=chenglou92.rescript-vscode), use the command "ReScript: Open the compiled JS file for this implementation file" to open the generated JS file for the currently active ReScript source file.
+**When taking your first steps with ReScript, we recommend you use our unique workflow of keeping a tab open for the generated JS file** (`.res.js`/`.res.mjs`), so that you can learn how ReScript transforms into JavaScript. Not many languages output clean JavaScript code you can inspect and learn from! With our [VS Code extension](https://marketplace.visualstudio.com/items?itemName=chenglou92.rescript-vscode), use the command "ReScript: Open the compiled JS file for this implementation file" to open the generated JS file for the currently active ReScript source file.
During development, instead of running `npm run res:build` each time to compile, use `npm run res:dev` to start a watcher that recompiles automatically after file changes.
@@ -65,48 +71,62 @@ If you already have a JavaScript project into which you'd like to add ReScript y
### Quick Setup
In the root directory of your project, execute:
+
```sh
npm create rescript-app@latest
```
+
```sh
npx create-rescript-app
```
+
```sh
yarn create rescript-app
```
+
```sh
pnpm create rescript-app
```
+
```sh
bun create rescript-app
```
+
`create-rescript-app` will tell you that a `package.json` file has been detected and ask you if it should install ReScript into your project. Just follow the steps accordingly.
### Manual Setup
+
- Install ReScript locally:
+
```sh
npm install rescript
```
+
```sh
yarn add rescript
```
+
```sh
pnpm install rescript
```
+
```sh
bun install rescript
```
+
```sh
// you will need deno configured to have a node_modules folder
deno install npm:rescript --allow-scripts
```
+
+
- Create a ReScript build configuration file (called `rescript.json`) at the root:
```json
{
diff --git a/pages/docs/manual/v12.0.0/interop-cheatsheet.mdx b/pages/docs/manual/v12.0.0/interop-cheatsheet.mdx
index 2a17a8023..f8e57ae6a 100644
--- a/pages/docs/manual/v12.0.0/interop-cheatsheet.mdx
+++ b/pages/docs/manual/v12.0.0/interop-cheatsheet.mdx
@@ -63,9 +63,10 @@ This is a glossary with examples. All the features are described by later pages.
let add = %raw("(a, b) => a + b")
%%raw("const a = 1")
```
+
```js
-var add = ((a, b) => a + b);
-const a = 1
+var add = (a, b) => a + b;
+const a = 1;
```
@@ -77,6 +78,7 @@ const a = 1
```res example
@val external setTimeout: (unit => unit, int) => float = "setTimeout"
```
+
```js
// Empty output
```
@@ -96,6 +98,7 @@ let someNumber = random()
@val @scope(("window", "location", "ancestorOrigins"))
external length: int = "length"
```
+
```js
var someNumber = Math.random();
```
@@ -110,6 +113,7 @@ var someNumber = Math.random();
let a = Some(5) // compiles to 5
let b = None // compiles to undefined
```
+
```js
var a = 5;
var b;
@@ -128,6 +132,7 @@ let result1: Nullable.t = Nullable.make("hello")
let result2: Nullable.t = Nullable.fromOption(Some(10))
let result3: option = Nullable.toOption(Nullable.make(10))
```
+
```js
import * as Caml_option from "./stdlib/caml_option.js";
import * as Core__Nullable from "./stdlib/core__Nullable.js";
@@ -165,6 +170,7 @@ var result3 = Caml_option.nullable_to_opt(10);
->filter(a => mod(a, 2) == 0)
->Console.log
```
+
```js
console.log(
[1, 2, 3]
@@ -173,7 +179,7 @@ console.log(
})
.filter(function (a) {
return a % 2 === 0;
- })
+ }),
);
```
@@ -187,6 +193,7 @@ console.log(
@module("path") @variadic
external join: array => string = "join"
```
+
```js
// Empty output
```
@@ -207,7 +214,7 @@ let filename = "index.res"
let result = await sh`ls ${filename}`
```
-```js
+```js
import * as $$Bun from "bun";
var filename = "index.res";
var result = await $$Bun.$`ls ${filename}`;
@@ -223,6 +230,7 @@ var result = await $$Bun.$`ls ${filename}`;
@module("Drawing") external drawCat: unit => unit = "draw"
@module("Drawing") external drawDog: (~giveName: string) => unit = "draw"
```
+
```js
// Empty output
```
@@ -244,6 +252,7 @@ external padLeft: (
padLeft("Hello World", #Int(4))
padLeft("Hello World", #Str("Message from ReScript: "))
```
+
```js
padLeft("Hello World", 4);
padLeft("Hello World", "Message from ReScript: ");
@@ -266,6 +275,7 @@ external convertToFloat: int => float = "%identity"
let age = 10
let gpa = 2.1 +. convertToFloat(age)
```
+
```js
var age = 10;
var gpa = 2.1 + 10;
diff --git a/pages/docs/manual/v12.0.0/introduction.mdx b/pages/docs/manual/v12.0.0/introduction.mdx
index 147fb1a60..62e314cc9 100644
--- a/pages/docs/manual/v12.0.0/introduction.mdx
+++ b/pages/docs/manual/v12.0.0/introduction.mdx
@@ -9,6 +9,7 @@ canonical: "/docs/manual/v12.0.0/introduction"
ReScript is a robustly typed language that compiles to efficient and human-readable JavaScript. It comes with a lightning fast compiler toolchain that scales to any codebase size.
## Part of the JavaScript ecosystem
+
ReScript looks like JS, acts like JS, and compiles to the highest quality of clean, readable and performant JS, directly runnable in browsers and Node. This means you can pick up ReScript and access the vast JavaScript ecosystem and tooling as if you've known ReScript for a long time!
You don't need to learn new package managers, bundlers, frameworks, or testing libraries. All of the knowledge you have about doing web development with JavaScript can be applied to building applications with Rescript.
@@ -16,13 +17,15 @@ You don't need to learn new package managers, bundlers, frameworks, or testing l
ReScript code can be [imported into JavaScript code](/docs/manual/latest/import-from-export-to-js#export-to-javascript), can [generate types for TypeScript](/docs/manual/latest/typescript-integration), and ReScript can [import code written in JavaScript or TypeScript](/docs/manual/latest/import-from-export-to-js#import-from-javascript).
## Type System
- - Is deliberately curated to be a simple subset most folks will have an easier time to use.
- - Has **no** pitfalls, aka the type system is "sound" (the types will always be correct). E.g. If a type isn't marked as nullable, its value will never lie and let through some `undefined` value silently. **ReScript code has no null/undefined errors**.
- - Is the same for everyone. No knobs, no bikeshedding opportunity.
- - Runs extremely fast precisely thanks to its simplicity and curation. It's one of the fastest compiler & build system toolchains for JavaScript development.
- - **Doesn't need type annotations**. Annotate as much or as little as you'd like. The types are inferred by the language (and, again, are guaranteed correct).
+
+- Is deliberately curated to be a simple subset most folks will have an easier time to use.
+- Has **no** pitfalls, aka the type system is "sound" (the types will always be correct). E.g. If a type isn't marked as nullable, its value will never lie and let through some `undefined` value silently. **ReScript code has no null/undefined errors**.
+- Is the same for everyone. No knobs, no bikeshedding opportunity.
+- Runs extremely fast precisely thanks to its simplicity and curation. It's one of the fastest compiler & build system toolchains for JavaScript development.
+- **Doesn't need type annotations**. Annotate as much or as little as you'd like. The types are inferred by the language (and, again, are guaranteed correct).
## Compiler
+
### Compiles to Optimized JavaScript
JavaScript's been aggressively optimized by talented engineers over a long span. Unfortunately, even for seasoned JS devs, it can be hard to know how to properly leverage JS's performance. ReScript's type system and compiler naturally guides you toward writing code that's very often performant by default, with good leverage of various Just-In-Time optimizations (hidden classes, inline caching, avoiding deopts, etc).
@@ -53,4 +56,4 @@ The JavaScript ecosystem is very reliant on dependencies. Shipping the final pro
- Function- and module-level code elimination is facilitated by the well-engineered type system and purity analysis.
- At the global level, ReScript generates code that is naturally friendly to dead code elimination done by bundling tools such as [Rollup](https://github.com/rollup/rollup) and [Closure Compiler](https://developers.google.com/closure/compiler/), after its own sophisticated elimination pass.
-- The same applies for ReScript's own tiny runtime (which is written in ReScript itself).
\ No newline at end of file
+- The same applies for ReScript's own tiny runtime (which is written in ReScript itself).
diff --git a/pages/docs/manual/v12.0.0/json.mdx b/pages/docs/manual/v12.0.0/json.mdx
index 7b500b560..c24f3eb5c 100644
--- a/pages/docs/manual/v12.0.0/json.mdx
+++ b/pages/docs/manual/v12.0.0/json.mdx
@@ -23,8 +23,9 @@ external parseIntoMyData: string => data = "parse"
let result = parseIntoMyData(`{"names": ["Luke", "Christine"]}`)
let name1 = result.names[0]
```
+
```js
-var result = JSON.parse("{\"names\": [\"Luke\", \"Christine\"]}");
+var result = JSON.parse('{"names": ["Luke", "Christine"]}');
var name1 = result.names[0];
```
@@ -41,11 +42,9 @@ Use [`JSON.stringify`](api/core/json#value-stringify) if your data is of type `J
```res example
Console.log(JSON.stringifyAny(["Amy", "Joe"]))
```
+
```js
-console.log(JSON.stringify([
- "Amy",
- "Joe"
-]));
+console.log(JSON.stringify(["Amy", "Joe"]));
```
@@ -60,6 +59,7 @@ Use the `@module` attribute to import JSON files directly.
@module external studentNames: JSON.t = "./students.json"
Console.log(studentNames)
```
+
```js
import * as StudentsJson from "./students.json";
@@ -67,6 +67,7 @@ var studentNames = StudentsJson;
console.log(studentNames);
```
+
```js
var StudentsJson = require("./students.json");
diff --git a/pages/docs/manual/v12.0.0/jsx.mdx b/pages/docs/manual/v12.0.0/jsx.mdx
index eefc78691..20f522e5a 100644
--- a/pages/docs/manual/v12.0.0/jsx.mdx
+++ b/pages/docs/manual/v12.0.0/jsx.mdx
@@ -19,6 +19,7 @@ ReScript supports the JSX syntax, with some slight differences compared to the o
```res
```
+
```js
React.createElement(MyComponent, {
name: "ReScript",
@@ -34,6 +35,7 @@ becomes
```res
MyComponent.createElement(~name="ReScript", ~children=list{}, ())
```
+
```js
React.createElement(MyComponent, {
name: "ReScript",
@@ -49,10 +51,16 @@ React.createElement(MyComponent, {
```res
child1 child2
```
+
```js
-React.createElement("div", {
- onClick: handler
-}, child1, child2);
+React.createElement(
+ "div",
+ {
+ onClick: handler,
+ },
+ child1,
+ child2,
+);
```
@@ -64,10 +72,16 @@ becomes
```res
div(~onClick=handler, ~children=list{child1, child2}, ())
```
+
```js
-React.createElement("div", {
- onClick: handler
-}, child1, child2);
+React.createElement(
+ "div",
+ {
+ onClick: handler,
+ },
+ child1,
+ child2,
+);
```
@@ -79,6 +93,7 @@ React.createElement("div", {
```res
<> child1 child2 >
```
+
```js
React.createElement(React.Fragment, undefined, child1, child2);
```
@@ -92,6 +107,7 @@ becomes
```res
list{child1, child2}
```
+
```js
React.createElement(React.Fragment, undefined, child1, child2);
```
@@ -105,6 +121,7 @@ React.createElement(React.Fragment, undefined, child1, child2);
```res
child1 child2
```
+
```js
React.createElement(MyComponent, { children: null }, child1, child2);
```
@@ -118,8 +135,14 @@ This is the syntax for passing a list of two items, `child1` and `child2`, to th
```res
MyComponent.createElement(~children=list{child1, child2}, ())
```
+
```js
-React.createElement(MyComponent.make, MyComponent.makeProps(null, undefined), child1, child2);
+React.createElement(
+ MyComponent.make,
+ MyComponent.makeProps(null, undefined),
+ child1,
+ child2,
+);
```
@@ -146,6 +169,7 @@ Here's a JSX tag that shows most of the features.
{React.string("hello")}
```
+
```js
React.createElement(MyComponent, {
children: React.createElement("div", undefined, "hello"),
@@ -153,7 +177,7 @@ React.createElement(MyComponent, {
stringAttribute: "string",
intAttribute: 1,
forcedOptional: "hello",
- onClick: handleClick
+ onClick: handleClick,
});
```
@@ -177,10 +201,11 @@ JSX props spread is supported now, but in a stricter way than in JS.
```res
```
+
```js
React.createElement(Comp, {
a: "a",
- b: "b"
+ b: "b",
});
```
@@ -217,11 +242,12 @@ JSX supports punning. ` ` is just a shorthand for `
```
+
```js
React.createElement(MyComponent, {
isLoading: true,
text: text,
- onClick: onClick
+ onClick: onClick,
});
```
@@ -235,7 +261,7 @@ Consequently, a JSX component can cram in a few more props before reaching for e
**Since 11.1**
-JSX now supports lowercase tags with hyphens in their name. This allows to bind
+JSX now supports lowercase tags with hyphens in their name. This allows to bind
to web components.
Note though that props names can't have hyphens, you should use `@as` to bind to
@@ -246,10 +272,11 @@ such props in your custom `JsxDOM.domProps` type ([see generic JSX transform](#g
```res
```
+
```js
React.createElement("model-viewer", {
"touch-actions": "pan-y",
- src: src
+ src: src,
});
```
@@ -259,15 +286,17 @@ React.createElement("model-viewer", {
**Since 11.1**
-While ReScript comes with first class support for JSX in React, it's also possible to have ReScript delegate JSX to other frameworks. You do that by configuring a _generic JSX transform_.
+While ReScript comes with first class support for JSX in React, it's also possible to have ReScript delegate JSX to other frameworks. You do that by configuring a _generic JSX transform_.
This is what you need to do to use a generic JSX transform:
+
1. Make sure you have a ReScript module that [implements the functions and types necessary for the JSX transform](#implementing-a-generic-jsx-transform-module).
2. Configure `rescript.json` to delegated JSX to that module.
That's it really. We'll expand on each point below.
### Configuration
+
You configure a generic JSX transform by putting any module name in the `module` config of JSX in `rescript.json`. This can be _any valid module name_. Example part from `rescript.json`:
```json
@@ -283,9 +312,11 @@ This will now put the `Preact` module in control of the generated JSX calls. The
`@react.component` will still be available, and so is a generic `@jsx.component` notation. Both work the same way.
### Usage Example
+
Here's a quick usage example (the actual definition of `Preact.res` comes below):
First, configure `rescript.json`:
+
```json
"jsx": {
"module": "Preact"
@@ -293,6 +324,7 @@ First, configure `rescript.json`:
```
Now you can build Preact components:
+
```rescript
// Name.res
@jsx.component // or @react.component if you want
@@ -300,12 +332,15 @@ let make = (~name) => Preact.string(`Hello ${name}!`)
```
And you can use them just like normal with JSX:
+
```rescript
let name =
```
#### File level configuration
+
You can configure what JSX transform is used at the file level via `@@jsxConfig`, just like before. Like:
+
```rescript
@@jsxConfig({module_: "Preact"})
```
@@ -313,6 +348,7 @@ You can configure what JSX transform is used at the file level via `@@jsxConfig`
This can be convenient if you're mixing different JSX frameworks in the same project.
### Implementing a generic JSX transform module
+
Below is a full list of everything you need in a generic JSX transform module, including code comments to clarify. It's an example implementation of a `Preact` transform, so when doing this for other frameworks you'd of course adapt what you import from, and so on.
> You can easily copy-paste-and-adapt this to your needs if you're creating bindings to a JSX framework. Most often, all you'll need to change is what the `@module("") external` points to, so the runtime calls point to the correct JS module.
@@ -338,8 +374,8 @@ external jsxs: (component<'props>, 'props) => element = "jsxs"
@module("preact")
external jsxsKeyed: (component<'props>, 'props, ~key: string=?, @ignore unit) => element = "jsxs"
-/* These identity functions and static values below are optional, but lets
-you move things easily to the `element` type. The only required thing to
+/* These identity functions and static values below are optional, but lets
+you move things easily to the `element` type. The only required thing to
define though is `array`, which the JSX transform will output. */
external array: array => element = "%identity"
@val external null: element = "null"
@@ -355,9 +391,9 @@ type fragmentProps = {children?: element}
/* The Elements module is the equivalent to the ReactDOM module in React. This holds things relevant to _lowercase_ JSX elements. */
module Elements = {
- /* Here you can control what props lowercase JSX elements should have.
- A base that the React JSX transform uses is provided via JsxDOM.domProps,
- but you can make this anything. The editor tooling will support
+ /* Here you can control what props lowercase JSX elements should have.
+ A base that the React JSX transform uses is provided via JsxDOM.domProps,
+ but you can make this anything. The editor tooling will support
autocompletion etc for your specific type. */
type props = JsxDOM.domProps
@@ -380,4 +416,4 @@ module Elements = {
}
```
-As you can see, most of the things you'll want to implement will be copy paste from the above. But do note that **everything needs to be there unless explicitly noted** or the transform will fail at compile time.
\ No newline at end of file
+As you can see, most of the things you'll want to implement will be copy paste from the above. But do note that **everything needs to be there unless explicitly noted** or the transform will fail at compile time.
diff --git a/pages/docs/manual/v12.0.0/lazy-values.mdx b/pages/docs/manual/v12.0.0/lazy-values.mdx
index 9e541f608..86e4e698c 100644
--- a/pages/docs/manual/v12.0.0/lazy-values.mdx
+++ b/pages/docs/manual/v12.0.0/lazy-values.mdx
@@ -6,7 +6,7 @@ canonical: "/docs/manual/v12.0.0/lazy-values"
# Lazy Value
-If you have some expensive computations you'd like to **defer and cache** subsequently, you can turn them into *lazy* values:
+If you have some expensive computations you'd like to **defer and cache** subsequently, you can turn them into _lazy_ values:
@@ -20,6 +20,7 @@ let expensiveFilesRead = Lazy.make(() => {
readdirSync("./pages")
})
```
+
```js
import * as Lazy from "./stdlib/Lazy.js";
import * as Nodefs from "node:fs";
@@ -28,7 +29,6 @@ let expensiveFilesRead = Lazy.make(() => {
console.log("Reading dir");
return Nodefs.readdirSync("./pages");
});
-
```
@@ -48,6 +48,7 @@ Console.log(Lazy.get(expensiveFilesRead)) // logs "Reading dir" and the director
// Second call. Will just return the already calculated result
Console.log(Lazy.get(expensiveFilesRead)) // logs the directory content
```
+
```js
console.log(Lazy.get(expensiveFilesRead));
@@ -73,6 +74,7 @@ let result = try {
| Not_found => [] // empty array of files
}
```
+
```js
let result;
diff --git a/pages/docs/manual/v12.0.0/let-binding.mdx b/pages/docs/manual/v12.0.0/let-binding.mdx
index 64d9377f0..ae6329cf8 100644
--- a/pages/docs/manual/v12.0.0/let-binding.mdx
+++ b/pages/docs/manual/v12.0.0/let-binding.mdx
@@ -15,6 +15,7 @@ let greeting = "hello!"
let score = 10
let newScore = 10 + score
```
+
```js
var greeting = "hello!";
var score = 10;
@@ -37,6 +38,7 @@ let message = {
}
// `part1` and `part2` not accessible here!
```
+
```js
var message = "hello world";
```
@@ -58,6 +60,7 @@ if displayGreeting {
}
// `message` not accessible here!
```
+
```js
if (displayGreeting) {
console.log("Enjoying the docs so far?");
@@ -99,6 +102,7 @@ let result1 = 0
let result2 = calculate(result1)
let result3 = calculateSomeMore(result2)
```
+
```js
var result1 = 0;
var result2 = calculate(0);
@@ -116,6 +120,7 @@ let result = 0
let result = calculate(result)
let result = calculateSomeMore(result)
```
+
```js
var result = calculate(0);
var result$1 = calculateSomeMore(result);
@@ -135,6 +140,7 @@ Console.log(result) // prints "hello"
let result = 1
Console.log(result) // prints 1
```
+
```js
var result = 1;
console.log("hello");
@@ -162,6 +168,7 @@ module A: {
let b = 4
}
```
+
`%%private` gives you an option to mark private fields directly
```res
@@ -182,4 +189,3 @@ Still, `%%private` is useful in the following scenarios:
- **Code generators.** Some code generators want to hide some values but it is sometimes very hard or time consuming for code generators to synthesize the types for public fields.
- **Quick prototyping.** During prototyping, we still want to hide some values, but the interface file is not stable yet. `%%private` provides you such convenience.
-
diff --git a/pages/docs/manual/v12.0.0/module.mdx b/pages/docs/manual/v12.0.0/module.mdx
index a32561bbe..e1e84c4f1 100644
--- a/pages/docs/manual/v12.0.0/module.mdx
+++ b/pages/docs/manual/v12.0.0/module.mdx
@@ -31,6 +31,7 @@ module School = {
}
}
```
+
```js
function getProfession(person) {
if (person) {
@@ -41,8 +42,8 @@ function getProfession(person) {
}
var School = {
- person1: /* Teacher */0,
- getProfession: getProfession
+ person1: /* Teacher */ 0,
+ getProfession: getProfession,
};
```
@@ -57,8 +58,9 @@ using the `.` notation. This demonstrates modules' utility for namespacing.
let anotherPerson: School.profession = School.Teacher
Console.log(School.getProfession(anotherPerson)) /* "A teacher" */
```
+
```js
-var anotherPerson = /* Teacher */0;
+var anotherPerson = /* Teacher */ 0;
console.log("A teacher");
```
@@ -77,13 +79,14 @@ module MyModule = {
let message = MyModule.NestedModule.message
```
+
```js
var NestedModule = {
- message: message
+ message: message,
};
var MyModule = {
- NestedModule: NestedModule
+ NestedModule: NestedModule,
};
var message = MyModule.NestedModule.message;
@@ -101,6 +104,7 @@ module's name. Instead of writing:
```res
let p = School.getProfession(School.person1)
```
+
```js
var p = School.getProfession(School.person1);
```
@@ -115,6 +119,7 @@ We can write:
open School
let p = getProfession(person1)
```
+
```js
var p = School.getProfession(School.person1);
```
@@ -134,6 +139,7 @@ let p = {
}
/* School's content isn't visible here anymore */
```
+
```js
var p = School.getProfession(School.person1);
```
@@ -185,7 +191,7 @@ var user2 = "Franz";
var User = {
user1: user1,
- user2: user2
+ user2: user2,
};
```
@@ -215,6 +221,7 @@ module ActualComponent = {
let render = () => defaultGreeting ++ " " ++ getAudience(~excited=true)
}
```
+
```js
function getAudience(excited) {
if (excited) {
@@ -226,7 +233,7 @@ function getAudience(excited) {
var BaseComponent = {
defaultGreeting: "Hello",
- getAudience: getAudience
+ getAudience: getAudience,
};
var defaultGreeting = "Hey";
@@ -238,7 +245,7 @@ function render(param) {
var ActualComponent = {
getAudience: getAudience,
defaultGreeting: defaultGreeting,
- render: render
+ render: render,
};
```
@@ -273,6 +280,7 @@ module type EstablishmentType = {
let getProfession: profession => string
}
```
+
```js
// Empty output
```
@@ -317,6 +325,7 @@ module Company: EstablishmentType = {
let person2 = ...
}
```
+
```js
function getProfession(person) {
...
@@ -357,6 +366,7 @@ module type ActualComponent = {
let render: unit => string
}
```
+
```js
// Empty output
```
@@ -378,6 +388,7 @@ module type MyList = {
let myListFun: list<'a> => list<'a>
}
```
+
```js
// Empty output
```
@@ -399,6 +410,7 @@ in the ecosystem to also document the public API of their corresponding modules.
type state = int
let render = (str) => str
```
+
```js
function render(str) {
return str;
@@ -417,7 +429,7 @@ let render: string => string
Modules can be passed to functions! It would be the equivalent of passing a file
as a first-class item. However, modules are at a different "layer" of the
-language than other common concepts, so we can't pass them to *regular*
+language than other common concepts, so we can't pass them to _regular_
functions. Instead, we pass them to special functions called "functors".
The syntax for defining and using functors is very much like the syntax
@@ -425,7 +437,7 @@ for defining and using regular functions. The primary differences are:
- Functors use the `module` keyword instead of `let`.
- Functors take modules as arguments and return a module.
-- Functors *require* annotating arguments.
+- Functors _require_ annotating arguments.
- Functors must start with a capital letter (just like modules/signatures).
Here's an example `MakeSet` functor, that takes in a module of the type
@@ -455,13 +467,14 @@ module MakeSet = (Item: Comparable) => {
}
}
```
+
```js
var List = require("./stdlib/list.js");
function MakeSet(Item) {
- var add = function(currentSet, newItem) {
+ var add = function (currentSet, newItem) {
if (
- List.exists(function(x) {
+ List.exists(function (x) {
return Item.equal(x, newItem);
}, currentSet)
) {
@@ -497,6 +510,7 @@ module IntPair = {
/* IntPair abides by the Comparable signature required by MakeSet */
module SetOfIntPairs = MakeSet(IntPair)
```
+
```js
function equal(param, param$1) {
if (param[0] === param$1[0]) {
@@ -547,6 +561,7 @@ module MakeSet: MakeSetType = (Item: Comparable) => {
...
}
```
+
```js
// Empty output
```
diff --git a/pages/docs/manual/v12.0.0/mutation.mdx b/pages/docs/manual/v12.0.0/mutation.mdx
index 8162d8ec0..ba31f7a82 100644
--- a/pages/docs/manual/v12.0.0/mutation.mdx
+++ b/pages/docs/manual/v12.0.0/mutation.mdx
@@ -17,9 +17,10 @@ Let-bindings are immutable, but you can wrap it with a `ref`, exposed as a recor
```res prelude
let myValue = ref(5)
```
+
```js
var myValue = {
- contents: 5
+ contents: 5,
};
```
@@ -34,6 +35,7 @@ You can get the actual value of a `ref` box through accessing its `contents` fie
```res example
let five = myValue.contents // 5
```
+
```js
var five = myValue.contents;
```
@@ -47,6 +49,7 @@ Assign a new value to `myValue` like so:
```res example
myValue.contents = 6
```
+
```js
myValue.contents = 6;
```
@@ -60,6 +63,7 @@ We provide a syntax sugar for this:
```res example
myValue := 6
```
+
```js
myValue.contents = 6;
```
diff --git a/pages/docs/manual/v12.0.0/null-undefined-option.mdx b/pages/docs/manual/v12.0.0/null-undefined-option.mdx
index 9113030f9..b14e586ad 100644
--- a/pages/docs/manual/v12.0.0/null-undefined-option.mdx
+++ b/pages/docs/manual/v12.0.0/null-undefined-option.mdx
@@ -17,6 +17,7 @@ We represent the existence and nonexistence of a value by wrapping it with the `
```res example
type option<'a> = None | Some('a)
```
+
```js
// Empty output
```
@@ -36,6 +37,7 @@ Here's a normal value:
```res example
let licenseNumber = 5
```
+
```js
var licenseNumber = 5;
```
@@ -54,6 +56,7 @@ let licenseNumber =
None
}
```
+
```js
var licenseNumber = personHasACar ? 5 : undefined;
```
@@ -72,6 +75,7 @@ switch licenseNumber {
Console.log("The person's license number is " ++ Int.toString(number))
}
```
+
```js
var number = licenseNumber;
@@ -95,6 +99,7 @@ The `option` type is common enough that we special-case it when compiling to Jav
```res example
let x = Some(5)
```
+
```js
var x = 5;
```
@@ -108,6 +113,7 @@ simply compiles down to `5`, and
```res example
let x = None
```
+
```js
var x;
```
@@ -125,6 +131,7 @@ The option-to-undefined translation isn't perfect, because on our side, `option`
```res example
let x = Some(Some(Some(5)))
```
+
```js
var x = 5;
```
@@ -138,6 +145,7 @@ This still compiles to `5`, but this gets troublesome:
```res example
let x = Some(None)
```
+
```js
var Caml_option = require("./stdlib/caml_option.js");
@@ -172,6 +180,7 @@ If you're receiving, for example, a JS string that can be `null` and `undefined`
```res example
@module("MyConstant") external myId: Nullable.t = "myId"
```
+
```js
// Empty output
```
@@ -188,6 +197,7 @@ let personId: Nullable.t = Nullable.make("abc123")
let result = validate(personId)
```
+
```js
var MyIdValidator = require("MyIdValidator");
var personId = "abc123";
diff --git a/pages/docs/manual/v12.0.0/object.mdx b/pages/docs/manual/v12.0.0/object.mdx
index abb2011d9..e353859e7 100644
--- a/pages/docs/manual/v12.0.0/object.mdx
+++ b/pages/docs/manual/v12.0.0/object.mdx
@@ -29,6 +29,7 @@ type person = {
"name": string
};
```
+
```js
// Empty output
```
@@ -51,10 +52,11 @@ let me = {
"name": "Big ReScript"
}
```
+
```js
var me = {
- "age": 5,
- "name": "Big ReScript"
+ age: 5,
+ name: "Big ReScript",
};
```
@@ -73,9 +75,10 @@ let me = {
"age": "hello!" // age is a string. No error.
}
```
+
```js
var me = {
- "age": "hello!"
+ age: "hello!",
};
```
@@ -98,6 +101,7 @@ Now the type system will error properly.
```res
let age = me["age"]
```
+
```js
var age = me["age"];
```
@@ -119,6 +123,7 @@ type student = {
student1["name"] = "Mary"
```
+
```js
var MyJSFile = require("MyJSFile");
MyJSFile.student1.name = "Mary";
@@ -148,11 +153,12 @@ let myPoint: point3d = {
"z": 3.0,
}
```
+
```js
var myPoint = {
x: 1.0,
y: 2.0,
- z: 3.0
+ z: 3.0,
};
```
@@ -182,8 +188,9 @@ let loc = document["location"]
// set a property
document["location"]["href"] = "rescript-lang.org"
```
+
```js
-document.addEventListener("mouseup", function(_event) {
+document.addEventListener("mouseup", function (_event) {
console.log("clicked!");
});
var loc = document.location;
diff --git a/pages/docs/manual/v12.0.0/overview.mdx b/pages/docs/manual/v12.0.0/overview.mdx
index bb2269eab..19ea5548d 100644
--- a/pages/docs/manual/v12.0.0/overview.mdx
+++ b/pages/docs/manual/v12.0.0/overview.mdx
@@ -44,14 +44,14 @@ canonical: "/docs/manual/v12.0.0/overview"
### Boolean
-| JavaScript | ReScript |
-| ------------------------------------- | ---------------------------------------------- |
-| `true`, `false` | Same |
-| `!true` | Same |
-| `\|\|`, `&&`, `<=`, `>=`, `<`, `>` | Same |
-| `a === b`, `a !== b` | Same |
-| No deep equality (recursive compare) | `a == b`, `a != b` |
-| `a == b` | No equality with implicit casting (thankfully) |
+| JavaScript | ReScript |
+| ------------------------------------ | ---------------------------------------------- |
+| `true`, `false` | Same |
+| `!true` | Same |
+| `\|\|`, `&&`, `<=`, `>=`, `<`, `>` | Same |
+| `a === b`, `a !== b` | Same |
+| No deep equality (recursive compare) | `a == b`, `a != b` |
+| `a == b` | No equality with implicit casting (thankfully) |
### Number
@@ -185,8 +185,8 @@ canonical: "/docs/manual/v12.0.0/overview"
### Exception
-| JavaScript | ReScript |
-| ----------------------------------------- | -------------------------------------------- |
+| JavaScript | ReScript |
+| ----------------------------------------- | ------------------------------------------------ |
| `throw new SomeError(...)` | `throw(SomeException(...))` |
| `try {a} catch (err) {...} finally {...}` | `try a catch { \| SomeException(err) => ...}` \* |
diff --git a/pages/docs/manual/v12.0.0/pattern-matching-destructuring.mdx b/pages/docs/manual/v12.0.0/pattern-matching-destructuring.mdx
index 9ba00341b..34cb69240 100644
--- a/pages/docs/manual/v12.0.0/pattern-matching-destructuring.mdx
+++ b/pages/docs/manual/v12.0.0/pattern-matching-destructuring.mdx
@@ -25,6 +25,7 @@ let coordinates = (10, 20, 30)
let (x, _, _) = coordinates
Console.log(x) // 10
```
+
```js
var coordinates = [10, 20, 30];
var x = 10;
@@ -49,28 +50,25 @@ type result =
let myResult = Success("You did it!")
let Success(message) = myResult // "You did it!" assigned to `message`
```
+
```js
var student1 = {
name: "John",
- age: 10
+ age: 10,
};
var name = "John";
-var myResult = /* Success */{
- _0: "You did it!"
+var myResult = /* Success */ {
+ _0: "You did it!",
};
-var message = "You did it!"
+var message = "You did it!";
var myArray = [1, 2, 3];
if (myArray.length !== 2) {
throw {
RE_EXN_ID: "Match_failure",
- _1: [
- "playground.res",
- 14,
- 4
- ],
- Error: new Error()
+ _1: ["playground.res", 14, 4],
+ Error: new Error(),
};
}
var item1 = myArray[0];
@@ -82,9 +80,9 @@ var myList = {
hd: 2,
tl: {
hd: 3,
- tl: /* [] */0
- }
- }
+ tl: /* [] */ 0,
+ },
+ },
};
// ...
```
@@ -105,14 +103,17 @@ let displayMessage = (Success(m)) => {
}
displayMessage(Success("You did it!"))
```
+
```js
function displayMessage(m) {
console.log(m._0);
}
-displayMessage(/* Success */{
- _0: "You did it!"
-});
+displayMessage(
+ /* Success */ {
+ _0: "You did it!",
+ },
+);
```
@@ -124,6 +125,7 @@ For a record, you can rename the field while destructuring:
```res
let {name: n} = student1 // "John" assigned to `n`
```
+
```js
var n = "John";
```
@@ -158,6 +160,7 @@ type payload =
| GoodResult(string)
| NoResult
```
+
```js
// Empty output
```
@@ -181,16 +184,19 @@ switch data {
Console.log("Bah.")
}
```
+
```js
var data = {
TAG: "GoodResult",
- _0: "Product shipped!"
+ _0: "Product shipped!",
};
if (typeof data !== "object") {
console.log("Bah.");
} else if (data.TAG === "BadResult") {
- console.log("Something's wrong. The error code is: " + "Product shipped!".toString());
+ console.log(
+ "Something's wrong. The error code is: " + "Product shipped!".toString(),
+ );
} else {
console.log("Success! Product shipped!");
}
@@ -216,6 +222,7 @@ type person =
| Teacher({name: string, age: int})
| Student(student)
```
+
```js
// Empty output
```
@@ -256,11 +263,12 @@ let message = switch person1 {
`Good luck next semester ${name}!`
}
```
+
```js
var person1 = {
TAG: "Teacher",
name: "Jane",
- age: 35
+ age: 35,
};
var message;
@@ -273,18 +281,28 @@ if (person1.TAG === "Teacher") {
var name = match.name;
var match$2 = match.reportCard;
if (match$2.passing) {
- message = "Congrats " + name + ", nice GPA of " + match$2.gpa.toString() + " you got there!";
+ message =
+ "Congrats " +
+ name +
+ ", nice GPA of " +
+ match$2.gpa.toString() +
+ " you got there!";
} else {
var exit = 0;
if (typeof match$1 !== "object") {
- message = match$1 === "Sick" ? "How are you feeling?" : "Good luck next semester " + name + "!";
+ message =
+ match$1 === "Sick"
+ ? "How are you feeling?"
+ : "Good luck next semester " + name + "!";
} else {
exit = 1;
}
if (exit === 1) {
- message = match.reportCard.gpa !== 0.0 ? "Good luck next semester " + name + "!" : "Come back in " + match$1._0.toString() + " days!";
+ message =
+ match.reportCard.gpa !== 0.0
+ ? "Good luck next semester " + name + "!"
+ : "Come back in " + match$1._0.toString() + " days!";
}
-
}
}
```
@@ -292,6 +310,7 @@ if (person1.TAG === "Teacher") {
**Note** how we've:
+
- drilled deep down into the value concisely
- using a **nested pattern check** `"Mary" | "Joe"` and `Vacations | Sabbatical`
- while extracting the `daysLeft` number from the latter case
@@ -311,6 +330,7 @@ let categoryId = switch (isBig, myAnimal) {
| (false, Bird) => 5
}
```
+
```js
var categoryId = isBig ? (myAnimal + 1) | 0 : myAnimal >= 2 ? 5 : 4;
```
@@ -319,10 +339,10 @@ var categoryId = isBig ? (myAnimal + 1) | 0 : myAnimal >= 2 ? 5 : 4;
**Note** how pattern matching on a tuple is equivalent to a 2D table:
-isBig \ myAnimal | Dog | Cat | Bird
------------------|-----|-----|------
-true | 1 | 2 | 3
-false | 4 | 4 | 5
+| isBig \ myAnimal | Dog | Cat | Bird |
+| ---------------- | --- | --- | ---- |
+| true | 1 | 2 | 3 |
+| false | 4 | 4 | 5 |
### Fall-Through Patterns
@@ -340,10 +360,11 @@ switch myStatus {
| Present => Console.log("Hey! How are you?")
}
```
+
```js
var myStatus = {
- TAG: /* Vacations */0,
- _0: 10
+ TAG: /* Vacations */ 0,
+ _0: 10,
};
if (typeof myStatus === "number") {
@@ -369,6 +390,7 @@ switch person1 {
| Student(_) => Console.log("Hey student")
}
```
+
```js
if (person1.TAG === "Teacher") {
console.log("Hi teacher");
@@ -389,6 +411,7 @@ switch myStatus {
| _ => Console.log("Ok.")
}
```
+
```js
if (typeof myStatus !== "object" || myStatus.TAG !== "Vacations") {
console.log("Ok.");
@@ -409,6 +432,7 @@ switch myStatus {
| Sabbatical(_) | Sick | Present => Console.log("Ok.")
}
```
+
```js
if (typeof myStatus !== "object" || myStatus.TAG !== "Vacations") {
console.log("Ok.");
@@ -438,6 +462,7 @@ switch person1 {
}
}
```
+
```js
if (person1.TAG !== "Teacher") {
if ("Jane".reportCard.gpa < 0.5) {
@@ -464,6 +489,7 @@ switch person1 {
Console.log("Heyo")
}
```
+
```js
if (person1.TAG) {
if (person1.reportCard.gpa < 0.5) {
@@ -479,6 +505,7 @@ if (person1.TAG) {
**Note:** Rescript versions < 9.0 had a `when` clause, not an `if` clause. Rescript 9.0 changed `when` to `if`. (`when` may still work, but is deprecated.)
### Match on subtype variants
+
You can refine a variant A to variant B using the [variant type spread syntax](variant.md#variant-type-spreads) in pattern matching. This is possible if variant B [is a subtype of](variant.md#coercion) variant A.
Let's look at an example:
@@ -511,6 +538,7 @@ let greetAnimal = (animal: animals) => {
}
}
```
+
```js
function greetPet(pet) {
if (pet === "Cat") {
@@ -530,26 +558,29 @@ function greetFish(fish) {
function greetAnimal(animal) {
switch (animal) {
- case "Cat" :
- case "Dog" :
+ case "Cat":
+ case "Dog":
return greetPet(animal);
- case "Cod" :
- case "Salmon" :
+ case "Cod":
+ case "Salmon":
return greetFish(animal);
}
}
```
+
Let's break down what we did:
-* Defined two different variants for pets and for fish
-* Wrote a dedicated function per animal type to greet that particular type of animal
-* Combined `pets` and `fish` into a main variant for `animals`
-* Wrote a function that can greet any animal by _spreading_ each sub variant on its own branch, aliasing that spread to a variable, and passing that variable to the dedicated greet function for that specific type
+
+- Defined two different variants for pets and for fish
+- Wrote a dedicated function per animal type to greet that particular type of animal
+- Combined `pets` and `fish` into a main variant for `animals`
+- Wrote a function that can greet any animal by _spreading_ each sub variant on its own branch, aliasing that spread to a variable, and passing that variable to the dedicated greet function for that specific type
Notice how we're able to match on parts of the main variant, as long as the variants are compatible.
The example above aliases the variant type spread to a variable so we can use it in our branch. But, you can just as easily match without aliasing if you don't care about the value:
+
```res
@@ -561,20 +592,22 @@ let isPet = (animal: animals) => {
}
```
+
```js
function isPet(animal) {
switch (animal) {
- case "Cat" :
- case "Dog" :
+ case "Cat":
+ case "Dog":
console.log("A pet!");
return;
- case "Cod" :
- case "Salmon" :
+ case "Cod":
+ case "Salmon":
console.log("Not a pet...");
return;
}
}
```
+
Similarily, if you want to get advanced, you can even pull out a single variant constructor. This works with and without aliases. Example:
@@ -595,6 +628,7 @@ let isPet = (animal: animals) => {
}
```
+
```js
function isPet(animal) {
if (animal === "Dog") {
@@ -604,6 +638,7 @@ function isPet(animal) {
console.log("Not a dog...");
}
```
+
And, thanks to the rules of subtyping, the `Dog` constructor wouldn't _really_ need to be spread inside of the `pets` variant for this to work:
@@ -615,7 +650,7 @@ type pets = Cat | Dog
type fish = Cod | Salmon
type animals = | ...pets | ...fish
-// Notice `dog` isn't spread into the `pets` variant,
+// Notice `dog` isn't spread into the `pets` variant,
// but this still work due to subtyping.
type dog = Dog
@@ -627,6 +662,7 @@ let isPet = (animal: animals) => {
}
```
+
```js
function isPet(animal) {
if (animal === "Dog") {
@@ -636,6 +672,7 @@ function isPet(animal) {
console.log("Not a dog...");
}
```
+
### Match on Exceptions
@@ -650,18 +687,18 @@ switch List.find(i => i === theItem, myItems) {
| exception Not_found => Console.log("No such item found!")
}
```
+
```js
var exit = 0;
var item;
try {
- item = List.find(function(i) {
+ item = List.find(function (i) {
return i === theItem;
}, myItems);
exit = 1;
-}
-catch (raw_exn){
+} catch (raw_exn) {
var exn = Caml_js_exceptions.internalToOCamlException(raw_exn);
if (exn.RE_EXN_ID === "Not_found") {
console.log("No such item found!");
@@ -692,6 +729,7 @@ switch students {
Console.log2("The students are: ", manyStudents)
}
```
+
```js
var students = ["Jane", "Harvey", "Patrick"];
@@ -729,9 +767,10 @@ let rec printStudents = (students) => {
}
printStudents(list{"Jane", "Harvey", "Patrick"})
```
+
```js
function printStudents(_students) {
- while(true) {
+ while (true) {
var students = _students;
if (!students) {
return;
@@ -745,7 +784,7 @@ function printStudents(_students) {
}
console.log("Last student: " + student);
return;
- };
+ }
}
printStudents({
@@ -754,9 +793,9 @@ printStudents({
hd: "Harvey",
tl: {
hd: "Patrick",
- tl: /* [] */0
- }
- }
+ tl: /* [] */ 0,
+ },
+ },
});
```
@@ -767,6 +806,7 @@ printStudents({
You can pattern match on dictionaries just like you can on other ReScript data structures.
When pattern matching on a dictionary it's assumed by default that you're expecting the keys you match on to exist in the dictionary. Example:
+
```res prelude
@@ -782,7 +822,7 @@ let b = switch d {
```js
let d = {
A: 5,
- B: 6
+ B: 6,
};
let b = d.B;
@@ -808,7 +848,7 @@ let b = switch d {
```js
let d = {
A: 5,
- B: 6
+ B: 6,
};
let b = d.B;
@@ -833,6 +873,7 @@ switch coordinates {
| (x, _centerY, _) => Console.log(x)
}
```
+
```js
var coordinates = [10, 20, 30];
var centerY = 20;
@@ -869,18 +910,23 @@ let message = switch person1 {
`Good luck next semester ${name}!`
}
```
+
```js
if (person1.TAG) {
var match$1 = person1.status;
var name = person1.name;
var match$2 = person1.reportCard;
if (match$2.passing) {
- "Congrats " + name + ", nice GPA of " + match$2.gpa.toString() + " you got there!";
+ "Congrats " +
+ name +
+ ", nice GPA of " +
+ match$2.gpa.toString() +
+ " you got there!";
} else if (typeof match$1 === "number") {
if (match$1 !== 0) {
"Good luck next semester " + name + "!";
} else {
- "How are you feeling?";
+ ("How are you feeling?");
}
} else if (person1.reportCard.gpa !== 0.0) {
"Good luck next semester " + name + "!";
@@ -895,12 +941,8 @@ if (person1.TAG) {
default:
throw {
RE_EXN_ID: "Match_failure",
- _1: [
- "playground.res",
- 13,
- 0
- ],
- Error: new Error()
+ _1: ["playground.res", 13, 0],
+ Error: new Error(),
};
}
}
@@ -930,6 +972,7 @@ switch myNullableValue {
| None => Console.log("value is absent")
}
```
+
```js
var myNullableValue = 5;
@@ -950,7 +993,7 @@ Hopefully you can see how pattern matching is a game changer for writing correct
Below is some advice:
-Avoid using the wildcard `_` unnecessarily. Using the wildcard `_` will bypass the compiler's exhaustiveness check. Consequently, the compiler will not be able to notify you of probable errors when you add a new case to a variant. Try only using `_` against infinite possibilities, e.g. string, int, etc.
+Avoid using the wildcard `_` unnecessarily. Using the wildcard `_` will bypass the compiler's exhaustiveness check. Consequently, the compiler will not be able to notify you of probable errors when you add a new case to a variant. Try only using `_` against infinite possibilities, e.g. string, int, etc.
Use the `if` clause sparingly.
@@ -969,6 +1012,7 @@ let optionBoolToBool = opt => {
}
}
```
+
```js
function optionBoolToBool(opt) {
if (opt === undefined) {
@@ -993,6 +1037,7 @@ let optionBoolToBool = opt => {
}
}
```
+
```js
function optionBoolToBool(opt) {
if (opt !== undefined && opt) {
@@ -1018,6 +1063,7 @@ let optionBoolToBool = opt => {
}
}
```
+
```js
function optionBoolToBool(opt) {
if (opt !== undefined && opt) {
@@ -1042,6 +1088,7 @@ let optionBoolToBool = opt => {
}
}
```
+
```js
function optionBoolToBool(opt) {
if (opt !== undefined && opt) {
@@ -1066,6 +1113,7 @@ let optionBoolToBool = opt => {
}
}
```
+
```js
function optionBoolToBool(opt) {
if (opt !== undefined) {
diff --git a/pages/docs/manual/v12.0.0/pipe.mdx b/pages/docs/manual/v12.0.0/pipe.mdx
index c78d33e5b..ce08a693a 100644
--- a/pages/docs/manual/v12.0.0/pipe.mdx
+++ b/pages/docs/manual/v12.0.0/pipe.mdx
@@ -15,6 +15,7 @@ Why would you use it? Imagine you have the following:
```res
validateAge(getAge(parseData(person)))
```
+
```js
validateAge(getAge(parseData(person)));
```
@@ -31,6 +32,7 @@ person
->getAge
->validateAge
```
+
```js
validateAge(getAge(parseData(person)));
```
@@ -46,6 +48,7 @@ Basically, `parseData(person)` is transformed into `person->parseData`, and `get
```res
a(one, two, three)
```
+
```js
a(one, two, three);
```
@@ -59,6 +62,7 @@ is the same as
```res
one->a(two, three)
```
+
```js
a(one, two, three);
```
@@ -80,11 +84,9 @@ _This section requires understanding of [our binding API](bind-to-js-function.md
JavaScript's APIs are often attached to objects, and are often chainable, like so:
```js
-const result = [1, 2, 3].map(a => a + 1).filter(a => a % 2 === 0);
+const result = [1, 2, 3].map((a) => a + 1).filter((a) => a % 2 === 0);
-asyncRequest()
- .setWaitDuration(4000)
- .send();
+asyncRequest().setWaitDuration(4000).send();
```
Assuming we don't need the chaining behavior above, we'd bind to each case of this using [`@send`](/syntax-lookup#send-decorator) from the aforementioned binding API page:
@@ -97,6 +99,7 @@ type request
@send external setWaitDuration: (request, int) => request = "setWaitDuration"
@send external send: request => unit = "send"
```
+
```js
// Empty output
```
@@ -115,12 +118,15 @@ let result = Array.filter(
send(setWaitDuration(asyncRequest(), 4000))
```
+
```js
-var result = [1, 2, 3].map(function(a) {
- return a + 1 | 0;
-}).filter(function(a) {
- return a % 2 === 0;
-});
+var result = [1, 2, 3]
+ .map(function (a) {
+ return (a + 1) | 0;
+ })
+ .filter(function (a) {
+ return a % 2 === 0;
+ });
asyncRequest().setWaitDuration(4000).send();
```
@@ -138,12 +144,15 @@ let result = [1, 2, 3]
asyncRequest()->setWaitDuration(4000)->send
```
+
```js
-var result = [1, 2, 3].map(function(a) {
- return a + 1 | 0;
-}).filter(function(a) {
- return a % 2 === 0;
-});
+var result = [1, 2, 3]
+ .map(function (a) {
+ return (a + 1) | 0;
+ })
+ .filter(function (a) {
+ return a % 2 === 0;
+ });
asyncRequest().setWaitDuration(4000).send();
```
@@ -159,6 +168,7 @@ You can pipe into a variant's constructor as if it was a function:
```res
let result = name->preprocess->Some
```
+
```js
var result = preprocess(name);
```
@@ -172,6 +182,7 @@ We turn this into:
```res
let result = Some(preprocess(name))
```
+
```js
var result = preprocess(name);
```
@@ -199,6 +210,7 @@ Let's say you have a function `namePerson`, which takes a `person` then a `name`
makePerson(~age=47)
->namePerson("Jane")
```
+
```js
namePerson(makePerson(47), "Jane");
```
@@ -213,6 +225,7 @@ If you have a name that you want to apply to a person object, you can use a plac
getName(input)
->namePerson(personDetails, _)
```
+
```js
var __x = getName(input);
namePerson(personDetails, __x);
@@ -228,6 +241,7 @@ This allows you to pipe into any positional argument. It also works for named ar
getName(input)
->namePerson(~person=personDetails, ~name=_)
```
+
```js
var __x = getName(input);
namePerson(personDetails, __x);
diff --git a/pages/docs/manual/v12.0.0/polymorphic-variant.mdx b/pages/docs/manual/v12.0.0/polymorphic-variant.mdx
index f2f2167b5..9396813a2 100644
--- a/pages/docs/manual/v12.0.0/polymorphic-variant.mdx
+++ b/pages/docs/manual/v12.0.0/polymorphic-variant.mdx
@@ -126,15 +126,12 @@ let him: account = #Facebook("Josh", 26)
```js
var me = {
NAME: "Instagram",
- VAL: "Jenny"
+ VAL: "Jenny",
};
var him = {
NAME: "Facebook",
- VAL: [
- "Josh",
- 26
- ]
+ VAL: ["Josh", 26],
};
```
@@ -297,7 +294,6 @@ export const myDirection = Direction.Up
For this particular example, we can also inline poly variant type definitions to design the type for the imported `myDirection` value:
-
```res
@@ -412,14 +408,17 @@ One might think that polymorphic variants are superior to regular [variants](./v
- Due to their "structural" nature, poly variant's type errors might be more confusing. If you accidentally write `#blur` instead of `#blue`, ReScript will still error but can't indicate the correct source as easily. Regular variants' source of truth is the type definition, so the error can't go wrong.
- It's also harder to refactor poly variants. Consider this:
+
```res
let myFruit = #Apple
let mySecondFruit = #Apple
let myCompany = #Apple
```
+
Refactoring the first one to `#Orange` doesn't mean we should refactor the third one. Therefore, the editor plugin can't touch the second one either. Regular variant doesn't have such problem, as these 2 values presumably come from different variant type definitions.
- You might lose some nice pattern match checks from the compiler:
+
```res
let myColor = #red
@@ -428,6 +427,7 @@ One might think that polymorphic variants are superior to regular [variants](./v
| #blue => Console.log("Hello blue!")
}
```
+
Because there's no poly variant definition, it's hard to know whether the `#blue` case can be safely removed.
In most scenarios, we'd recommend to use regular variants over polymorphic variants, especially when you are writing plain ReScript code. In case you want to write zero-cost interop bindings or generate clean JS output, poly variants are oftentimes a better option.
diff --git a/pages/docs/manual/v12.0.0/primitive-types.mdx b/pages/docs/manual/v12.0.0/primitive-types.mdx
index d48d7956e..0ef927e75 100644
--- a/pages/docs/manual/v12.0.0/primitive-types.mdx
+++ b/pages/docs/manual/v12.0.0/primitive-types.mdx
@@ -21,6 +21,7 @@ let greeting = "Hello world!"
let multilineGreeting = "Hello
world!"
```
+
```js
var greeting = "Hello world!";
var multilineGreeting = "Hello\n world!";
@@ -35,6 +36,7 @@ To concatenate strings, use `++`:
```res example
let greetings = "Hello " ++ "world!"
```
+
```js
var greetings = "Hello world!";
```
@@ -60,6 +62,7 @@ World
${name}
`
```
+
```js
var name = "Joe";
@@ -95,8 +98,9 @@ ReScript has a type for a string with a single letter:
```res example
let firstLetterOfAlphabet = 'a'
```
+
```js
-var firstLetterOfAlphabet = /* "a" */97;
+var firstLetterOfAlphabet = /* "a" */ 97;
```
@@ -114,6 +118,7 @@ ReScript regular expressions compile cleanly to their JavaScript counterpart:
```res example
let r = /b/g
```
+
```js
let r = /b/g;
```
@@ -160,6 +165,7 @@ As with integers, you may use underscores within literals to improve readability
```res example
let result = (1 :> float) +. 2.
```
+
```js
var result = 1 + 2;
```
@@ -185,6 +191,7 @@ open! BigInt
let a = 9007199254740991n + 9007199254740991n
let b = 2n ** 2n
```
+
```js
var a = 9007199254740991n + 9007199254740991n;
@@ -207,6 +214,7 @@ let d = lnot(1n)
let e = lsl(1n, 1n)
let f = asr(1n, 1n)
```
+
```js
var Js_bigint = require("./stdlib/js_bigint.js");
@@ -218,9 +226,9 @@ var c = 1n ^ 1n;
var d = Js_bigint.lnot(1n);
-var e = (1n << 1n);
+var e = 1n << 1n;
-var f = (1n >> 1n);
+var f = 1n >> 1n;
```
@@ -238,6 +246,7 @@ switch bigintValue {
| _ => Console.log("Other bigint")
}
```
+
```js
if (1n !== 1n) {
if (1n !== 100n) {
@@ -254,19 +263,18 @@ var bigintValue = 1n;
-
## Unit
The `unit` type indicates the absence of a specific value. It has only a single value, `()`, which acts as a placeholder when no other value exists or is needed. It compiles to JavaScript's `undefined` and resembles the `void` type in languages such as C++. What's the point of such a type?
Consider the `Math.random` function. Its type signature is `unit => float`, which means it receives a `unit` as input and calculates a random `float` as output. You use the function like this - `let x = Math.random()`. Notice `()` as the first and only function argument.
-Imagine a simplified `Console.log` function that prints a message. Its type signature is `string => unit` and you'd use it like this `Console.log("Hello!")`. It takes a string as input, prints it, and then returns nothing useful. When `unit` is the output of a function it means the function performs some kind of side-effect.
+Imagine a simplified `Console.log` function that prints a message. Its type signature is `string => unit` and you'd use it like this `Console.log("Hello!")`. It takes a string as input, prints it, and then returns nothing useful. When `unit` is the output of a function it means the function performs some kind of side-effect.
## Unknown
The `unknown` type represents values with contents that are a mystery or are not 100% guaranteed to be what you think they are. It provides type-safety when interacting with data received from an untrusted source. For example, suppose an external function is supposed to return a `string`. It might. But if the documentation is not accurate or the code has bugs, the function could return `null`, an `array`, or something else you weren't expecting.
-The ReScript type system helps you avoid run-time crashes and unpredicatable behavior by preventing you from using `unknown` in places that expect a `string` or `int` or some other type. The ReScript core libraries also provide utility functions to help you inspect `unknown` values and access their contents. In some cases you may need a JSON parsing library to convert `unknown` values to types you can safely use.
+The ReScript type system helps you avoid run-time crashes and unpredicatable behavior by preventing you from using `unknown` in places that expect a `string` or `int` or some other type. The ReScript core libraries also provide utility functions to help you inspect `unknown` values and access their contents. In some cases you may need a JSON parsing library to convert `unknown` values to types you can safely use.
Consider using `unknown` when receiving data from [external JavaScript functions](/docs/manual/next/bind-to-js-function)
diff --git a/pages/docs/manual/v12.0.0/promise.mdx b/pages/docs/manual/v12.0.0/promise.mdx
index 0c8bc2032..b269289c8 100644
--- a/pages/docs/manual/v12.0.0/promise.mdx
+++ b/pages/docs/manual/v12.0.0/promise.mdx
@@ -24,7 +24,7 @@ type user = {name: string}
let fetchUser: string => promise
```
-To work with promise values (instead of using `async` / `await`) you may want to use the built-in `Promise` module.
+To work with promise values (instead of using `async` / `await`) you may want to use the built-in `Promise` module.
## Promise
@@ -85,7 +85,6 @@ You can handle a rejected promise using the [`Promise.catch()`](./api/core/promi
In case you want to launch multiple promises in parallel, use `Promise.all`:
-
```res
@@ -102,15 +101,13 @@ let logAsyncMessage = async () => {
```js
async function logAsyncMessage(param) {
var messages = await Promise.all([
- global.fetchMessage("message1"),
- global.fetchMessage("message2")
- ]);
+ global.fetchMessage("message1"),
+ global.fetchMessage("message2"),
+ ]);
console.log(messages.join(", "));
}
-export {
- logAsyncMessage ,
-}
+export { logAsyncMessage };
```
@@ -136,8 +133,7 @@ Js.Promise.make: (
) => Js.Promise.t<'a>
```
-This type signature means that `make` takes a callback that takes 2 named arguments, `resolve` and `reject`. Both arguments are themselves [uncurried callbacks](
-function.md#uncurried-function) (with a dot). `make` returns the created promise.
+This type signature means that `make` takes a callback that takes 2 named arguments, `resolve` and `reject`. Both arguments are themselves [uncurried callbacks](function.md#uncurried-function) (with a dot). `make` returns the created promise.
### Usage
@@ -159,6 +155,7 @@ myPromise->Js.Promise.then_(value => {
Js.Promise.resolve(-2)
}, _)
```
+
```js
var myPromise = new Promise(function (resolve, reject) {
return resolve(2);
diff --git a/pages/docs/manual/v12.0.0/record.mdx b/pages/docs/manual/v12.0.0/record.mdx
index 8879aa14c..8601daa23 100644
--- a/pages/docs/manual/v12.0.0/record.mdx
+++ b/pages/docs/manual/v12.0.0/record.mdx
@@ -23,6 +23,7 @@ type person = {
name: string,
}
```
+
```js
// Empty output
```
@@ -53,14 +54,15 @@ let person = {
}
```
+
```js
let person = {
age: 90,
name: "Test Person",
notificationSettings: {
sendEmails: true,
- allowPasswordLogin: false
- }
+ allowPasswordLogin: false,
+ },
};
```
@@ -69,6 +71,7 @@ let person = {
Nesting record definitions is a nice way to group records that are part of the same structure, and won't be referenced from the outside.
If you end up needing to refer to a nested record type explicitly, you should make it an explicit definition instead of a nested one. This is mainly for 2 reasons:
+
- The records that are automatically generated for the nested record definitions are named in a way that would require you to use escaped identifiers to reference them. The nested record at `notificationSettings` above would be named `\"person.notificationSettings"` for instance
- For the sake of clarity (and caring about your co-workers), having an explicit and named definition to look at and refer to is much easier than scanning a potentially large record definition for the nested record you're looking for
@@ -98,14 +101,15 @@ let person = {
}
```
+
```js
let person = {
age: 90,
name: "Test Person",
notificationSettings: {
sendEmails: true,
- allowPasswordLogin: false
- }
+ allowPasswordLogin: false,
+ },
};
```
@@ -123,10 +127,11 @@ let me = {
name: "Big ReScript"
}
```
+
```js
var me = {
age: 5,
- name: "Big ReScript"
+ name: "Big ReScript",
};
```
@@ -142,6 +147,7 @@ The type is found by looking above the `me` value. **Note**: if the type instead
// School.res
type person = {age: int, name: string}
```
+
```js
// Empty output
```
@@ -157,14 +163,15 @@ let me: School.person = {age: 20, name: "Big ReScript"}
/* or */
let me2 = {School.age: 20, name: "Big ReScript"}
```
+
```js
var me = {
age: 20,
- name: "Big ReScript"
+ name: "Big ReScript",
};
var me2 = {
age: 20,
- name: "Big ReScript"
+ name: "Big ReScript",
};
```
@@ -181,6 +188,7 @@ Use the familiar dot notation:
```res example
let name = me.name
```
+
```js
var name = "Big ReScript";
```
@@ -196,10 +204,11 @@ New records can be created from old records with the `...` spread operator. The
```res example
let meNextYear = {...me, age: me.age + 1}
```
+
```js
var meNextYear = {
age: 21,
- name: "Big ReScript"
+ name: "Big ReScript",
};
```
@@ -222,13 +231,14 @@ type person = {
let baby = {name: "Baby ReScript", age: 5}
baby.age = baby.age + 1 // `baby.age` is now 6. Happy birthday!
```
+
```js
var baby = {
name: "Baby ReScript",
- age: 5
+ age: 5,
};
-baby.age = baby.age + 1 | 0;
+baby.age = (baby.age + 1) | 0;
```
@@ -240,6 +250,7 @@ Fields not marked with `mutable` in the type declaration cannot be mutated.
ReScript records compile to straightforward JavaScript objects; see the various JS output tabs above.
## Optional Record Fields
+
ReScript [`v10`](/blog/release-10-0-0#experimental-optional-record-fields) introduced optional record fields. This means that you can define fields that can be omitted when creating the record. It looks like this:
@@ -250,6 +261,7 @@ type person = {
name?: string
}
```
+
```js
// Empty output
```
@@ -259,6 +271,7 @@ type person = {
Notice how `name` has a suffixed `?`. That means that the field itself is _optional_.
### Creation
+
You can omit any optional fields when creating a record. Not setting an optional field will default the field's value to `None`:
@@ -278,14 +291,15 @@ let friend = {
age: 7
}
```
+
```js
var me = {
age: 5,
- name: "Big ReScript"
+ name: "Big ReScript",
};
var friend = {
- age: 7
+ age: 7,
};
```
@@ -294,6 +308,7 @@ var friend = {
This has consequences for pattern matching, which we'll expand a bit on soon.
## Immutable Update
+
Updating an optional field via an immutable update above lets you set that field value without needing to care whether it's optional or not.
@@ -314,12 +329,13 @@ let withoutName = {
name: "New Name"
}
```
+
```js
import * as Caml_obj from "./stdlib/caml_obj.js";
var me = {
age: 123,
- name: "Hello"
+ name: "Hello",
};
var newrecord = Caml_obj.obj_dup(me);
@@ -331,7 +347,6 @@ var withoutName = newrecord;
-
However, if you want to set the field to an optional value, you prefix that value with `?`:
@@ -354,12 +369,13 @@ let withoutName = {
name: ?maybeName
}
```
+
```js
import * as Caml_obj from "./stdlib/caml_obj.js";
var me = {
age: 123,
- name: "Hello"
+ name: "Hello",
};
var maybeName = "My Name";
@@ -376,6 +392,7 @@ var withoutName = newrecord;
You can unset an optional field's value via that same mechanism by setting it to `?None`.
### Pattern Matching on Optional Fields
+
[Pattern matching](pattern-matching-destructuring), one of ReScript's most important features, has two caveats when you deal with optional fields.
When matching on the value directly, it's an `option`. Example:
@@ -398,6 +415,7 @@ let isRescript = switch me.name {
| Some(_) | None => false
}
```
+
```js
var isRescript;
@@ -405,7 +423,7 @@ isRescript = "Hello" === "ReScript" ? true : false;
var me = {
age: 123,
- name: "Hello"
+ name: "Hello",
};
```
@@ -432,6 +450,7 @@ let isRescript = switch me {
}
```
+
```js
var isRescript;
@@ -439,7 +458,7 @@ isRescript = "Hello" === "ReScript" ? true : false;
var me = {
age: 123,
- name: "Hello"
+ name: "Hello",
};
```
@@ -465,12 +484,13 @@ let nameWasSet = switch me {
| {name: ?Some(_)} => true
}
```
+
```js
var nameWasSet = true;
var me = {
age: 123,
- name: "Hello"
+ name: "Hello",
};
```
@@ -595,6 +615,7 @@ let name = nameFromB(a :> b)
## Tips & Tricks
### Record Types Are Found By Field Name
+
With records, you **cannot** say "I'd like this function to take any record type, as long as they have the field `age`". The following **won't work as intended**:
@@ -605,6 +626,7 @@ type monster = {age: int, hasTentacles: bool}
let getAge = (entity) => entity.age
```
+
```js
function getAge(entity) {
return entity.age;
@@ -626,7 +648,8 @@ getAge(me) // type error!
The type system will complain that `me` is a `person`, and that `getAge` only works on `monster`. If you need such capability, use ReScript objects, described [here](object.md).
### Optional Fields in Records Can Be Useful for Bindings
-Many JavaScript APIs tend to have large configuration objects that can be a bit annoying to model as records, since you previously always needed to specify all record fields when creating a record.
+
+Many JavaScript APIs tend to have large configuration objects that can be a bit annoying to model as records, since you previously always needed to specify all record fields when creating a record.
Optional record fields, introduced in [`v10`](/blog/release-10-0-0#experimental-optional-record-fields), is intended to help with this. Optional fields will let you avoid having to specify all fields, and let you just specify the one's you care about. A significant improvement in ergonomics for bindings and other APIs with for example large configuration objects.
@@ -636,4 +659,3 @@ After reading the constraints in the previous sections, and if you're coming fro
1. The truth is that most of the times in your app, your data's shape is actually fixed, and if it's not, it can potentially be better represented as a combination of variant (introduced next) + record instead.
2. Since a record type is resolved through finding that single explicit type declaration (we call this "nominal typing"), the type error messages end up better than the counterpart ("structural typing", like for tuples). This makes refactoring easier; changing a record type's fields naturally allows the compiler to know that it's still the same record, just misused in some places. Otherwise, under structural typing, it might get hard to tell whether the definition site or the usage site is wrong.
-
diff --git a/pages/docs/manual/v12.0.0/scoped-polymorphic-types.mdx b/pages/docs/manual/v12.0.0/scoped-polymorphic-types.mdx
index e0c1a3d23..80ce25351 100644
--- a/pages/docs/manual/v12.0.0/scoped-polymorphic-types.mdx
+++ b/pages/docs/manual/v12.0.0/scoped-polymorphic-types.mdx
@@ -97,4 +97,3 @@ let testExn: 'a. unit => 'a = () => throw(Abort) // Works!
let testExn2 = (): 'a. 'a = throw(Abort) // Syntax error!
type fn = 'a. 'a => unit // Syntax error!
```
-
diff --git a/pages/docs/manual/v12.0.0/tagged-templates.mdx b/pages/docs/manual/v12.0.0/tagged-templates.mdx
index 1b569211c..928f36b03 100644
--- a/pages/docs/manual/v12.0.0/tagged-templates.mdx
+++ b/pages/docs/manual/v12.0.0/tagged-templates.mdx
@@ -8,21 +8,24 @@ canonical: "/docs/manual/v12.0.0/tagged-templates"
**Since 11.1**
-Tagged templates provide a special form of string interpolation, enabling the creation of template literals
-where placeholders aren't restricted to strings. Moreover, the resulting output isn't confined solely to
-strings either. You can take a look at the [JS documentation
+Tagged templates provide a special form of string interpolation, enabling the creation of template literals
+where placeholders aren't restricted to strings. Moreover, the resulting output isn't confined solely to
+strings either. You can take a look at the [JS documentation
about tagged templates](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals#tagged_templates)
to learn more about them.
## Define a tag function
Tag functions in ReScript have the following signature:
-```res
+
+```res
let myTagFunction : (array, array<'param>) => 'output
```
+
As you can see, you can have any type you want both for the placeholder array and for the output.
Given how string interpolation works, you'll always have the following invariant:
+
```res
Array.length(strings) == Array.length(placeholder) + 1
```
@@ -58,28 +61,32 @@ let s = (strings, parameters) => {
React.string(text)
}
```
+
```js
import * as Core__Array from "./stdlib/core__Array.js";
function s(strings, parameters) {
- return Core__Array.reduceWithIndex(parameters, strings[0], (function (acc, param, i) {
- var s = strings[i + 1 | 0];
- var p;
- switch (param.TAG) {
- case "I" :
- case "F" :
- p = param._0.toString();
- break;
- case "S" :
- p = param._0;
- break;
- case "Bool" :
- p = param._0 ? "true" : "false";
- break;
-
- }
- return acc + p + s;
- }));
+ return Core__Array.reduceWithIndex(
+ parameters,
+ strings[0],
+ function (acc, param, i) {
+ var s = strings[(i + 1) | 0];
+ var p;
+ switch (param.TAG) {
+ case "I":
+ case "F":
+ p = param._0.toString();
+ break;
+ case "S":
+ p = param._0;
+ break;
+ case "Bool":
+ p = param._0 ? "true" : "false";
+ break;
+ }
+ return acc + p + s;
+ },
+ );
}
```
@@ -99,26 +106,30 @@ module Greetings = {
}
}
```
+
```js
function Greetings(props) {
- return React.createElement("div", undefined, s([
- "hello ",
- " you're ",
- " year old!"
- ], [
- {
- TAG: "S",
- _0: props.name
- },
- {
- TAG: "I",
- _0: props.age
- }
- ]));
+ return React.createElement(
+ "div",
+ undefined,
+ s(
+ ["hello ", " you're ", " year old!"],
+ [
+ {
+ TAG: "S",
+ _0: props.name,
+ },
+ {
+ TAG: "I",
+ _0: props.age,
+ },
+ ],
+ ),
+ );
}
```
-Pretty neat, isn't it? As you can see, it looks like any regular template literal but it accepts placeholders that are not strings
-and it outputs something that is not a string either, a `React.element` in this case.
\ No newline at end of file
+Pretty neat, isn't it? As you can see, it looks like any regular template literal but it accepts placeholders that are not strings
+and it outputs something that is not a string either, a `React.element` in this case.
diff --git a/pages/docs/manual/v12.0.0/tuple.mdx b/pages/docs/manual/v12.0.0/tuple.mdx
index 27fcc103e..086a3846b 100644
--- a/pages/docs/manual/v12.0.0/tuple.mdx
+++ b/pages/docs/manual/v12.0.0/tuple.mdx
@@ -19,6 +19,7 @@ Tuples are a ReScript-specific data structure that don't exist in JavaScript. Th
let ageAndName = (24, "Lil' ReScript")
let my3dCoordinates = (20.0, 30.5, 100.0)
```
+
```js
var ageAndName = [24, "Lil' ReScript"];
var my3dCoordinates = [20.0, 30.5, 100.0];
@@ -36,10 +37,12 @@ let ageAndName: (int, string) = (24, "Lil' ReScript")
type coord3d = (float, float, float)
let my3dCoordinates: coord3d = (20.0, 30.5, 100.0)
```
+
```js
var ageAndName = [24, "Lil' ReScript"];
var my3dCoordinates = [20.0, 30.5, 100.0];
```
+
**Note**: there's no tuple of size 1. You'd just use the value itself.
@@ -53,6 +56,7 @@ To get a specific member of a tuple, destructure it:
```res example
let (_, y, _) = my3dCoordinates // now you've retrieved y
```
+
```js
var y = 30.5;
```
@@ -70,6 +74,7 @@ let coordinates1 = (10, 20, 30)
let (c1x, _, _) = coordinates1
let coordinates2 = (c1x + 50, 20, 30)
```
+
```js
var coordinates1 = [10, 20, 30];
var c1x = 10;
@@ -91,6 +96,7 @@ let getCenterCoordinates = () => {
(x, y)
}
```
+
```js
function getCenterCoordinates(param) {
var x = doSomeOperationsHere(undefined);
diff --git a/pages/docs/manual/v12.0.0/type.mdx b/pages/docs/manual/v12.0.0/type.mdx
index e0344acbc..c352c2fdd 100644
--- a/pages/docs/manual/v12.0.0/type.mdx
+++ b/pages/docs/manual/v12.0.0/type.mdx
@@ -7,6 +7,7 @@ canonical: "/docs/manual/v12.0.0/type"
# Type
Types are the highlight of ReScript! They are:
+
- **Strong**. A type can't change into another type. In JavaScript, your variable's type might change when the code runs (aka at runtime). E.g. a `number` variable might change into a `string` sometimes. This is an anti-feature; it makes the code much harder to understand when reading or debugging.
- **Static**. ReScript types are erased after compilation and don't exist at runtime. Never worry about your types dragging down performance. You don't need type info during runtime; we report all the information (especially all the type errors) during compile time. Catch the bugs earlier!
- **Sound**. This is our biggest differentiator versus many other typed languages that compile to JavaScript. Our type system is guaranteed to **never** be wrong. Most type systems make a guess at the type of a value and show you a type in your editor that's sometime incorrect. We don't do that. We believe that a type system that is sometime incorrect can end up being dangerous due to expectation mismatches.
@@ -25,10 +26,11 @@ This let-binding doesn't contain any written type:
let score = 10
let add = (a, b) => a + b
```
+
```js
var score = 10;
function add(a, b) {
- return a + b | 0;
+ return (a + b) | 0;
}
```
@@ -45,6 +47,7 @@ But you can also optionally write down the type, aka annotate your value:
```res example
let score: int = 10
```
+
```js
var score = 10;
```
@@ -64,10 +67,11 @@ let myInt = (5: int) + (4: int)
let add = (x: int, y: int) : int => x + y
let drawCircle = (~radius as r: int): circleType => /* code here */
```
+
```js
var myInt = 9;
function add(x, y) {
- return x + y | 0;
+ return (x + y) | 0;
}
function drawCircle(r) {
/* code here */
@@ -88,6 +92,7 @@ You can refer to a type by a different name. They'll be equivalent:
type scoreType = int
let x: scoreType = 10
```
+
```js
var x = 10;
```
@@ -110,6 +115,7 @@ type floatCoordinates = (float, float, float)
let a: intCoordinates = (10, 20, 20)
let b: floatCoordinates = (10.5, 20.5, 20.5)
```
+
```js
var a = [10, 20, 20];
var b = [10.5, 20.5, 20.5];
@@ -127,6 +133,7 @@ type coordinates<'a> = ('a, 'a, 'a)
let a: coordinates = (10, 20, 20)
let b: coordinates = (10.5, 20.5, 20.5)
```
+
```js
var a = [10, 20, 20];
var b = [10.5, 20.5, 20.5];
@@ -141,6 +148,7 @@ Note that the above codes are just contrived examples for illustration purposes.
```res example
let buddy = (10, 20, 20)
```
+
```js
var buddy = [10, 20, 20];
```
@@ -157,6 +165,7 @@ Type arguments appear in many places. Our `array<'a>` type is such a type that r
// inferred as `array`
let greetings = ["hello", "world", "how are you"]
```
+
```js
// inferred as `array`
var greetings = ["hello", "world", "how are you"];
@@ -187,20 +196,21 @@ let payloadResults: myPayloadResults = [
Error("Something wrong happened!")
]
```
+
```js
var payloadResults = [
{
- TAG: /* Ok */0,
- _0: {data: "hi"}
+ TAG: /* Ok */ 0,
+ _0: { data: "hi" },
},
{
- TAG: /* Ok */0,
- _0: {data: "bye"}
+ TAG: /* Ok */ 0,
+ _0: { data: "bye" },
},
{
- TAG: /* Error */1,
- _0: "Something wrong happened!"
- }
+ TAG: /* Error */ 1,
+ _0: "Something wrong happened!",
+ },
];
```
@@ -218,6 +228,7 @@ type rec person = {
friends: array
}
```
+
```js
// Empty output
```
@@ -234,6 +245,7 @@ Types can also be _mutually_ recursive through `and`:
type rec student = {taughtBy: teacher}
and teacher = {students: array}
```
+
```js
// Empty output
```
@@ -249,6 +261,7 @@ ReScript's type system is robust and does not allow dangerous, unsafe stuff like
```res
external myShadyConversion: myType1 => myType2 = "%identity"
```
+
```js
// Empty output
```
@@ -264,6 +277,7 @@ external convertToFloat : int => float = "%identity"
let age = 10
let gpa = 2.1 +. convertToFloat(age)
```
+
```js
var age = 10;
var gpa = 2.1 + 10;
diff --git a/pages/docs/manual/v12.0.0/typescript-integration.mdx b/pages/docs/manual/v12.0.0/typescript-integration.mdx
index dc5e5489e..152992784 100644
--- a/pages/docs/manual/v12.0.0/typescript-integration.mdx
+++ b/pages/docs/manual/v12.0.0/typescript-integration.mdx
@@ -68,9 +68,8 @@ import * as ColorJS from "./Color.res.js";
export type color = "Red" | "Blue";
-export const printColorMessage: (
- color: color
-) => void = ColorJS.printColorMessage as any;
+export const printColorMessage: (color: color) => void =
+ ColorJS.printColorMessage as any;
```
genType automatically maps the `color` variant to TS via a string union type `"Red" | "Blue"`.
@@ -87,7 +86,7 @@ printColorMessage("Red", "Hello, genType!");
## Exporting an entire module
-_Since ReScript `11.0.0`_ modules can be annotated with `@genType` as well. In that case, all types and values of the module will be converted to TS types. Example:
+_Since ReScript `11.0.0`_ modules can be annotated with `@genType` as well. In that case, all types and values of the module will be converted to TS types. Example:
@@ -109,17 +108,17 @@ module Size = {
```
```ts
-import * as MyCompBS__Es6Import from './MyComp.res';
+import * as MyCompBS__Es6Import from "./MyComp.res";
const MyCompBS: any = MyCompBS__Es6Import;
export type Size_t = "Small" | "Medium" | "Large";
-export const Size_getNum: (size:Size_t) => number = MyCompBS.Size.getNum;
+export const Size_getNum: (size: Size_t) => number = MyCompBS.Size.getNum;
-export const Size: { getNum: (size:Size_t) => number } = MyCompBS.Size
+export const Size: { getNum: (size: Size_t) => number } = MyCompBS.Size;
```
-
+
## Setup
@@ -214,13 +213,13 @@ These features are for experimentation only. They could be changed/removed any t
- Export object and record types as interfaces. To activate, add `"exportInterfaces": true` to the configuration. The types are also renamed from `name` to `Iname`.
-
## Shims
A shim is a TS file that provides user-provided definitions for library types.
Required only if one needs to export certain basic ReScript data types to JS when one cannot modify the sources to add annotations (e.g. exporting ReScript lists), and if the types are not first-classed in genType.
- - Example: `Array` with format: `"RescriptModule=JavaScriptModule"`
+
+- Example: `Array` with format: `"RescriptModule=JavaScriptModule"`
Configure your shim files within `"gentypeconfig"` in your [`rescript.json`]:
@@ -232,12 +231,12 @@ Configure your shim files within `"gentypeconfig"` in your [`rescript.json`]:
"ReactEvent": "ReactEvent",
"RescriptPervasives": "RescriptPervasives",
"ReasonReact": "ReactShim"
- },
- },
+ }
+ }
}
```
-and add relevant `.shim.ts` files in a directory which is visible by ReScript e.g.
+and add relevant `.shim.ts` files in a directory which is visible by ReScript e.g.
```
├── rescript.json
diff --git a/pages/docs/manual/v12.0.0/use-illegal-identifier-names.mdx b/pages/docs/manual/v12.0.0/use-illegal-identifier-names.mdx
index cfd0e0987..4933cbed0 100644
--- a/pages/docs/manual/v12.0.0/use-illegal-identifier-names.mdx
+++ b/pages/docs/manual/v12.0.0/use-illegal-identifier-names.mdx
@@ -7,6 +7,7 @@ canonical: "/docs/manual/v12.0.0/use-illegal-identifier-names"
# Use Illegal Identifier Names
Sometime, for e.g. a let binding or a record field, you might want to use:
+
- A capitalized name.
- A name that contains illegal characters (e.g. emojis, hyphen, space).
- A name that's one of ReScript's reserved keywords.
@@ -32,17 +33,18 @@ let calculate = (~\"Props") => {
\"Props" + 1
}
```
+
```js
var my$$unknown$unknown$unknown$unknown = 10;
var myElement = {
- "aria-label": "close"
+ "aria-label": "close",
};
var label = myElement["aria-label"];
function calculate(Props) {
- return Props + 1 | 0;
+ return (Props + 1) | 0;
}
```
diff --git a/pages/docs/manual/v12.0.0/variant.mdx b/pages/docs/manual/v12.0.0/variant.mdx
index 6d7ece732..6727a0ea2 100644
--- a/pages/docs/manual/v12.0.0/variant.mdx
+++ b/pages/docs/manual/v12.0.0/variant.mdx
@@ -20,6 +20,7 @@ type myResponse =
let areYouCrushingIt = Yes
```
+
```js
var areYouCrushingIt = "Yes";
```
@@ -40,6 +41,7 @@ If the variant you're using is in a different file, bring it into scope like you
// Zoo.res
type animal = Dog | Cat | Bird
```
+
```js
// Empty output
```
@@ -54,6 +56,7 @@ let pet: Zoo.animal = Dog // preferred
// or
let pet2 = Zoo.Dog
```
+
```js
var pet = "Dog";
var pet2 = "Dog";
@@ -73,6 +76,7 @@ type account =
| Instagram(string)
| Facebook(string, int)
```
+
```js
// Empty output
```
@@ -87,15 +91,16 @@ Here, `Instagram` holds a `string`, and `Facebook` holds a `string` and an `int`
let myAccount = Facebook("Josh", 26)
let friendAccount = Instagram("Jenny")
```
+
```js
var myAccount = {
TAG: "Facebook",
_0: "Josh",
- _1: 26
+ _1: 26,
};
var friendAccount = {
TAG: "Instagram",
- _0: "Jenny"
+ _0: "Jenny",
};
```
@@ -114,11 +119,12 @@ type user =
let me = Id({name: "Joe", password: "123"})
```
+
```js
var me = {
TAG: "Id",
name: "Joe",
- password: "123"
+ password: "123",
};
```
@@ -138,13 +144,14 @@ type user =
let me = Id({name: "Joe", password: "123"})
```
+
```js
var me = {
TAG: "Id",
_0: {
name: "Joe",
- password: "123"
- }
+ password: "123",
+ },
};
```
@@ -153,6 +160,7 @@ var me = {
The output is slightly uglier and less performant than the former.
## Variant Type Spreads
+
Just like [with records](record#record-type-spread), it's possible to use type spreads to create new variants from other variants:
```rescript
@@ -161,11 +169,13 @@ type b = | ...a | Four | Five
```
Type `b` is now:
+
```rescript
type b = One | Two | Three | Four | Five
```
Type spreads act as a 'copy-paste', meaning all constructors are copied as-is from `a` to `b`. Here are the rules for spreads to work:
+
- You can't overwrite constructors, so the same constructor name can exist in only one place as you spread. This is true even if the constructors are identical.
- All variants and constructors must share the same runtime configuration - `@unboxed`, `@tag`, `@as` and so on.
- You can't spread types in recursive definitions.
@@ -211,6 +221,7 @@ type adventurer = Warrior(s) | Wizard(string)
let a1 = Warrior({score: 10.5})
let a2 = Wizard("Joe")
```
+
```js
var g1 = "Hello";
@@ -220,7 +231,7 @@ var o1 = "Good";
var o2 = {
TAG: "Error",
- _0: "oops!"
+ _0: "oops!",
};
var f1 = "Child";
@@ -228,31 +239,31 @@ var f1 = "Child";
var f2 = {
TAG: "Mom",
_0: 30,
- _1: "Jane"
+ _1: "Jane",
};
var f3 = {
TAG: "Dad",
- _0: 32
+ _0: 32,
};
var p1 = "Teacher";
var p2 = {
TAG: "Student",
- gpa: 99.5
+ gpa: 99.5,
};
var a1 = {
TAG: "Warrior",
_0: {
- score: 10.5
- }
+ score: 10.5,
+ },
};
var a2 = {
TAG: "Wizard",
- _0: "Joe"
+ _0: "Joe",
};
```
@@ -323,7 +334,9 @@ type direction = "UP" | "DOWN" | "LEFT" | "RIGHT";
There's no way to attach documentation strings to string literals in TypeScript, and you only get the actual value to interact with.
### Valid `@as` payloads
+
Here's a list of everything you can put in the `@as` tag of a variant constructor:
+
- A string literal: `@as("success")`
- An int: `@as(5)`
- A float: `@as(1.5)`
@@ -352,8 +365,10 @@ var myArray = ["hello", true, false, 13.37];
In the above example, reaching back into the values is as simple as pattern matching on them.
### Advanced: Unboxing rules
+
#### No overlap in constructors
-A variant can be unboxed if no constructors have overlap in their runtime representation.
+
+A variant can be unboxed if no constructors have overlap in their runtime representation.
For example, you can't have `String1(string) | String2(string)` in the same unboxed variant, because there's no way for ReScript to know at runtime which of `String1` or `String2` that `string` belongs to, as it could belong to both.
The same goes for two records - even if they have fully different shapes, they're still JavaScript `object` at runtime.
@@ -361,14 +376,16 @@ The same goes for two records - even if they have fully different shapes, they'r
Don't worry - the compiler will guide you and ensure there's no overlap.
#### What you can unbox
+
Here's a list of all possible things you can unbox:
+
- `string`: `String(string)`
- `float`: `Float(float)`. Note you can only have one of `float` or `int` because JavaScript only has `number` (not actually `int` and `float` like in ReScript) so we can't disambiguate between `float` and `int` at runtime.
- `int`: `Int(int)`. See note above on `float`.
- `bigint`: `BigInt(int)`. **Since 11.1** This is a distinct type from JavaScript's `number` type so you can use it beside either `float` or `int`.
- `bool`: `Boolean(bool)`
- `array<'value>`: `List(array)`
-- `('a, 'b, 'c)`: `Tuple((string, int, bool))`. Any size of tuples works, but you can have only one case of array or tuple in a variant.
+- `('a, 'b, 'c)`: `Tuple((string, int, bool))`. Any size of tuples works, but you can have only one case of array or tuple in a variant.
- `promise<'value>`: `Promise(promise)`
- `Dict.t`: `Object(Dict.t)`
- `Date.t`: `Date(Date.t)`. A JavaScript date.
@@ -381,6 +398,7 @@ Again notice that the constructor names can be anything, what matters is what's
> **Under the hood**: Untagged variants uses a combination of JavaScript `typeof` and `instanceof` checks to discern between unboxed constructors at runtime. This means that we could add more things to the list above detailing what can be unboxed, if there are useful enough use cases.
### Pattern matching on unboxed variants
+
Pattern matching works the same on unboxed variants as it does on regular variants. In fact, in the perspective of ReScript's type system there's no difference between untagged and tagged variants. You can do virtually the same things with both. That's the beauty of untagged variants - they're just variants to you as a developer.
Here's an example of pattern matching on an unboxed nullable value that illustrates the above:
@@ -404,6 +422,7 @@ let getBestFriendsAge = user =>
| _ => None
}
```
+
No difference to how you'd do with a regular variant. But, the runtime representation is different to a regular variant.
> Notice how `@as` allows us to say that an untagged variant case should map to a specific underlying _primitive_. `Present` has a type variable, so it can hold any type. And since it's an unboxed type, only the payloads `'a` or `null` will be kept at runtime. That's where the magic comes from.
@@ -492,7 +511,8 @@ let usersToJson = users => Array(users->Array.map(userToJson))
This can be extrapolated to many more cases.
### Advanced: Catch-all Constructors
-With untagged variants comes a rather interesting capability - catch-all cases are now possible to encode directly into a variant.
+
+With untagged variants comes a rather interesting capability - catch-all cases are now possible to encode directly into a variant.
Let's look at how it works. Imagine you're using a third party API that returns a list of available animals. You could of course model it as a regular `string`, but given that variants can be used as "typed strings", using a variant would give you much more benefit:
@@ -501,37 +521,41 @@ Let's look at how it works. Imagine you're using a third party API that returns
type animal = Dog | Cat | Bird
type apiResponse = {
- animal: animal
+animal: animal
}
let greetAnimal = (animal: animal) =>
- switch animal {
- | Dog => "Wof"
- | Cat => "Meow"
- | Bird => "Kashiiin"
- }
-```
+switch animal {
+| Dog => "Wof"
+| Cat => "Meow"
+| Bird => "Kashiiin"
+}
+
+````
```javascript
-```
-
+````
+
-This is all fine and good as long as the API returns `"Dog"`, `"Cat"` or `"Bird"` for `animal`.
+This is all fine and good as long as the API returns `"Dog"`, `"Cat"` or `"Bird"` for `animal`.
However, what if the API changes before you have a chance to deploy new code, and can now return `"Turtle"` as well? Your code would break down because the variant `animal` doesn't cover `"Turtle"`.
So, we'll need to go back to `string`, loosing all of the goodies of using a variant, and then do manual conversion into the `animal` variant from `string`, right?
Well, this used to be the case before, but not anymore! We can leverage untagged variants to bake in handling of unknown values into the variant itself.
Let's update our type definition first:
+
```rescript
@unboxed
type animal = Dog | Cat | Bird | UnknownAnimal(string)
```
Notice we've added `@unboxed` and the constructor `UnknownAnimal(string)`. Remember how untagged variants work? You remove the constructors and just leave the payloads. This means that the variant above at runtime translates to this (made up) JavaScript type:
+
```
type animal = "Dog" | "Cat" | "Bird" | string
```
+
So, any string not mapping directly to one of the payloadless constructors will now map to the general `string` case.
As soon as we've added this, the compiler complains that we now need to handle this additional case in our pattern match as well. Let's fix that:
@@ -542,18 +566,19 @@ As soon as we've added this, the compiler complains that we now need to handle t
type animal = Dog | Cat | Bird | UnknownAnimal(string)
type apiResponse = {
- animal: animal
+animal: animal
}
let greetAnimal = (animal: animal) =>
- switch animal {
- | Dog => "Wof"
- | Cat => "Meow"
- | Bird => "Kashiiin"
- | UnknownAnimal(otherAnimal) =>
- `I don't know how to greet animal ${otherAnimal}`
- }
-```
+switch animal {
+| Dog => "Wof"
+| Cat => "Meow"
+| Bird => "Kashiiin"
+| UnknownAnimal(otherAnimal) =>
+`I don't know how to greet animal ${otherAnimal}`
+}
+
+````
```javascript
function greetAnimal(animal) {
if (!(animal === "Cat" || animal === "Dog" || animal === "Bird")) {
@@ -566,10 +591,11 @@ function greetAnimal(animal) {
return "Meow";
case "Bird" :
return "Kashiiin";
-
+
}
}
-```
+````
+
There! Now the external API can change as much as it wants, we'll be forced to write all code that interfaces with `animal` in a safe way that handles all possible cases. All of this baked into the variant definition itself, so no need for labor intensive manual conversion.
@@ -577,12 +603,15 @@ There! Now the external API can change as much as it wants, we'll be forced to w
This is useful in any scenario when you use something enum-style that's external and might change. Additionally, it's also useful when something external has a large number of possible values that are known, but where you only care about a subset of them. With a catch-all case you don't need to bind to all of them just because they can happen, you can safely just bind to the ones you care about and let the catch-all case handle the rest.
## Coercion
+
In certain situations, variants can be coerced to other variants, or to and from primitives. Coercion is always zero cost.
### Coercing Variants to Other Variants
+
You can coerce a variant to another variant if they're identical in runtime representation, and additionally if the variant you're coercing can be represented as the variant you're coercing to.
Here's an example using [variant type spreads](#variant-type-spreads):
+
```rescript
type a = One | Two | Three
type b = | ...a | Four | Five
@@ -590,14 +619,16 @@ type b = | ...a | Four | Five
let one: a = One
let four: b = Four
-// This works because type `b` can always represent type `a` since all of type `a`'s constructors are spread into type `b`
+// This works because type `b` can always represent type `a` since all of type `a`'s constructors are spread into type `b`
let oneAsTypeB = (one :> b)
```
### Coercing Variants to Primitives
+
Variants that are guaranteed to always be represented by a single primitive at runtime can be coerced to that primitive.
It works with strings, the default runtime representation of payloadless constructors:
+
```rescript
// Constructors without payloads are represented as `string` by default
type a = One | Two | Three
@@ -609,6 +640,7 @@ let oneAsString = (one :> string)
```
If you were to configure all of your construtors to be represented as `int` or `float`, you could coerce to those too:
+
```rescript
type asInt = | @as(1) One | @as(2) Two | @as(3) Three
@@ -617,13 +649,16 @@ let toInt = (oneInt :> int)
```
### Advanced: Coercing `string` to Variant
+
In certain situtations it's possible to coerce a `string` to a variant. This is an advanced technique that you're unlikely to need much, but when you do it's really useful.
You can coerce a `string` to a variant when:
+
- Your variant is `@unboxed`
- Your variant has a "catch-all" `string` case
Let's look at an example:
+
```rescript
@unboxed
type myEnum = One | Two | Other(string)
@@ -649,6 +684,7 @@ type account =
type account2 =
| Instagram((string, int)) // 1 argument - happens to be a 2-tuple
```
+
```js
// Empty output
```
@@ -683,6 +719,7 @@ let betterDraw = (animal) =>
betterDraw(MyFloat(1.5))
```
+
```js
var MyLibrary = require("myLibrary");
@@ -691,16 +728,15 @@ function betterDraw(animal) {
}
betterDraw({
- TAG: "MyFloat",
- _0: 1.5
- });
+ TAG: "MyFloat",
+ _0: 1.5,
+});
```
**Try not to do that**, as this generates extra noisy output. Instead, use the `@unboxed` attribute to guide ReScript to generate more efficient code:
-
```res example
@@ -720,6 +756,7 @@ let betterDraw = (animal) =>
betterDraw(MyFloat(1.5))
```
+
```js
var MyLibrary = require("myLibrary");
@@ -740,6 +777,7 @@ Alternatively, define two `external`s that both compile to the same JS call:
@module("myLibrary") external drawFloat: float => unit = "draw"
@module("myLibrary") external drawString: string => unit = "draw"
```
+
```js
// Empty output
```
@@ -791,16 +829,17 @@ let logData = data => {
logData(data)
```
+
```js
function logData(data) {
switch (data) {
- case "Dog" :
+ case "Dog":
console.log("Wof");
return;
- case "Cat" :
+ case "Cat":
console.log("Meow");
return;
- case "Bird" :
+ case "Bird":
console.log("Kashiiin");
return;
}
diff --git a/pages/docs/manual/v8.0.0/api/belt.mdx b/pages/docs/manual/v8.0.0/api/belt.mdx
index 657b1b643..69a58a6fc 100644
--- a/pages/docs/manual/v8.0.0/api/belt.mdx
+++ b/pages/docs/manual/v8.0.0/api/belt.mdx
@@ -143,9 +143,9 @@ let k = letters[10]; /* k == None */
Although we've fixed the problem where `k` raises an exception, we now have a type error when trying to capitalize `a`. There are a few things going on here:
-- Reason transforms array index access to the function `Array.get`. So `letters[0]` is the same as `Array.get(letters, 0)`.
+- Reason transforms array index access to the function `Array.get`. So `letters[0]` is the same as `Array.get(letters, 0)`.
- The compiler uses whichever `Array` module is in scope. If you `open Belt`, then it uses `Belt.Array`.
-- `Belt.Array.get` returns values wrapped in options, so `letters[0] == Some("a")`.
+- `Belt.Array.get` returns values wrapped in options, so `letters[0] == Some("a")`.
Fortunately, this is easy to fix:
@@ -160,7 +160,7 @@ let capitalA =
| Some(a) => Some(Js.String.toUpperCase(a))
| None => None
};
-
+
/* Alternatively, use the Option module: */
let capitalA = a->Option.map(Js.String.toUpperCase);
diff --git a/pages/docs/manual/v8.0.0/api/belt/array.mdx b/pages/docs/manual/v8.0.0/api/belt/array.mdx
index b65f1b601..4b04fc6df 100644
--- a/pages/docs/manual/v8.0.0/api/belt/array.mdx
+++ b/pages/docs/manual/v8.0.0/api/belt/array.mdx
@@ -8,7 +8,7 @@ Utililites for `Array` functions.
### Note about index syntax
-Code like `arr[0]` does *not* compile to JavaScript `arr[0]`. ReScript transforms the `[]` index syntax into a function: `Array.get(arr, 0)`. By default, this uses the default standard library's `Array.get` function, which may raise an exception if the index isn't found. If you `open Belt`, it will use the `Belt.Array.get` function which returns options instead of raising exceptions. [See this for more information](../belt.mdx#array-access-runtime-safety).
+Code like `arr[0]` does _not_ compile to JavaScript `arr[0]`. ReScript transforms the `[]` index syntax into a function: `Array.get(arr, 0)`. By default, this uses the default standard library's `Array.get` function, which may raise an exception if the index isn't found. If you `open Belt`, it will use the `Belt.Array.get` function which returns options instead of raising exceptions. [See this for more information](../belt.mdx#array-access-runtime-safety).
## length
diff --git a/pages/docs/manual/v8.0.0/api/belt/float.mdx b/pages/docs/manual/v8.0.0/api/belt/float.mdx
index df49aeab9..7ea4f5aaf 100644
--- a/pages/docs/manual/v8.0.0/api/belt/float.mdx
+++ b/pages/docs/manual/v8.0.0/api/belt/float.mdx
@@ -8,7 +8,7 @@ This module includes convenience methods for handling `float` types.
let toInt: float => int;
```
-Converts a given `float` to an `int`.
+Converts a given `float` to an `int`.
```re example
Js.log(Belt.Float.toInt(1.0) === 1); /* true */
@@ -56,7 +56,7 @@ Js.log(Belt.Float.toString(1.0) === "1.0"); /* true */
let (+): (float, float) => float;
```
-Addition of two `float` values.
+Addition of two `float` values.
Can be opened in a module to avoid dot-notation (`+.`), however this yields a shadow warning (Warning number 44) in the default configuration.
```re example
@@ -84,7 +84,7 @@ Js.log(2.0 - 1.0 === 1.0); /* true */
let ( * ): (float, float) => float;
```
-Multiplication of two `float` values.
+Multiplication of two `float` values.
Can be opened in a module to avoid dot-notation (`*.`), however this yields a shadow warning (Warning number 44) in the default configuration.
```re example
diff --git a/pages/docs/manual/v8.0.0/api/belt/hash-map-int.mdx b/pages/docs/manual/v8.0.0/api/belt/hash-map-int.mdx
index 5d1bd723b..335e83c10 100644
--- a/pages/docs/manual/v8.0.0/api/belt/hash-map-int.mdx
+++ b/pages/docs/manual/v8.0.0/api/belt/hash-map-int.mdx
@@ -46,7 +46,7 @@ let clear: t('b) => unit;
Clears a hash table.
```re example
-let hMap = Belt.HashMap.Int.fromArray([|(1, "1")|])
+let hMap = Belt.HashMap.Int.fromArray([|(1, "1")|])
Belt.HashMap.Int.clear(hMap)
Belt.HashMap.Int.isEmpty(hMap) == true;
```
@@ -60,7 +60,7 @@ let isEmpty: t('a) => bool;
`isEmpty(m)` checks whether a hash map is empty.
```re example
-let hMap = Belt.HashMap.Int.fromArray([|(1, "1")|])
+let hMap = Belt.HashMap.Int.fromArray([|(1, "1")|])
Belt.HashMap.Int.isEmpty(hMap) == false;
```
@@ -73,7 +73,7 @@ let set: (t('a), key, 'a) => unit;
`set(tbl, k, v)` if `k` does not exist, add the binding `k,v`, otherwise, update the old value with the new `v`.
```re example
-
+
let hMap = Belt.HashMap.Int.fromArray([|(2, "2")|]);
Belt.HashMap.Int.set(hMap, 1, "1");
diff --git a/pages/docs/manual/v8.0.0/api/belt/hash-map-string.mdx b/pages/docs/manual/v8.0.0/api/belt/hash-map-string.mdx
index e91eea789..e496b6852 100644
--- a/pages/docs/manual/v8.0.0/api/belt/hash-map-string.mdx
+++ b/pages/docs/manual/v8.0.0/api/belt/hash-map-string.mdx
@@ -46,7 +46,7 @@ let clear: t('b) => unit;
Clears a hash table.
```re example
-let hMap = Belt.HashMap.String.fromArray([|("1", "1")|])
+let hMap = Belt.HashMap.String.fromArray([|("1", "1")|])
Belt.HashMap.String.clear(hMap)
Belt.HashMap.String.isEmpty(hMap) == true;
```
@@ -60,7 +60,7 @@ let isEmpty: t('a) => bool;
`isEmpty(m)` checks whether a hash map is empty.
```re example
-let hMap = Belt.HashMap.String.fromArray([|("1", "1")|])
+let hMap = Belt.HashMap.String.fromArray([|("1", "1")|])
Belt.HashMap.String.isEmpty(hMap) == false;
```
@@ -73,7 +73,7 @@ let set: (t('a), key, 'a) => unit;
`set(tbl, k, v)` if `k` does not exist, add the binding `k,v`, otherwise, update the old value with the new `v`.
```re example
-
+
let hMap = Belt.HashMap.String.fromArray([|("2", "2")|]);
Belt.HashMap.String.set(hMap, "1", "1");
diff --git a/pages/docs/manual/v8.0.0/api/belt/hash-map.mdx b/pages/docs/manual/v8.0.0/api/belt/hash-map.mdx
index c5185c670..bc7a7bc19 100644
--- a/pages/docs/manual/v8.0.0/api/belt/hash-map.mdx
+++ b/pages/docs/manual/v8.0.0/api/belt/hash-map.mdx
@@ -58,8 +58,8 @@ module IntHash =
let hash = a => a;
let eq = (a, b) => a == b;
});
-
-let hMap = Belt.HashMap.fromArray([|(1, "1")|], ~id=(module IntHash))
+
+let hMap = Belt.HashMap.fromArray([|(1, "1")|], ~id=(module IntHash))
Belt.HashMap.clear(hMap)
Belt.HashMap.isEmpty(hMap) == true;
```
@@ -79,7 +79,7 @@ module IntHash =
let hash = a => a;
let eq = (a, b) => a == b;
});
-
+
Belt.HashMap.isEmpty(Belt.HashMap.fromArray([|(1, "1")|], ~id=(module IntHash))) == false;
```
@@ -98,7 +98,7 @@ module IntHash =
let hash = a => a;
let eq = (a, b) => a == b;
});
-
+
let s0 = Belt.HashMap.fromArray([|(2, "2"), (1, "1"), (3, "3")|], ~id=(module IntHash));
Belt.HashMap.set(s0, 2, "3");
@@ -121,7 +121,7 @@ module IntHash =
let hash = a => a;
let eq = (a, b) => a == b;
});
-
+
let s0 = Belt.HashMap.fromArray([|(2, "2"), (1, "1"), (3, "3")|], ~id=(module IntHash));
let s1 = Belt.HashMap.copy(s0)
@@ -145,7 +145,7 @@ module IntHash =
let hash = a => a;
let eq = (a, b) => a == b;
});
-
+
let s0 = Belt.HashMap.make(~hintSize=10, ~id=(module IntHash));
Belt.HashMap.set(s0, 1, "value1");
@@ -168,7 +168,7 @@ module IntHash =
let hash = a => a;
let eq = (a, b) => a == b;
});
-
+
let s0 = Belt.HashMap.make(~hintSize=10, ~id=(module IntHash));
Belt.HashMap.set(s0, 1, "value1");
@@ -191,7 +191,7 @@ module IntHash =
let hash = a => a;
let eq = (a, b) => a == b;
});
-
+
let s0 = Belt.HashMap.make(~hintSize=10, ~id=(module IntHash));
Belt.HashMap.set(s0, 1, "value1");
Belt.HashMap.remove(s0, 1);
@@ -221,7 +221,7 @@ module IntHash =
let hash = a => a;
let eq = (a, b) => a == b;
});
-
+
let s0 = Belt.HashMap.make(~hintSize=10, ~id=(module IntHash));
Belt.HashMap.set(s0, 1, "value1");
Belt.HashMap.forEach(s0, (key, value) => Js.log2(key, value));
@@ -253,7 +253,7 @@ module IntHash =
let hash = a => a;
let eq = (a, b) => a == b;
});
-
+
let s0 = Belt.HashMap.make(~hintSize=10, ~id=(module IntHash));
Belt.HashMap.set(s0, 1, "value1");
Belt.HashMap.set(s0, 2, "value2");
@@ -286,7 +286,7 @@ module IntHash =
let hash = a => a;
let eq = (a, b) => a == b;
});
-
+
let s0 = Belt.HashMap.make(~hintSize=10, ~id=(module IntHash));
Belt.HashMap.set(s0, 1, "value1");
Belt.HashMap.set(s0, 2, "value2");
@@ -311,7 +311,7 @@ module IntHash =
let hash = a => a;
let eq = (a, b) => a == b;
});
-
+
let s0 = Belt.HashMap.make(~hintSize=10, ~id=(module IntHash));
Belt.HashMap.set(s0, 1, "value1");
Belt.HashMap.set(s0, 2, "value2");
@@ -334,7 +334,7 @@ module IntHash =
let hash = a => a;
let eq = (a, b) => a == b;
});
-
+
let s0 = Belt.HashMap.make(~hintSize=10, ~id=(module IntHash));
Belt.HashMap.set(s0, 1, "value1");
Belt.HashMap.set(s0, 2, "value2");
@@ -357,7 +357,7 @@ module IntHash =
let hash = a => a;
let eq = (a, b) => a == b;
});
-
+
let s0 = Belt.HashMap.make(~hintSize=10, ~id=(module IntHash));
Belt.HashMap.set(s0, 1, "value1");
Belt.HashMap.set(s0, 2, "value2");
@@ -380,7 +380,7 @@ module IntHash =
let hash = a => a;
let eq = (a, b) => a == b;
});
-
+
let s0 = Belt.HashMap.make(~hintSize=10, ~id=(module IntHash));
Belt.HashMap.set(s0, 1, "value1");
Belt.HashMap.set(s0, 2, "value2");
@@ -405,7 +405,7 @@ module IntHash =
let hash = a => a;
let eq = (a, b) => a == b;
});
-
+
let s0 = Belt.HashMap.fromArray([|(1, "value1"), (2, "value2")|], ~id=(module IntHash));
Belt.HashMap.toArray(s0) == [|(1, "value1"), (2, "value2")|];
```
@@ -423,7 +423,7 @@ module IntHash =
let hash = a => a;
let eq = (a, b) => a == b;
});
-
+
let hMap = Belt.HashMap.make(~hintSize=10, ~id=(module IntHash));
Belt.HashMap.mergeMany(hMap, [|(1, "1"), (2, "2")|])
```
diff --git a/pages/docs/manual/v8.0.0/api/belt/int.mdx b/pages/docs/manual/v8.0.0/api/belt/int.mdx
index c2f5a912a..6a91b9b62 100644
--- a/pages/docs/manual/v8.0.0/api/belt/int.mdx
+++ b/pages/docs/manual/v8.0.0/api/belt/int.mdx
@@ -8,7 +8,7 @@ This module includes convenience methods for handling `int` types.
let toFloat: int => float;
```
-Converts a given `int` to a `float`.
+Converts a given `int` to a `float`.
```re example
Js.log(Belt.Int.toFloat(1) === 1.0); /* true */
@@ -38,7 +38,6 @@ Converts a given `string` to an `int`. Returns `Some(int)` when the input is a n
Js.log(Belt.Int.fromString("1") === Some(1)); /* true */
```
-
## toString
```re sig
diff --git a/pages/docs/manual/v8.0.0/api/belt/list.mdx b/pages/docs/manual/v8.0.0/api/belt/list.mdx
index 8c47eb8a5..58aaf643b 100644
--- a/pages/docs/manual/v8.0.0/api/belt/list.mdx
+++ b/pages/docs/manual/v8.0.0/api/belt/list.mdx
@@ -547,6 +547,7 @@ Equivalent to: `zipBy(xs, ys, f)->reverse`
Belt.List.mapReverse2([1, 2, 3], [1, 2], (+)); /* [4, 2] */
```
+
## mapReverse2U
```re sig
diff --git a/pages/docs/manual/v8.0.0/api/belt/map.mdx b/pages/docs/manual/v8.0.0/api/belt/map.mdx
index e3c60653b..6fee6ff3c 100644
--- a/pages/docs/manual/v8.0.0/api/belt/map.mdx
+++ b/pages/docs/manual/v8.0.0/api/belt/map.mdx
@@ -58,7 +58,7 @@ module IntCmp =
type t = int;
let cmp = (a, b) => Pervasives.compare(a, b);
});
-
+
Belt.Map.isEmpty(Belt.Map.fromArray([|(1, "1")|], ~id=(module IntCmp))) == false;
```
@@ -492,7 +492,7 @@ module IntCmp =
type t = int;
let cmp = (a, b) => Pervasives.compare(a, b);
});
-
+
let s0 = Belt.Map.fromArray([|(2, "2"), (1, "1"), (3, "3")|], ~id=(module IntCmp));
let s1 = Belt.Map.set(s0, 2, "3");
diff --git a/pages/docs/manual/v8.0.0/api/belt/option.mdx b/pages/docs/manual/v8.0.0/api/belt/option.mdx
index 47da1aeeb..708e58d47 100644
--- a/pages/docs/manual/v8.0.0/api/belt/option.mdx
+++ b/pages/docs/manual/v8.0.0/api/belt/option.mdx
@@ -3,7 +3,7 @@
In Belt we represent the existence and nonexistence of a value by wrapping it
-with the `option` type. In order to make it a bit more convenient to work with
+with the `option` type. In order to make it a bit more convenient to work with
option-types, Belt provides utility-functions for it.
The `option` type is a part of the Reason / OCaml standard library which is defined like this:
diff --git a/pages/docs/manual/v8.0.0/api/belt/range.mdx b/pages/docs/manual/v8.0.0/api/belt/range.mdx
index 08051b9fc..f5e694b83 100644
--- a/pages/docs/manual/v8.0.0/api/belt/range.mdx
+++ b/pages/docs/manual/v8.0.0/api/belt/range.mdx
@@ -3,7 +3,7 @@
A small utility module to provide inclusive range operations for `[start,
-finish]`. Internally it is relying on loops instead of creating new arrays,
+finish]`. Internally it is relying on loops instead of creating new arrays,
which makes it pretty performant and memory friendly.
diff --git a/pages/docs/manual/v8.0.0/api/dom.mdx b/pages/docs/manual/v8.0.0/api/dom.mdx
index 7ed577be7..050f1b88f 100644
--- a/pages/docs/manual/v8.0.0/api/dom.mdx
+++ b/pages/docs/manual/v8.0.0/api/dom.mdx
@@ -471,7 +471,7 @@ type htmlPreElement
## htmlProgressElement
```re sig
-type htmlProgressElement
+type htmlProgressElement
```
## htmlQuoteElement
@@ -489,7 +489,7 @@ type htmlScriptElement
## htmlSelectElement
```re sig
-type htmlSelectElement
+type htmlSelectElement
```
## htmlSlotElement
@@ -630,7 +630,7 @@ type xmlDocument
type event
```
-## uiEvent
+## uiEvent
```re sig
type uiEvent
diff --git a/pages/docs/manual/v8.0.0/api/js/array-2.mdx b/pages/docs/manual/v8.0.0/api/js/array-2.mdx
index dda2ebfcb..c646ce666 100644
--- a/pages/docs/manual/v8.0.0/api/js/array-2.mdx
+++ b/pages/docs/manual/v8.0.0/api/js/array-2.mdx
@@ -27,6 +27,7 @@ let result = Js.Array2.(
reduce((+), 0)
);
```
+
## t
@@ -47,11 +48,11 @@ A type used to describe JavaScript objects that are like an array or are iterabl
## from
- ```re sig
+```re sig
let from: array_like('a) => array('b);
```
-Creates a shallow copy of an array from an array-like object. See [`Array.from`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from) on MDN.
+Creates a shallow copy of an array from an array-like object. See [`Array.from`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from) on MDN.
```re example
let strArr = Js.String.castToArrayLike("abcd");
@@ -60,11 +61,11 @@ Js.Array2.from(strArr) == [|"a", "b", "c", "d"|];
## fromMap
- ```re sig
+```re sig
let fromMap: (array_like('a), 'a => 'b) => array('b);
```
-Creates a new array by applying a function (the second argument) to each item in the `array_like` first argument. See [`Array.from`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from) on MDN.
+Creates a new array by applying a function (the second argument) to each item in the `array_like` first argument. See [`Array.from`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from) on MDN.
```re example
let strArr = Js.String.castToArrayLike("abcd");
@@ -74,7 +75,7 @@ Js.Array2.fromMap(strArr, code) == [|97.0, 98.0, 99.0, 100.0|];
## isArray
- ```re sig
+```re sig
let isArray: 'a => bool;
```
@@ -88,7 +89,7 @@ Js.Array2.isArray("abcd") == false;
## length
- ```re sig
+```re sig
let length: array('a) => int;
```
@@ -96,11 +97,11 @@ Returns the number of elements in the array. See [`Array.length`](https://develo
## copyWithin
- ```re sig
+```re sig
let copyWithin: (t('a), ~to_: int) => t('a);
```
-Copies from the first element in the given array to the designated `~to_` position, returning the resulting array. *This function modifies the original array.* See [`Array.copyWithin`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/copyWithin) on MDN.
+Copies from the first element in the given array to the designated `~to_` position, returning the resulting array. _This function modifies the original array._ See [`Array.copyWithin`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/copyWithin) on MDN.
```re example
let arr = [|100, 101, 102, 103, 104|];
@@ -111,11 +112,11 @@ arr == [|100, 101, 100, 101, 102|];
## copyWithinFrom
- ```re sig
+```re sig
let copyWithinFrom: (t('a), ~to_: int, ~from: int) => t('a);
```
-Copies starting at element `~from` in the given array to the designated `~to_` position, returning the resulting array. *This function modifies the original array.* See [`Array.copyWithin`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/copyWithin) on MDN.
+Copies starting at element `~from` in the given array to the designated `~to_` position, returning the resulting array. _This function modifies the original array._ See [`Array.copyWithin`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/copyWithin) on MDN.
```re example
let arr = [|100, 101, 102, 103, 104|];
@@ -130,7 +131,7 @@ arr == [|102, 103, 104, 103, 104|];
let copyWithinFromRange: (t('a), ~to_: int, ~start: int, ~end_: int) => t('a);
```
-Copies starting at element `~start` in the given array up to but not including `~end_` to the designated `~to_` position, returning the resulting array. *This function modifies the original array.* See [`Array.copyWithin`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/copyWithin) on MDN.
+Copies starting at element `~start` in the given array up to but not including `~end_` to the designated `~to_` position, returning the resulting array. _This function modifies the original array._ See [`Array.copyWithin`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/copyWithin) on MDN.
```re example
let arr = [|100, 101, 102, 103, 104, 105|];
@@ -144,7 +145,8 @@ arr == [|100, 102, 103, 104, 104, 105|];
```re sig
let fillInPlace: (t('a), 'a) => t('a);
```
-Sets all elements of the given array (the first arumgent) to the designated value (the secon argument), returning the resulting array. *This function modifies the original array.* See [`Array.fill`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/fill) on MDN.
+
+Sets all elements of the given array (the first arumgent) to the designated value (the secon argument), returning the resulting array. _This function modifies the original array._ See [`Array.fill`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/fill) on MDN.
```re example
let arr = [|100, 101, 102, 103, 104|];
@@ -158,7 +160,8 @@ arr == [|99, 99, 99, 99, 99|];
```re sig
let fillFromInPlace: (t('a), 'a, ~from: int) => t('a);
```
-Sets all elements of the given array (the first arumgent) from position `~from` to the end to the designated value (the second argument), returning the resulting array. *This function modifies the original array.* See [`Array.fill`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/fill) on MDN.
+
+Sets all elements of the given array (the first arumgent) from position `~from` to the end to the designated value (the second argument), returning the resulting array. _This function modifies the original array._ See [`Array.fill`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/fill) on MDN.
```re example
let arr = [|100, 101, 102, 103, 104|];
@@ -172,21 +175,23 @@ arr == [|100, 101, 99, 99, 99|];
```re sig
let fillRangeInPlace: (t('a), 'a, ~start: int, ~end_: int) => t('a);
```
-Sets the elements of the given array (the first arumgent) from position `~start` up to but not including position `~end_` to the designated value (the second argument), returning the resulting array. *This function modifies the original array.* See [`Array.fill`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/fill) on MDN.
+
+Sets the elements of the given array (the first arumgent) from position `~start` up to but not including position `~end_` to the designated value (the second argument), returning the resulting array. _This function modifies the original array._ See [`Array.fill`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/fill) on MDN.
```re example
let arr = [|100, 101, 102, 103, 104|];
Js.Array2.fillRangeInPlace(arr, 99, ~start=1, ~end_=4)
== [|100, 99, 99, 99, 104|];
arr == [|100, 99, 99, 99, 104|];
-```
+```
## pop
```re sig
let pop: t('a) => option('a);
```
-If the array is not empty, removes the last element and returns it as `Some(value)`; returns `None` if the array is empty. *This function modifies the original array.* See [`Array.pop`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/pop) on MDN.
+
+If the array is not empty, removes the last element and returns it as `Some(value)`; returns `None` if the array is empty. _This function modifies the original array._ See [`Array.pop`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/pop) on MDN.
```re example
let arr = [|100, 101, 102, 103, 104|];
@@ -202,7 +207,8 @@ Js.Array2.pop(empty) == None;
```re sig
let push: (t('a), 'a) => int;
```
-Appends the given value to the array, returning the number of elements in the updated array. *This function modifies the original array.* See [`Array.push`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push) on MDN.
+
+Appends the given value to the array, returning the number of elements in the updated array. _This function modifies the original array._ See [`Array.push`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push) on MDN.
```re example
let arr = [|"ant", "bee", "cat"|];
@@ -215,7 +221,8 @@ arr == [|"ant", "bee", "cat", "dog"|];
```re sig
let pushMany: (t('a), array('a)) => int;
```
-Appends the values from one array (the second argument) to another (the first argument), returning the number of elements in the updated array. *This function modifies the original array.* See [`Array.push`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push) on MDN.
+
+Appends the values from one array (the second argument) to another (the first argument), returning the number of elements in the updated array. _This function modifies the original array._ See [`Array.push`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push) on MDN.
```re example
let arr = [|"ant", "bee", "cat"|];
@@ -228,7 +235,8 @@ arr == [|"ant", "bee", "cat", "dog", "elk"|];
```re sig
let reverseInPlace: t('a) => t('a);
```
-Returns an array with the elements of the input array in reverse order. *This function modifies the original array.* See [`Array.reverse`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse) on MDN.
+
+Returns an array with the elements of the input array in reverse order. _This function modifies the original array._ See [`Array.reverse`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse) on MDN.
```re example
let arr = [|"ant", "bee", "cat"|];
@@ -241,7 +249,8 @@ arr == [|"cat", "bee", "ant"|];
```re sig
let shift: t('a) => option('a);
```
-If the array is not empty, removes the first element and returns it as `Some(value)`; returns `None` if the array is empty. *This function modifies the original array.* See [`Array.shift`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/shift) on MDN.
+
+If the array is not empty, removes the first element and returns it as `Some(value)`; returns `None` if the array is empty. _This function modifies the original array._ See [`Array.shift`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/shift) on MDN.
```re example
let arr = [|100, 101, 102, 103, 104|];
@@ -257,7 +266,8 @@ Js.Array2.shift(empty) == None;
```re sig
let sortInPlace: t('a) => t('a);
```
-Sorts the given array in place and returns the sorted array. JavaScript sorts the array by converting the arguments to UTF-16 strings and sorting them. See the second example with sorting numbers, which does not do a numeric sort. *This function modifies the original array.* See [`Array.sort`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort) on MDN.
+
+Sorts the given array in place and returns the sorted array. JavaScript sorts the array by converting the arguments to UTF-16 strings and sorting them. See the second example with sorting numbers, which does not do a numeric sort. _This function modifies the original array._ See [`Array.sort`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort) on MDN.
```re example
let words = [|"bee", "dog", "ant", "cat"|];
@@ -274,13 +284,14 @@ numbers == [|1, 10, 2, 20, 3, 30|];
```re sig
let sortInPlaceWith: (t('a), ('a, 'a) => int) => t('a);
```
-Sorts the given array in place and returns the sorted array. *This function modifies the original array.*
+
+Sorts the given array in place and returns the sorted array. _This function modifies the original array._
The first argument to `sortInPlaceWith()` is a function that compares two items from the array and returns:
-* an integer less than zero if the first item is less than the second item
-* zero if the items are equal
-* an integer greater than zero if the first item is greater than the second item
+- an integer less than zero if the first item is less than the second item
+- zero if the items are equal
+- an integer greater than zero if the first item is greater than the second item
See [`Array.sort`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort) on MDN.
@@ -293,7 +304,7 @@ let byLength = (s1, s2) => {
Js.Array2.sortInPlaceWith(words, byLength)
== [|"dog", "horse", "camel", "aardvark"|];
-
+
// sort in reverse numeric order
let numbers = [|3, 30, 10, 1, 20, 2|];
let reverseNumeric = (n1, n2) => {n2 - n1};
@@ -306,7 +317,8 @@ Js.Array2.sortInPlaceWith(numbers, reverseNumeric)
```re sig
let spliceInPlace: (t('a), ~pos: int, ~remove: int, ~add: array('a)) => t('a);
```
-Starting at position `~pos`, remove `~remove` elements and then add the elements from the `~add` array. Returns an array consisting of the removed items. *This function modifies the original array.* See [`Array.splice`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice) on MDN.
+
+Starting at position `~pos`, remove `~remove` elements and then add the elements from the `~add` array. Returns an array consisting of the removed items. _This function modifies the original array._ See [`Array.splice`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice) on MDN.
```re example
let arr = [|"a", "b", "c", "d", "e", "f"|];
@@ -327,7 +339,8 @@ arr3 == [|"a", "b", "c", "d", "e", "f", "x", "y", "z"|];
```re sig
let removeFromInPlace: (t('a), ~pos: int) => t('a);
```
-Removes elements from the given array starting at position `~pos` to the end of the array, returning the removed elements. *This function modifies the original array.* See [`Array.splice`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice) on MDN.
+
+Removes elements from the given array starting at position `~pos` to the end of the array, returning the removed elements. _This function modifies the original array._ See [`Array.splice`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice) on MDN.
```re example
let arr = [|"a", "b", "c", "d", "e", "f"|];
@@ -340,7 +353,8 @@ arr == [|"a", "b", "c", "d"|];
```re sig
let removeCountInPlace: (t('a), ~pos: int, ~count: int) => t('a);
```
-Removes `~count` elements from the given array starting at position `~pos`, returning the removed elements. *This function modifies the original array.* See [`Array.splice`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice) on MDN.
+
+Removes `~count` elements from the given array starting at position `~pos`, returning the removed elements. _This function modifies the original array._ See [`Array.splice`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice) on MDN.
```re example
let arr = [|"a", "b", "c", "d", "e", "f"|];
@@ -353,7 +367,8 @@ arr == [|"a", "b", "f"|];
```re sig
let unshift: (t('a), 'a) => int;
```
-Adds the given element to the array, returning the new number of elements in the array. *This function modifies the original array.* See [`Array.unshift`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/unshift) on MDN.
+
+Adds the given element to the array, returning the new number of elements in the array. _This function modifies the original array._ See [`Array.unshift`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/unshift) on MDN.
```re example
let arr = [|"b", "c", "d"|];
@@ -366,7 +381,8 @@ arr == [|"a", "b", "c", "d"|];
```re sig
let unshiftMany: (t('a), array('a)) => int;
```
-Adds the elements in the second array argument at the beginning of the first array argument, returning the new number of elements in the array. *This function modifies the original array.* See [`Array.unshift`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/unshift) on MDN.
+
+Adds the elements in the second array argument at the beginning of the first array argument, returning the new number of elements in the array. _This function modifies the original array._ See [`Array.unshift`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/unshift) on MDN.
```re example
let arr = [|"d", "e"|];
@@ -379,6 +395,7 @@ arr == [|"a", "b", "c", "d", "e"|];
```re sig
let append: (t('a), 'a) => t('a);
```
+
Deprecated. `append()` is not type-safe. Use `concat()` instead.
## concat
@@ -386,6 +403,7 @@ Deprecated. `append()` is not type-safe. Use `concat()` instead.
```re sig
let concat: (t('a), t('a)) => t('a);
```
+
Concatenates the second array argument to the first array argument, returning a new array. The original arrays are not modified. See [`Array.concat`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat) on MDN.
```re example
@@ -398,6 +416,7 @@ Js.Array2.concat([|"a", "b"|], [|"c", "d", "e"|])
```re sig
let concatMany: (t('a), array(t('a))) => t('a);
```
+
The second argument to `concatMany()` is an array of arrays; these are added at the end of the first argument, returning a new array. See [`Array.concat`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat) on MDN.
```re example
@@ -410,6 +429,7 @@ Js.Array2.concatMany([|"a", "b", "c"|], [| [|"d", "e"|], [|"f", "g", "h"|] |])
```re sig
let includes: (t('a), 'a) => bool;
```
+
Returns true if the given value is in the array, `false` otherwise. See [`Array.includes`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes) on MDN.
```re example
@@ -422,6 +442,7 @@ Js.Array2.includes([|"a", "b", "c"|], "x") == false;
```re sig
let indexOf: (t('a), 'a) => int;
```
+
Returns the index of the first element in the array that has the given value. If the value is not in the array, returns -1. See [`Array.indexOf`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf) on MDN.
```re example
@@ -434,6 +455,7 @@ Js.Array2.indexOf([|100, 101, 102, 103|], 999) == -1;
```re sig
let indexOfFrom: (t('a), 'a, ~from: int) => int;
```
+
Returns the index of the first element in the array with the given value. The search starts at position `~from`. See [`Array.indexOf`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf) on MDN.
```re example
@@ -447,6 +469,7 @@ Js.Array2.indexOfFrom([|"a", "b", "a", "c", "a"|], "b", ~from=2) == -1;
```re sig
let joinWith: (t('a), string) => string;
```
+
This function converts each element of the array to a string (via JavaScript) and concatenates them, separated by the string given in the first argument, into a single string. See [`Array.join`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join) on MDN.
```re example
@@ -461,6 +484,7 @@ Js.Array2.joinWith([|2.5, 3.6, 3e-2|], ";") == "2.5;3.6;0.03";
```re sig
let lastIndexOf: (t('a), 'a) => int;
```
+
Returns the index of the last element in the array that has the given value. If the value is not in the array, returns -1. See [`Array.lastIndexOf`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/lastIndexOf) on MDN.
```re example
@@ -473,6 +497,7 @@ Js.Array2.lastIndexOf([|"a", "b", "a", "c"|], "x") == -1;
```re sig
let lastIndexOfFrom: (t('a), 'a, ~from: int) => int;
```
+
Returns the index of the last element in the array that has the given value, searching from position `~from` down to the start of the array. If the value is not in the array, returns -1. See [`Array.lastIndexOf`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/lastIndexOf) on MDN.
```re example
@@ -485,6 +510,7 @@ Js.Array2.lastIndexOfFrom([|"a", "b", "a", "c", "a", "d"|], "c", ~from=2) == -1;
```re sig
let slice: (t('a), ~start: int, ~end_: int) => t('a);
```
+
Returns a shallow copy of the given array from the `~start` index up to but not including the `~end_` position. Negative numbers indicate an offset from the end of the array. See [`Array.slice`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice) on MDN.
```re example
@@ -499,12 +525,15 @@ Js.Array2.slice(arr, ~start=9, ~end_=10) == [| |];
```re sig
let copy: t('a) => t('a);
```
+
Returns a copy of the entire array. Same as `Js.Array2.Slice(arr, ~start=0, ~end_=Js.Array2.length(arr))`. See [`Array.slice`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice) on MDN.
+
## sliceFrom
```re sig
let sliceFrom: (t('a), int) => t('a);
```
+
Returns a shallow copy of the given array from the given index to the end. See [`Array.slice`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice) on MDN.
```re example
@@ -516,6 +545,7 @@ Js.Array2.sliceFrom([|100, 101, 102, 103, 104|], 2) == [|102, 103, 104|];
```re sig
let toString: t('a) => string;
```
+
Converts the array to a string. Each element is converted to a string using JavaScript. Unlike the JavaScript `Array.toString()`, all elements in a ReasonML array must have the same type. See [`Array.toString`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/toString) on MDN.
```re example
@@ -528,6 +558,7 @@ Js.Array2.toString([|"a", "b", "c"|]) == "a,b,c";
```re sig
let toLocaleString: t('a) => string;
```
+
Converts the array to a string using the conventions of the current locale. Each element is converted to a string using JavaScript. Unlike the JavaScript `Array.toLocaleString()`, all elements in a ReasonML array must have the same type. See [`Array.toLocaleString`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/toLocaleString) on MDN.
```re example
@@ -541,6 +572,7 @@ Js.Array2.toLocaleString([|Js.Date.make()|]);
```re sig
let every: (t('a), 'a => bool) => bool;
```
+
The first argument to `every()` is an array. The second argument is a predicate function that returns a boolean. The `every()` function returns `true` if the predicate function is true for all items in the given array. If given an empty array, returns `true`. See [`Array.every`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every) on MDN.
```re example
@@ -551,24 +583,25 @@ Js.Array2.every([|6, 22, 7, 4|], isEven) == false;
## everyi
-```re sig
+````re sig
let everyi: (t('a), ('a, int) => bool) => bool;
The first argument to `everyi()` is an array. The second argument is a predicate function with two arguments: an array element and that element’s index; it returns a boolean. The `everyi()` function returns `true` if the predicate function is true for all items in the given array. If given an empty array, returns `true`. See [`Array.every`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every) on MDN.
```re example
// determine if all even-index items are positive
-let evenIndexPositive = (item, index) =>
+let evenIndexPositive = (item, index) =>
{(index mod 2 == 0) ? item > 0 : true;};
Js.Array2.everyi([|6, -3, 5, 8|], evenIndexPositive) == true;
Js.Array2.everyi([|6, 3, -5, 8|], evenIndexPositive) == false;
-```
+````
## filter
```re sig
let filter: (t('a), 'a => bool) => t('a);
```
+
Applies the given predicate function (the second argument) to each element in the array; the result is an array of those elements for which the predicate function returned `true`. See [`Array.filter`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) on MDN.
```re example
@@ -582,11 +615,12 @@ Js.Array2.filter( [|"abc", "", "", "def", "ghi"|], nonEmpty)
```re sig
let filteri: (t('a), ('a, int) => bool) => t('a);
```
-Each element of the given array are passed to the predicate function. The return value is an array of all those elements for which the predicate function returned `true`. See [`Array.filter`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) on MDN.
+
+Each element of the given array are passed to the predicate function. The return value is an array of all those elements for which the predicate function returned `true`. See [`Array.filter`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) on MDN.
```re example
// keep only positive elements at odd indices
-let positiveOddElement = (item, index) =>
+let positiveOddElement = (item, index) =>
{(index mod 2 == 1) && (item > 0)};
Js.Array2.filteri([|6, 3, 5, 8, 7, -4, 1|],
@@ -598,6 +632,7 @@ Js.Array2.filteri([|6, 3, 5, 8, 7, -4, 1|],
```re sig
let find: (t('a), 'a => bool) => option('a);
```
+
Returns `Some(value)` for the first element in the array that satisifies the given predicate function, or `None` if no element satisifies the predicate. See [`Array.find`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find) on MDN.
```re example
@@ -611,11 +646,12 @@ Js.Array2.find([|33, 22, 55, 77, 44|], (x) => {x < 0}) == None;
```re sig
let findi: (t('a), ('a, int) => bool) => option('a);
```
+
Returns `Some(value)` for the first element in the array that satisifies the given predicate function, or `None` if no element satisifies the predicate. The predicate function takes an array element and an index as its parameters. See [`Array.find`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find) on MDN.
```re example
// find first positive item at an odd index
-let positiveOddElement = (item, index) =>
+let positiveOddElement = (item, index) =>
{(index mod 2 == 1) && (item > 0)};
Js.Array2.findi([|66, -33, 55, 88, 22|], positiveOddElement) == Some(88);
@@ -627,6 +663,7 @@ Js.Array2.findi([|66, -33, 55, -88, 22|], positiveOddElement) == None;
```re sig
let findIndex: (t('a), 'a => bool) => int;
```
+
Returns the index of the first element in the array that satisifies the given predicate function, or -1 if no element satisifies the predicate. See [`Array.find`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find) on MDN.
```re example
@@ -639,11 +676,12 @@ Js.Array2.findIndex([|33, 22, 55, 77, 44|], (x) => {x < 0}) == -1;
```re sig
let findIndexi: (t('a), ('a, int) => bool) => int;
```
+
Returns `Some(value)` for the first element in the array that satisifies the given predicate function, or `None` if no element satisifies the predicate. The predicate function takes an array element and an index as its parameters. See [`Array.find`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find) on MDN.
```re example
// find index of first positive item at an odd index
-let positiveOddElement = (item, index) =>
+let positiveOddElement = (item, index) =>
{(index mod 2 == 1) && (item > 0)};
Js.Array2.findIndexi([|66, -33, 55, 88, 22|], positiveOddElement) == 3;
@@ -655,6 +693,7 @@ Js.Array2.findIndexi([|66, -33, 55, -88, 22|], positiveOddElement) == -1;
```re sig
let forEach: (t('a), 'a => unit) => unit;
```
+
The `forEach()` function applies the function given as the second argument to each element in the array. The function you provide returns `unit`, and the `forEach()` function also returns `unit`. You use `forEach()` when you need to process each element in the array but not return any new array or value; for example, to print the items in an array. See [`Array.forEach`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach) on MDN.
```re example
@@ -667,6 +706,7 @@ Js.Array2.forEach([|"a", "b", "c"|], (x) => {Js.log(x)}) == ();
```re sig
let forEachi: (t('a), ('a, int) => unit) => unit;
```
+
The `forEachi()` function applies the function given as the second argument to each element in the array. The function you provide takes an item in the array and its index number, and returns `unit`. The `forEachi()` function also returns `unit`. You use `forEachi()` when you need to process each element in the array but not return any new array or value; for example, to print the items in an array. See [`Array.forEach`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach) on MDN.
```re example
@@ -679,6 +719,7 @@ Js.Array2.forEachi([|"a", "b", "c"|], (item, index) => {Js.log2((index + 1), ite
```re sig
let map: (t('a), 'a => 'b) => t('b);
```
+
Applies the function (the second argument) to each item in the array, returning a new array. The result array does not have to have elements of the same type as the input array. See [`Array.map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) on MDN.
```re example
@@ -692,6 +733,7 @@ Js.Array2.map([|"animal", "vegetable", "mineral"|], Js.String.length)
```re sig
let mapi: (t('a), ('a, int) => 'b) => t('b);
```
+
Applies the function (the second argument) to each item in the array, returning a new array. The function acceps two arguments: an item from the array and its index number. The result array does not have to have elements of the same type as the input array. See [`Array.map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) on MDN.
```re example
@@ -705,7 +747,8 @@ Js.Array2.mapi([|10, 11, 12|], product) == [|0, 11, 24|];
```re sig
let reduce: (t('a), ('b, 'a) => 'b, 'b) => 'b;
```
-The `reduce()` function takes three parameters: an array, a *reducer function*, and a beginning accumulator value. The reducer function has two parameters: an accumulated value and an element of the array.
+
+The `reduce()` function takes three parameters: an array, a _reducer function_, and a beginning accumulator value. The reducer function has two parameters: an accumulated value and an element of the array.
`reduce()` first calls the reducer function with the beginning value and the first element in the array. The result becomes the new accumulator value, which is passed in to the reducer function along with the second element in the array. `reduce()` proceeds through the array, passing in the result of each stage as the accumulator to the reducer function.
@@ -729,7 +772,8 @@ Js.Array2.reduce([|2.0, 4.0|],
```re sig
let reducei: (t('a), ('b, 'a, int) => 'b, 'b) => 'b;
```
-The `reducei()` function takes three parameters: an array, a *reducer function*, and a beginning accumulator value. The reducer function has three parameters: an accumulated value, an element of the array, and the index of that element.
+
+The `reducei()` function takes three parameters: an array, a _reducer function_, and a beginning accumulator value. The reducer function has three parameters: an accumulated value, an element of the array, and the index of that element.
`reducei()` first calls the reducer function with the beginning value, the first element in the array, and zero (its index). The result becomes the new accumulator value, which is passed to the reducer function along with the second element in the array and one (its index). `reducei()` proceeds from left to right through the array, passing in the result of each stage as the accumulator to the reducer function.
@@ -753,11 +797,12 @@ Js.Array2.reducei([|2, 5, 1, 4, 3|], sumOfEvens, 0) == 6;
```re sig
let reduceRight: (t('a), ('b, 'a) => 'b, 'b) => 'b;
```
-The `reduceRight()` function takes three parameters: an array, a *reducer function*, and a beginning accumulator value. The reducer function has two parameters: an accumulated value and an element of the array.
+
+The `reduceRight()` function takes three parameters: an array, a _reducer function_, and a beginning accumulator value. The reducer function has two parameters: an accumulated value and an element of the array.
`reduceRight()` first calls the reducer function with the beginning value and the last element in the array. The result becomes the new accumulator value, which is passed in to the reducer function along with the next-to-last element in the array. `reduceRight()` proceeds from right to left through the array, passing in the result of each stage as the accumulator to the reducer function.
-When all array elements are processed, the final value of the accumulator becomes the return value of `reduceRight()`. See [`Array.reduceRight`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduceRight) on MDN.
+When all array elements are processed, the final value of the accumulator becomes the return value of `reduceRight()`. See [`Array.reduceRight`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduceRight) on MDN.
**NOTE:** In many cases, `reduce()` and `reduceRight()` give the same result. However, see the last example here and compare it to the example from `reduce()`, where order makes a difference.
@@ -776,7 +821,8 @@ Js.Array2.reduceRight([|2.0, 4.0|],
```re sig
let reduceRighti: (t('a), ('b, 'a, int) => 'b, 'b) => 'b;
```
-The `reduceRighti()` function takes three parameters: an array, a *reducer function*, and a beginning accumulator value. The reducer function has three parameters: an accumulated value, an element of the array, and the index of that element. `reduceRighti()` first calls the reducer function with the beginning value, the last element in the array, and its index (length of array minus one). The result becomes the new accumulator value, which is passed in to the reducer function along with the second element in the array and one (its index). `reduceRighti()` proceeds from right to left through the array, passing in the result of each stage as the accumulator to the reducer function.
+
+The `reduceRighti()` function takes three parameters: an array, a _reducer function_, and a beginning accumulator value. The reducer function has three parameters: an accumulated value, an element of the array, and the index of that element. `reduceRighti()` first calls the reducer function with the beginning value, the last element in the array, and its index (length of array minus one). The result becomes the new accumulator value, which is passed in to the reducer function along with the second element in the array and one (its index). `reduceRighti()` proceeds from right to left through the array, passing in the result of each stage as the accumulator to the reducer function.
When all array elements are processed, the final value of the accumulator becomes the return value of `reduceRighti()`. See [`Array.reduceRight`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduceRight) on MDN.
@@ -800,6 +846,7 @@ Js.Array2.reduceRighti([|2, 5, 1, 4, 3|], sumOfEvens, 0) == 6;
```re sig
let some: (t('a), 'a => bool) => bool;
```
+
Returns `true` if the predicate function given as the second argument to `some()` returns `true` for any element in the array; `false` otherwise.
```re example
@@ -814,6 +861,7 @@ Js.Array2.some([|3, 7, 5, 1, 9|], isEven) == false;
```re sig
let somei: (t('a), ('a, int) => bool) => bool;
```
+
Returns `true` if the predicate function given as the second argument to `somei()` returns `true` for any element in the array; `false` otherwise. The predicate function has two arguments: an item from the array and the index value
```re example
@@ -835,6 +883,7 @@ Js.Array2.somei([|"a", "bc", "def", "gh"|], sameLength) == false;
```re sig
let unsafe_get: (array('a), int) => 'a;
```
+
Returns the value at the given position in the array if the position is in bounds; returns the JavaScript value `undefined` otherwise.
```re example
@@ -848,7 +897,8 @@ Js.Array2.unsafe_get(arr, 4); // returns undefined
```re sig
let unsafe_set: (array('a), int, 'a) => unit;
```
-Sets the value at the given position in the array if the position is in bounds. If the index is out of bounds, well, “here there be dragons.“ *This function modifies the original array.*
+
+Sets the value at the given position in the array if the position is in bounds. If the index is out of bounds, well, “here there be dragons.“ _This function modifies the original array._
```re example
let arr = [|100, 101, 102, 103|];
diff --git a/pages/docs/manual/v8.0.0/api/js/array.mdx b/pages/docs/manual/v8.0.0/api/js/array.mdx
index 29e47e346..938eedb6a 100644
--- a/pages/docs/manual/v8.0.0/api/js/array.mdx
+++ b/pages/docs/manual/v8.0.0/api/js/array.mdx
@@ -52,7 +52,7 @@ A type used to describe JavaScript objects that are like an array or are iterabl
let from: array_like('a) => array('b);
```
-Creates a shallow copy of an array from an array-like object. See [`Array.from`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from) on MDN.
+Creates a shallow copy of an array from an array-like object. See [`Array.from`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from) on MDN.
```re example
let strArr = Js.String.castToArrayLike("abcd");
@@ -65,7 +65,7 @@ Js.Array.from(strArr) == [|"a", "b", "c", "d"|];
let fromMap: (array_like('a), 'a => 'b) => array('b);
```
-Creates a new array by applying a function (the second argument) to each item in the `array_like` first argument. See [`Array.from`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from) on MDN.
+Creates a new array by applying a function (the second argument) to each item in the `array_like` first argument. See [`Array.from`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from) on MDN.
```re example
let strArr = Js.String.castToArrayLike("abcd");
@@ -101,7 +101,7 @@ Returns the number of elements in the array. See [`Array.length`](https://develo
let copyWithin: (~to_: int, t('a)) => t('a);
```
-Copies from the first element in the given array to the designated `~to_` position, returning the resulting array. *This function modifies the original array.* See [`Array.copyWithin`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/copyWithin) on MDN.
+Copies from the first element in the given array to the designated `~to_` position, returning the resulting array. _This function modifies the original array._ See [`Array.copyWithin`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/copyWithin) on MDN.
```re example
let arr = [|100, 101, 102, 103, 104|];
@@ -116,7 +116,7 @@ arr == [|100, 101, 100, 101, 102|];
let copyWithinFrom: (~to_: int, ~from: int, t('a)) => t('a);
```
-Copies starting at element `~from` in the given array to the designated `~to_` position, returning the resulting array. *This function modifies the original array.* See [`Array.copyWithin`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/copyWithin) on MDN.
+Copies starting at element `~from` in the given array to the designated `~to_` position, returning the resulting array. _This function modifies the original array._ See [`Array.copyWithin`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/copyWithin) on MDN.
```re example
let arr = [|100, 101, 102, 103, 104|];
@@ -131,7 +131,7 @@ arr == [|102, 103, 104, 103, 104|];
let copyWithinFromRange: (~to_: int, ~start: int, ~end_: int, t('a)) => t('a);
```
-Copies starting at element `~start` in the given array up to but not including `~end_` to the designated `~to_` position, returning the resulting array. *This function modifies the original array.* See [`Array.copyWithin`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/copyWithin) on MDN.
+Copies starting at element `~start` in the given array up to but not including `~end_` to the designated `~to_` position, returning the resulting array. _This function modifies the original array._ See [`Array.copyWithin`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/copyWithin) on MDN.
```re example
let arr = [|100, 101, 102, 103, 104, 105|];
@@ -145,7 +145,8 @@ arr == [|100, 102, 103, 104, 104, 105|];
```re sig
let fillInPlace: ('a, t('a)) => t('a);
```
-Sets all elements of the given array (the second arumgent) to the designated value (the first argument), returning the resulting array. *This function modifies the original array.* See [`Array.fill`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/fill) on MDN.
+
+Sets all elements of the given array (the second arumgent) to the designated value (the first argument), returning the resulting array. _This function modifies the original array._ See [`Array.fill`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/fill) on MDN.
```re example
let arr = [|100, 101, 102, 103, 104|];
@@ -159,7 +160,8 @@ arr == [|99, 99, 99, 99, 99|];
```re sig
let fillFromInPlace: ('a, ~from: int, t('a)) => t('a);
```
-Sets all elements of the given array (the last arumgent) from position `~from` to the end to the designated value (the first argument), returning the resulting array. *This function modifies the original array.* See [`Array.fill`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/fill) on MDN.
+
+Sets all elements of the given array (the last arumgent) from position `~from` to the end to the designated value (the first argument), returning the resulting array. _This function modifies the original array._ See [`Array.fill`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/fill) on MDN.
```re example
let arr = [|100, 101, 102, 103, 104|];
@@ -174,14 +176,14 @@ arr == [|100, 101, 99, 99, 99|];
let fillRangeInPlace: ('a, ~start: int, ~end_: int, t('a)) => t('a);
```
-Sets the elements of the given array (the last arumgent) from position `~start` up to but not including position `~end_` to the designated value (the first argument), returning the resulting array. *This function modifies the original array.* See [`Array.fill`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/fill) on MDN.
+Sets the elements of the given array (the last arumgent) from position `~start` up to but not including position `~end_` to the designated value (the first argument), returning the resulting array. _This function modifies the original array._ See [`Array.fill`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/fill) on MDN.
```re example
let arr = [|100, 101, 102, 103, 104|];
Js.Array.fillRangeInPlace(99, ~start=1, ~end_=4, arr)
== [|100, 99, 99, 99, 104|];
arr == [|100, 99, 99, 99, 104|];
-```
+```
## pop
@@ -189,7 +191,7 @@ arr == [|100, 99, 99, 99, 104|];
let pop: t('a) => option('a);
```
-If the array is not empty, removes the last element and returns it as `Some(value)`; returns `None` if the array is empty. *This function modifies the original array.* See [`Array.pop`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/pop) on MDN.
+If the array is not empty, removes the last element and returns it as `Some(value)`; returns `None` if the array is empty. _This function modifies the original array._ See [`Array.pop`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/pop) on MDN.
```re example
let arr = [|100, 101, 102, 103, 104|];
@@ -206,7 +208,7 @@ Js.Array.pop(empty) == None;
let push: ('a, t('a)) => int;
```
-Appends the given value to the array, returning the number of elements in the updated array. *This function modifies the original array.* See [`Array.push`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push) on MDN.
+Appends the given value to the array, returning the number of elements in the updated array. _This function modifies the original array._ See [`Array.push`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push) on MDN.
```re example
let arr = [|"ant", "bee", "cat"|];
@@ -220,7 +222,7 @@ arr == [|"ant", "bee", "cat", "dog"|];
let pushMany: (array('a), t('a)) => int;
```
-Appends the values from one array (the first argument) to another (the second argument), returning the number of elements in the updated array. *This function modifies the original array.* See [`Array.push`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push) on MDN.
+Appends the values from one array (the first argument) to another (the second argument), returning the number of elements in the updated array. _This function modifies the original array._ See [`Array.push`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push) on MDN.
```re example
let arr = [|"ant", "bee", "cat"|];
@@ -234,7 +236,7 @@ arr == [|"ant", "bee", "cat", "dog", "elk"|];
let reverseInPlace: t('a) => t('a);
```
-Returns an array with the elements of the input array in reverse order. *This function modifies the original array.* See [`Array.reverse`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse) on MDN.
+Returns an array with the elements of the input array in reverse order. _This function modifies the original array._ See [`Array.reverse`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse) on MDN.
```re example
let arr = [|"ant", "bee", "cat"|];
@@ -247,7 +249,8 @@ arr == [|"cat", "bee", "ant"|];
```re sig
let shift: t('a) => option('a);
```
-If the array is not empty, removes the first element and returns it as `Some(value)`; returns `None` if the array is empty. *This function modifies the original array.* See [`Array.shift`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/shift) on MDN.
+
+If the array is not empty, removes the first element and returns it as `Some(value)`; returns `None` if the array is empty. _This function modifies the original array._ See [`Array.shift`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/shift) on MDN.
```re example
let arr = [|100, 101, 102, 103, 104|];
@@ -257,13 +260,14 @@ arr == [|101, 102, 103, 104|];
let empty: array(int) = [| |];
Js.Array.shift(empty) == None;
```
+
## sortInPlace
```re sig
let sortInPlace: t('a) => t('a);
```
-Sorts the given array in place and returns the sorted array. JavaScript sorts the array by converting the arguments to UTF-16 strings and sorting them. See the second example with sorting numbers, which does not do a numeric sort. *This function modifies the original array.* See [`Array.sort`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort) on MDN.
+Sorts the given array in place and returns the sorted array. JavaScript sorts the array by converting the arguments to UTF-16 strings and sorting them. See the second example with sorting numbers, which does not do a numeric sort. _This function modifies the original array._ See [`Array.sort`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort) on MDN.
```re example
let words = [|"bee", "dog", "ant", "cat"|];
@@ -281,13 +285,13 @@ numbers == [|1, 10, 2, 20, 3, 30|];
let sortInPlaceWith: (('a, 'a) => int, t('a)) => t('a);
```
-Sorts the given array in place and returns the sorted array. *This function modifies the original array.*
+Sorts the given array in place and returns the sorted array. _This function modifies the original array._
The first argument to `sortInPlaceWith()` is a function that compares two items from the array and returns:
-* an integer less than zero if the first item is less than the second item
-* zero if the items are equal
-* an integer greater than zero if the first item is greater than the second item
+- an integer less than zero if the first item is less than the second item
+- zero if the items are equal
+- an integer greater than zero if the first item is greater than the second item
See [`Array.sort`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort) on MDN.
@@ -300,7 +304,7 @@ let byLength = (s1, s2) => {
Js.Array.sortInPlaceWith(byLength, words)
== [|"dog", "horse", "camel", "aardvark"|];
-
+
// sort in reverse numeric order
let numbers = [|3, 30, 10, 1, 20, 2|];
let reverseNumeric = (n1, n2) => {n2 - n1};
@@ -314,7 +318,7 @@ Js.Array.sortInPlaceWith(reverseNumeric, numbers)
let spliceInPlace: (~pos: int, ~remove: int, ~add: array('a), t('a)) => t('a);
```
-Starting at position `~pos`, remove `~remove` elements and then add the elements from the `~add` array. Returns an array consisting of the removed items. *This function modifies the original array.* See [`Array.splice`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice) on MDN.
+Starting at position `~pos`, remove `~remove` elements and then add the elements from the `~add` array. Returns an array consisting of the removed items. _This function modifies the original array._ See [`Array.splice`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice) on MDN.
```re example
let arr = [|"a", "b", "c", "d", "e", "f"|];
@@ -336,7 +340,7 @@ arr3 == [|"a", "b", "c", "d", "e", "f", "x", "y", "z"|];
let removeFromInPlace: (~pos: int, t('a)) => t('a);
```
-Removes elements from the given array starting at position `~pos` to the end of the array, returning the removed elements. *This function modifies the original array.* See [`Array.splice`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice) on MDN.
+Removes elements from the given array starting at position `~pos` to the end of the array, returning the removed elements. _This function modifies the original array._ See [`Array.splice`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice) on MDN.
```re example
let arr = [|"a", "b", "c", "d", "e", "f"|];
@@ -350,7 +354,7 @@ arr == [|"a", "b", "c", "d"|];
let removeCountInPlace: (~pos: int, ~count: int, t('a)) => t('a);
```
-Removes `~count` elements from the given array starting at position `~pos`, returning the removed elements. *This function modifies the original array.* See [`Array.splice`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice) on MDN.
+Removes `~count` elements from the given array starting at position `~pos`, returning the removed elements. _This function modifies the original array._ See [`Array.splice`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice) on MDN.
```re example
let arr = [|"a", "b", "c", "d", "e", "f"|];
@@ -364,7 +368,7 @@ arr == [|"a", "b", "f"|];
let unshift: ('a, t('a)) => int;
```
-Adds the given element to the array, returning the new number of elements in the array. *This function modifies the original array.* See [`Array.unshift`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/unshift) on MDN.
+Adds the given element to the array, returning the new number of elements in the array. _This function modifies the original array._ See [`Array.unshift`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/unshift) on MDN.
```re example
let arr = [|"b", "c", "d"|];
@@ -378,7 +382,7 @@ arr == [|"a", "b", "c", "d"|];
let unshiftMany: (array('a), t('a)) => int;
```
-Adds the elements in the first array argument at the beginning of the second array argument, returning the new number of elements in the array. *This function modifies the original array.* See [`Array.unshift`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/unshift) on MDN.
+Adds the elements in the first array argument at the beginning of the second array argument, returning the new number of elements in the array. _This function modifies the original array._ See [`Array.unshift`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/unshift) on MDN.
```re example
let arr = [|"d", "e"|];
@@ -438,6 +442,7 @@ Js.Array.includes("x", [|"a", "b", "c"|]) == false;
```re sig
let indexOf: ('a, t('a)) => int;
```
+
Returns the index of the first element in the array that has the given value. If the value is not in the array, returns -1. See [`Array.indexOf`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf) on MDN.
```re example
@@ -465,6 +470,7 @@ Js.Array.indexOfFrom("b", ~from=2, [|"a", "b", "a", "c", "a"|]) == -1;
```re sig
let join: t('a) => string;
```
+
Deprecated. Use `joinWith` instead.
## joinWith
@@ -472,6 +478,7 @@ Deprecated. Use `joinWith` instead.
```re sig
let joinWith: (string, t('a)) => string;
```
+
This function converts each element of the array to a string (via JavaScript) and concatenates them, separated by the string given in the first argument, into a single string. See [`Array.join`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join) on MDN.
```re example
@@ -617,7 +624,7 @@ The first argument to `everyi()` is a predicate function with two arguments: an
```re example
// determine if all even-index items are positive
-let evenIndexPositive = (item, index) =>
+let evenIndexPositive = (item, index) =>
{(index mod 2 == 0) ? item > 0 : true;};
Js.Array.everyi(evenIndexPositive, [|6, -3, 5, 8|]) == true;
@@ -638,18 +645,17 @@ Js.Array.filter(nonEmpty, [|"abc", "", "", "def", "ghi"|])
== [|"abc", "def", "ghi"|];
```
-
## filteri
```re sig
let filteri: (('a, int) => bool, t('a)) => t('a);
```
-Each element of the given array are passed to the predicate function. The return value is an array of all those elements for which the predicate function returned `true`. See [`Array.filter`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) on MDN.
+Each element of the given array are passed to the predicate function. The return value is an array of all those elements for which the predicate function returned `true`. See [`Array.filter`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) on MDN.
```re example
// keep only positive elements at odd indices
-let positiveOddElement = (item, index) =>
+let positiveOddElement = (item, index) =>
{(index mod 2 == 1) && (item > 0)};
Js.Array.filteri(positiveOddElement,
@@ -680,7 +686,7 @@ Returns `Some(value)` for the first element in the array that satisifies the giv
```re example
// find first positive item at an odd index
-let positiveOddElement = (item, index) =>
+let positiveOddElement = (item, index) =>
{(index mod 2 == 1) && (item > 0)};
Js.Array.findi(positiveOddElement, [|66, -33, 55, 88, 22|]) == Some(88);
@@ -699,6 +705,7 @@ Returns the index of the first element in the array that satisifies the given pr
Js.Array.findIndex((x) => {x < 0}, [|33, 22, -55, 77, -44|]) == 2;
Js.Array.findIndex((x) => {x < 0}, [|33, 22, 55, 77, 44|]) == -1;
```
+
## findIndexi
```re sig
@@ -709,7 +716,7 @@ Returns `Some(value)` for the first element in the array that satisifies the giv
```re example
// find index of first positive item at an odd index
-let positiveOddElement = (item, index) =>
+let positiveOddElement = (item, index) =>
{(index mod 2 == 1) && (item > 0)};
Js.Array.findIndexi(positiveOddElement, [|66, -33, 55, 88, 22|]) == 3;
@@ -776,7 +783,7 @@ Js.Array.mapi(product, [|10, 11, 12|]) == [|0, 11, 24|];
let reduce: (('b, 'a) => 'b, 'b, t('a)) => 'b;
```
-The `reduce()` function takes three parameters: a *reducer function*, a beginning accumulator value, and an array. The reducer function has two parameters: an accumulated value and an element of the array.
+The `reduce()` function takes three parameters: a _reducer function_, a beginning accumulator value, and an array. The reducer function has two parameters: an accumulated value and an element of the array.
`reduce()` first calls the reducer function with the beginning value and the first element in the array. The result becomes the new accumulator value, which is passed in to the reducer function along with the second element in the array. `reduce()` proceeds through the array, passing in the result of each stage as the accumulator to the reducer function.
@@ -801,7 +808,7 @@ Js.Array.reduce((acc, item) => {item /. acc}, 1.0,
let reducei: (('b, 'a, int) => 'b, 'b, t('a)) => 'b;
```
-The `reducei()` function takes three parameters: a *reducer function*, a beginning accumulator value, and an array. The reducer function has three parameters: an accumulated value, an element of the array, and the index of that element.
+The `reducei()` function takes three parameters: a _reducer function_, a beginning accumulator value, and an array. The reducer function has three parameters: an accumulated value, an element of the array, and the index of that element.
`reducei()` first calls the reducer function with the beginning value, the first element in the array, and zero (its index). The result becomes the new accumulator value, which is passed to the reducer function along with the second element in the array and one (its index). `reducei()` proceeds from left to right through the array, passing in the result of each stage as the accumulator to the reducer function.
@@ -826,11 +833,11 @@ Js.Array.reducei(sumOfEvens, 0, [|2, 5, 1, 4, 3|]) == 6;
let reduceRight: (('b, 'a) => 'b, 'b, t('a)) => 'b;
```
-The `reduceRight()` function takes three parameters: a *reducer function*, a beginning accumulator value, and an array. The reducer function has two parameters: an accumulated value and an element of the array.
+The `reduceRight()` function takes three parameters: a _reducer function_, a beginning accumulator value, and an array. The reducer function has two parameters: an accumulated value and an element of the array.
`reduceRight()` first calls the reducer function with the beginning value and the last element in the array. The result becomes the new accumulator value, which is passed in to the reducer function along with the next-to-last element in the array. `reduceRight()` proceeds from right to left through the array, passing in the result of each stage as the accumulator to the reducer function.
-When all array elements are processed, the final value of the accumulator becomes the return value of `reduceRight()`. See [`Array.reduceRight`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduceRight) on MDN.
+When all array elements are processed, the final value of the accumulator becomes the return value of `reduceRight()`. See [`Array.reduceRight`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduceRight) on MDN.
**NOTE:** In many cases, `reduce()` and `reduceRight()` give the same result. However, see the last example here and compare it to the example from `reduce()`, where order makes a difference.
@@ -850,7 +857,7 @@ Js.Array.reduceRight((acc, item) => {item /. acc}, 1.0,
let reduceRighti: (('b, 'a, int) => 'b, 'b, t('a)) => 'b;
```
-The `reduceRighti()` function takes three parameters: a *reducer function*, a beginning accumulator value, and an array. The reducer function has three parameters: an accumulated value, an element of the array, and the index of that element. `reduceRighti()` first calls the reducer function with the beginning value, the last element in the array, and its index (length of array minus one). The result becomes the new accumulator value, which is passed in to the reducer function along with the second element in the array and one (its index). `reduceRighti()` proceeds from right to left through the array, passing in the result of each stage as the accumulator to the reducer function.
+The `reduceRighti()` function takes three parameters: a _reducer function_, a beginning accumulator value, and an array. The reducer function has three parameters: an accumulated value, an element of the array, and the index of that element. `reduceRighti()` first calls the reducer function with the beginning value, the last element in the array, and its index (length of array minus one). The result becomes the new accumulator value, which is passed in to the reducer function along with the second element in the array and one (its index). `reduceRighti()` proceeds from right to left through the array, passing in the result of each stage as the accumulator to the reducer function.
When all array elements are processed, the final value of the accumulator becomes the return value of `reduceRighti()`. See [`Array.reduceRight`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduceRight) on MDN.
@@ -911,6 +918,7 @@ Js.Array.somei(sameLength, [|"a", "bc", "def", "gh"|]) == false;
```re sig
let unsafe_get: (array('a), int) => 'a;
```
+
Returns the value at the given position in the array if the position is in bounds; returns
the JavaScript value `undefined` otherwise.
@@ -926,7 +934,7 @@ Js.Array.unsafe_get(arr, 4); // returns undefined
let unsafe_set: (array('a), int, 'a) => unit;
```
-Sets the value at the given position in the array if the position is in bounds. If the index is out of bounds, well, “here there be dragons.“ *This function modifies the original array.*
+Sets the value at the given position in the array if the position is in bounds. If the index is out of bounds, well, “here there be dragons.“ _This function modifies the original array._
```re example
let arr = [|100, 101, 102, 103|];
diff --git a/pages/docs/manual/v8.0.0/api/js/console.mdx b/pages/docs/manual/v8.0.0/api/js/console.mdx
index 46fee0bf9..be97d2482 100644
--- a/pages/docs/manual/v8.0.0/api/js/console.mdx
+++ b/pages/docs/manual/v8.0.0/api/js/console.mdx
@@ -6,7 +6,6 @@ Provide console (logging) utilities.
-
## log
```re sig
diff --git a/pages/docs/manual/v8.0.0/api/js/date.mdx b/pages/docs/manual/v8.0.0/api/js/date.mdx
index e8de680bc..1981141fe 100644
--- a/pages/docs/manual/v8.0.0/api/js/date.mdx
+++ b/pages/docs/manual/v8.0.0/api/js/date.mdx
@@ -3,7 +3,8 @@
Provide bindings to JS date. (See [`Date`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) on MDN.) JavaScript stores dates as the number of milliseconds since
-the UNIX *epoch*, midnight 1 January 1970, UTC.
+the UNIX _epoch_, midnight 1 January 1970, UTC.
+
In these examples, we will be using this date:
@@ -17,7 +18,6 @@ The code used to access this date is running in the Europe/Austria time zone wit
In all of these functions, month values are in the range 0-11, where January is month zero.
-
## t
```re sig
@@ -29,6 +29,7 @@ type t;
```re sig
let valueOf: t => float;
```
+
Returns the primitive value of this date, equivalent to `getTime()`. (See [`Date.valueOf`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/valueOf) on MDN.)
```re example
@@ -40,6 +41,7 @@ Js.Date.valueOf(exampleDate) == 123456654321.0;
```re sig
let make: unit => t;
```
+
Returns a date representing the current time. See [`Date()` Constructor](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/Date) on MDN.
```re example
@@ -77,6 +79,7 @@ Js.Date.fromString("Thor, 32 Lok -19 60:70:80 XYZ"); // returns NaN
```re sig
let makeWithYM: (~year: float, ~month: float, unit) => t;
```
+
Returns a date representing midnight of the first day of the given month and year in the current time zone. Fractional parts of arguments are ignored. See [`Date()` Constructor](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/Date) on MDN.
```re example
@@ -88,6 +91,7 @@ let november1 = Js.Date.makeWithYM(~year=2020.0, ~month=10.0, ());
```re sig
let makeWithYMD: (~year: float, ~month: float, ~date: float, unit) => t;
```
+
Returns a date representing midnight of the given date of the given month and year in the current time zone. Fractional parts of arguments are ignored. See [`Date()` Constructor](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/Date) on MDN.
## makeWithYMDH
@@ -95,6 +99,7 @@ Returns a date representing midnight of the given date of the given month and ye
```re sig
let makeWithYMDH: (~year: float, ~month: float, ~date: float, ~hours: float, unit) => t;
```
+
Returns a date representing the given date of the given month and year, at zero minutes and zero seconds past the given `hours`, in the current time zone. Fractional parts of arguments are ignored. See [`Date()` Constructor](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/Date) on MDN. Fractional parts of the arguments are ignored.
## makeWithYMDHM
@@ -102,13 +107,15 @@ Returns a date representing the given date of the given month and year, at zero
```re sig
let makeWithYMDHM: (~year: float, ~month: float, ~date: float, ~hours: float, ~minutes: float, unit) => t;
```
-Returns a date representing the given date of the given month and year, at zero seconds past the given time in hours and minutes in the current time zone. Fractional parts of arguments are ignored. See [`Date()` Constructor](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/Date) on MDN.
+
+Returns a date representing the given date of the given month and year, at zero seconds past the given time in hours and minutes in the current time zone. Fractional parts of arguments are ignored. See [`Date()` Constructor](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/Date) on MDN.
## makeWithYMDHMS
```re sig
let makeWithYMDHMS: (~year: float, ~month: float, ~date: float, ~hours: float, ~minutes: float, ~seconds: float, unit) => t;
```
+
Returns a date representing the given date of the given month and year, at the given time in hours, minutes, and seconds in the current time zone. Fractional parts of arguments are ignored. See [`Date()` Constructor](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/Date) on MDN.
```re example
@@ -121,6 +128,7 @@ Js.Date.makeWithYMDHMS(~year=1973.0, ~month=11.0, ~date=29.0,
```re sig
let utcWithYM: (~year: float, ~month: float, unit) => float;
```
+
Returns a float representing the number of milliseconds past the epoch for midnight of the first day of the given month and year in UTC. Fractional parts of arguments are ignored. See [`Date.UTC`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/UTC) on MDN.
```re example
@@ -132,6 +140,7 @@ let november1 = Js.Date.utcWithYM(~year=2020.0, ~month=10.0, ());
```re sig
let utcWithYMD: (~year: float, ~month: float, ~date: float, unit) => float;
```
+
Returns a float representing the number of milliseconds past the epoch for midnight of the given date of the given month and year in UTC. Fractional parts of arguments are ignored. See [`Date.UTC`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/UTC) on MDN.
## utcWithYMDH
@@ -139,6 +148,7 @@ Returns a float representing the number of milliseconds past the epoch for midni
```re sig
let utcWithYMDH: (~year: float, ~month: float, ~date: float, ~hours: float, unit) => float;
```
+
Returns a float representing the number of milliseconds past the epoch for midnight of the given date of the given month and year, at zero minutes and seconds past the given hours in UTC. Fractional parts of arguments are ignored. See [`Date.UTC`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/UTC) on MDN.
## utcWithYMDHM
@@ -146,6 +156,7 @@ Returns a float representing the number of milliseconds past the epoch for midni
```re sig
let utcWithYMDHM: (~year: float, ~month: float, ~date: float, ~hours: float, ~minutes: float, unit) => float;
```
+
Returns a float representing the number of milliseconds past the epoch for midnight of the given date of the given month and year, at zero seconds past the given number of minutes past the given hours in UTC. Fractional parts of arguments are ignored. See [`Date.UTC`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/UTC) on MDN.
## utcWithYMDHMS
@@ -153,6 +164,7 @@ Returns a float representing the number of milliseconds past the epoch for midni
```re sig
let utcWithYMDHMS: (~year: float, ~month: float, ~date: float, ~hours: float, ~minutes: float, ~seconds: float, unit) => float;
```
+
Returns a float representing the number of milliseconds past the epoch for midnight of the given date of the given month and year, at the given time in hours, minutes and seconds in UTC. Fractional parts of arguments are ignored. See [`Date.UTC`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/UTC) on MDN.
## now
@@ -160,6 +172,7 @@ Returns a float representing the number of milliseconds past the epoch for midni
```re sig
let now: unit => float;
```
+
Returns the current time as number of milliseconds since Unix epoch.
## parse
@@ -167,6 +180,7 @@ Returns the current time as number of milliseconds since Unix epoch.
```re sig
let parse: string => t;
```
+
Deprecated. Use [`fromString()`](#fromstring).
## parseAsFloat
@@ -174,6 +188,7 @@ Deprecated. Use [`fromString()`](#fromstring).
```re sig
let parseAsFloat: string => float;
```
+
Returns a float with the number of milliseconds past the epoch represented by the given string. The string can be in “IETF-compliant RFC 2822 timestamps, and also strings in a version of ISO8601.” Returns `NaN` if given an invalid date string. According to the [`Date.parse`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse) documentation on MDN, its use is discouraged. Returns `NaN` if passed invalid date string.
## getDate
@@ -181,6 +196,7 @@ Returns a float with the number of milliseconds past the epoch represented by th
```re sig
let getDate: t => float;
```
+
Returns the day of the month for its argument. The argument is evaluated in the current time zone. See [`Date.getDate`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getDate) on MDN.
```re example
@@ -192,7 +208,8 @@ Js.Date.getDate(exampleDate) == 29.0;
```re sig
let getDay: t => float;
```
-Returns the day of the week (0.0-6.0) for its argument, where 0.0 represents Sunday. The argument is evaluated in the current time zone. See [`Date.getDay`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getDay) on MDN.
+
+Returns the day of the week (0.0-6.0) for its argument, where 0.0 represents Sunday. The argument is evaluated in the current time zone. See [`Date.getDay`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getDay) on MDN.
```re example
Js.Date.getDay(exampleDate) == 4.0;
@@ -203,6 +220,7 @@ Js.Date.getDay(exampleDate) == 4.0;
```re sig
let getFullYear: t => float;
```
+
Returns the full year (as opposed to the range 0-99) for its argument. The argument is evaluated in the current time zone. See [`Date.getFullYear`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getFullYear) on MDN.
```re example
@@ -214,6 +232,7 @@ Js.Date.getFullYear(exampleDate) == 1973.0;
```re sig
let getHours: t => float;
```
+
Returns the hours for its argument, evaluated in the current time zone. See [`Date.getHours`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getHours) on MDN.
```re example
@@ -225,6 +244,7 @@ Js.Date.getHours(exampleDate) == 22.0; // Vienna is in GMT+01:00
```re sig
let getMilliseconds: t => float;
```
+
Returns the number of milliseconds for its argument, evaluated in the current time zone. See [`Date.getMilliseconds`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getMilliseconds) on MDN.
```re example
@@ -236,6 +256,7 @@ Js.Date.getMilliseconds(exampleDate) == 321.0;
```re sig
let getMinutes: t => float;
```
+
Returns the number of minutes for its argument, evaluated in the current time zone. See [`Date.getMinutes`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getMinutes) on MDN.
```re example
@@ -247,7 +268,8 @@ Js.Date.getMinutes(exampleDate) == 30.0;
```re sig
let getMonth: t => float;
```
-Returns the month (0.0-11.0) for its argument, evaluated in the current time zone. January is month zero. See [`Date.getMonth`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getMonth) on MDN.
+
+Returns the month (0.0-11.0) for its argument, evaluated in the current time zone. January is month zero. See [`Date.getMonth`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getMonth) on MDN.
```re example
Js.Date.getMonth(exampleDate) == 10.0;
@@ -258,6 +280,7 @@ Js.Date.getMonth(exampleDate) == 10.0;
```re sig
let getSeconds: t => float;
```
+
Returns the seconds for its argument, evaluated in the current time zone. See [`Date.getSeconds`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getSeconds) on MDN.
```re example
@@ -269,7 +292,8 @@ Js.Date.getSeconds(exampleDate) == 54.0;
```re sig
let getTime: t => float;
```
-Returns the number of milliseconds since Unix epoch, evaluated in UTC. See [`Date.getTime`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getTime) on MDN.
+
+Returns the number of milliseconds since Unix epoch, evaluated in UTC. See [`Date.getTime`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getTime) on MDN.
```re example
Js.Date.getTime(exampleDate) == 123456654321.0
@@ -292,6 +316,7 @@ Js.Date.getTimezoneOffset(exampleDate) == -60.0;
```re sig
let getUTCDate: t => float;
```
+
Returns the day of the month of the argument, evaluated in UTC. See [`Date.getUTCDate`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getUTCDate) on MDN.
```re example
@@ -303,6 +328,7 @@ Js.Date.getUTCDate(exampleDate) == 29.0;
```re sig
let getUTCDay: t => float;
```
+
Returns the day of the week of the argument, evaluated in UTC. The range of the return value is 0.0-6.0, where Sunday is zero. See [`Date.getUTCDay`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getUTCDay) on MDN.
```re example
@@ -314,7 +340,8 @@ Js.Date.getUTCDay(exampleDate) == 4.0;
```re sig
let getUTCFullYear: t => float;
```
-Returns the full year (as opposed to the range 0-99) for its argument. The argument is evaluated in UTC. See [`Date.getUTCFullYear`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getUTCFullYear) on MDN.
+
+Returns the full year (as opposed to the range 0-99) for its argument. The argument is evaluated in UTC. See [`Date.getUTCFullYear`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getUTCFullYear) on MDN.
```re example
Js.Date.getUTCFullYear(exampleDate) == 1973.0;
@@ -325,6 +352,7 @@ Js.Date.getUTCFullYear(exampleDate) == 1973.0;
```re sig
let getUTCHours: t => float;
```
+
Returns the hours for its argument, evaluated in the current time zone. See [`Date.getUTCHours`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getUTCHours) on MDN.
```re example
@@ -336,6 +364,7 @@ Js.Date.getUTCHours(exampleDate) == 21.0;
```re sig
let getUTCMilliseconds: t => float;
```
+
Returns the number of milliseconds for its argument, evaluated in UTC. See [`Date.getUTCMilliseconds`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getUTCMilliseconds) on MDN.
```re example
@@ -347,6 +376,7 @@ Js.Date.getUTCMilliseconds(exampleDate) == 321.0;
```re sig
let getUTCMinutes: t => float;
```
+
Returns the number of minutes for its argument, evaluated in UTC. See [`Date.getUTCMinutes`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getUTCMinutes) on MDN.
```re example
@@ -358,6 +388,7 @@ Js.Date.getUTCMinutes(exampleDate) == 30.0;
```re sig
let getUTCMonth: t => float;
```
+
Returns the month (0.0-11.0) for its argument, evaluated in UTC. January is month zero. See [`Date.getUTCMonth`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getUTCMonth) on MDN.
```re example
@@ -369,6 +400,7 @@ Js.Date.getUTCMonth(exampleDate) == 10.0;
```re sig
let getUTCSeconds: t => float;
```
+
Returns the seconds for its argument, evaluated in UTC. See [`Date.getUTCSeconds`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getUTCSeconds) on MDN.
```re example
@@ -380,6 +412,7 @@ Js.Date.getUTCSeconds(exampleDate) == 54.0;
```re sig
let getYear: t => float;
```
+
Deprecated. Use `getFullYear()` instead.
## setDate
@@ -387,7 +420,8 @@ Deprecated. Use `getFullYear()` instead.
```re sig
let setDate: (t, float) => float;
```
-Sets the given `Date`’s day of month to the value in the second argument according to the current time zone. Returns the number of milliseconds since the epoch of the updated `Date`. *This function modifies the original `Date`.* See [`Date.setDate`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setDate) on MDN.
+
+Sets the given `Date`’s day of month to the value in the second argument according to the current time zone. Returns the number of milliseconds since the epoch of the updated `Date`. _This function modifies the original `Date`._ See [`Date.setDate`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setDate) on MDN.
```re example
let date1 = Js.Date.fromFloat(123456654321.0); // 29 November 1973 21:30:54.321 GMT
@@ -401,7 +435,8 @@ twoWeeksBefore == Js.Date.getTime(date1);
```re sig
let setFullYear: (t, float) => float;
```
-Sets the given `Date`’s year to the value in the second argument according to the current time zone. Returns the number of milliseconds since the epoch of the updated `Date`. *This function modifies the original `Date`.* See [`Date.setFullYear`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setFullYear) on MDN.
+
+Sets the given `Date`’s year to the value in the second argument according to the current time zone. Returns the number of milliseconds since the epoch of the updated `Date`. _This function modifies the original `Date`._ See [`Date.setFullYear`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setFullYear) on MDN.
```re example
let date1 = Js.Date.fromFloat(123456654321.0); // 29 November 1973 21:30:54.321 GMT
@@ -416,7 +451,7 @@ nextYear == Js.Date.getTime(date1);
let setFullYearM: (t, ~year: float, ~month: float, unit) => float;
```
-Sets the given `Date`’s year and month to the values in the labeled arguments according to the current time zone. Returns the number of milliseconds since the epoch of the updated `Date`. *This function modifies the original `Date`.* See [`Date.setFullYear`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setFullYear) on MDN.
+Sets the given `Date`’s year and month to the values in the labeled arguments according to the current time zone. Returns the number of milliseconds since the epoch of the updated `Date`. _This function modifies the original `Date`._ See [`Date.setFullYear`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setFullYear) on MDN.
```re example
let date1 = Js.Date.fromFloat(123456654321.0); // 29 November 1973 21:30:54.321 GMT
@@ -430,7 +465,8 @@ future == Js.Date.getTime(date1);
```re sig
let setFullYearMD: (t, ~year: float, ~month: float, ~date: float, unit) => float;
```
-Sets the given `Date`’s year, month, and day of month to the values in the labeled arguments according to the current time zone. Returns the number of milliseconds since the epoch of the updated `Date`. *This function modifies the original `Date`.* See [`Date.setFullYear`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setFullYear) on MDN.
+
+Sets the given `Date`’s year, month, and day of month to the values in the labeled arguments according to the current time zone. Returns the number of milliseconds since the epoch of the updated `Date`. _This function modifies the original `Date`._ See [`Date.setFullYear`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setFullYear) on MDN.
```re example
let date1 = Js.Date.fromFloat(123456654321.0); // 29 November 1973 21:30:54.321 GMT
@@ -444,7 +480,8 @@ future == Js.Date.getTime(date1);
```re sig
let setHours: (t, float) => float;
```
-Sets the given `Date`’s hours to the value in the second argument according to the current time zone. Returns the number of milliseconds since the epoch of the updated `Date`. *This function modifies the original `Date`.* See [`Date.setHours`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setHours) on MDN.
+
+Sets the given `Date`’s hours to the value in the second argument according to the current time zone. Returns the number of milliseconds since the epoch of the updated `Date`. _This function modifies the original `Date`._ See [`Date.setHours`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setHours) on MDN.
```re example
let date1 = Js.Date.fromFloat(123456654321.0); // 29 November 1973 21:30:54.321 GMT
@@ -458,7 +495,8 @@ nextHour == Js.Date.getTime(date1);
```re sig
let setHoursM: (t, ~hours: float, ~minutes: float, unit) => float;
```
-Sets the given `Date`’s hours and minutes to the values in the labeled arguments according to the current time zone. Returns the number of milliseconds since the epoch of the updated `Date`. *This function modifies the original `Date`.* See [`Date.setHours`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setHours) on MDN.
+
+Sets the given `Date`’s hours and minutes to the values in the labeled arguments according to the current time zone. Returns the number of milliseconds since the epoch of the updated `Date`. _This function modifies the original `Date`._ See [`Date.setHours`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setHours) on MDN.
```re example
let date1 = Js.Date.fromFloat(123456654321.0); // 29 November 1973 21:30:54.321 GMT
@@ -472,11 +510,12 @@ futureTime == Js.Date.getTime(date1);
```re sig
let setHoursMS: (t, ~hours: float, ~minutes: float, ~seconds: float, unit) => float;
```
-Sets the given `Date`’s hours, minutes, and seconds to the values in the labeled arguments according to the current time zone. Returns the number of milliseconds since the epoch of the updated `Date`. *This function modifies the original `Date`.* See [`Date.setHours`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setHours) on MDN.
+
+Sets the given `Date`’s hours, minutes, and seconds to the values in the labeled arguments according to the current time zone. Returns the number of milliseconds since the epoch of the updated `Date`. _This function modifies the original `Date`._ See [`Date.setHours`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setHours) on MDN.
```re example
let date1 = Js.Date.fromFloat(123456654321.0); // 29 November 1973 21:30:54.321 GMT
-let futureTime = Js.Date.setHoursMS(date1, ~hours=22.0, ~minutes=46.0,
+let futureTime = Js.Date.setHoursMS(date1, ~hours=22.0, ~minutes=46.0,
~seconds=37.0, ());
date1 == Js.Date.fromString("1973-11-29T22:46:37.321Z00:00");
futureTime == Js.Date.getTime(date1);
@@ -487,11 +526,12 @@ futureTime == Js.Date.getTime(date1);
```re sig
let setHoursMSMs: (t, ~hours: float, ~minutes: float, ~seconds: float, ~milliseconds: float, unit) => float;
```
-Sets the given `Date`’s hours, minutes, seconds, and milliseconds to the values in the labeled arguments according to the current time zone. Returns the number of milliseconds since the epoch of the updated `Date`. *This function modifies the original `Date`.* See [`Date.setHours`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setHours) on MDN.
+
+Sets the given `Date`’s hours, minutes, seconds, and milliseconds to the values in the labeled arguments according to the current time zone. Returns the number of milliseconds since the epoch of the updated `Date`. _This function modifies the original `Date`._ See [`Date.setHours`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setHours) on MDN.
```re example
let date1 = Js.Date.fromFloat(123456654321.0); // 29 November 1973 21:30:54.321 GMT
-let futureTime = Js.Date.setHoursMSMs(date1, ~hours=22.0, ~minutes=46.0,
+let futureTime = Js.Date.setHoursMSMs(date1, ~hours=22.0, ~minutes=46.0,
~seconds=37.0, ~milliseconds=494.0, ());
date1 == Js.Date.fromString("1973-11-29T22:46:37.494Z00:00");
futureTime == Js.Date.getTime(date1);
@@ -502,7 +542,8 @@ futureTime == Js.Date.getTime(date1);
```re sig
let setMilliseconds: (t, float) => float;
```
-Sets the given `Date`’s milliseconds to the value in the second argument according to the current time zone. Returns the number of milliseconds since the epoch of the updated `Date`. *This function modifies the original `Date`.* See [`Date.setMilliseconds`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setMilliseconds) on MDN.
+
+Sets the given `Date`’s milliseconds to the value in the second argument according to the current time zone. Returns the number of milliseconds since the epoch of the updated `Date`. _This function modifies the original `Date`._ See [`Date.setMilliseconds`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setMilliseconds) on MDN.
```re example
let date1 = Js.Date.fromFloat(123456654321.0); // 29 November 1973 21:30:54.321 GMT
@@ -516,7 +557,8 @@ futureTime == Js.Date.getTime(date1);
```re sig
let setMinutes: (t, float) => float;
```
-Sets the given `Date`’s minutes to the value in the second argument according to the current time zone. Returns the number of milliseconds since the epoch of the updated `Date`. *This function modifies the original `Date`.* See [`Date.setMinutes`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setMinutes) on MDN.
+
+Sets the given `Date`’s minutes to the value in the second argument according to the current time zone. Returns the number of milliseconds since the epoch of the updated `Date`. _This function modifies the original `Date`._ See [`Date.setMinutes`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setMinutes) on MDN.
```re example
let date1 = Js.Date.fromFloat(123456654321.0); // 29 November 1973 21:30:54.321 GMT
@@ -530,7 +572,8 @@ futureTime == Js.Date.getTime(date1);
```re sig
let setMinutesS: (t, ~minutes: float, ~seconds: float, unit) => float;
```
-Sets the given `Date`’s minutes and seconds to the values in the labeled arguments according to the current time zone. Returns the number of milliseconds since the epoch of the updated `Date`. *This function modifies the original `Date`.* See [`Date.setMinutes`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setMinutes) on MDN.
+
+Sets the given `Date`’s minutes and seconds to the values in the labeled arguments according to the current time zone. Returns the number of milliseconds since the epoch of the updated `Date`. _This function modifies the original `Date`._ See [`Date.setMinutes`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setMinutes) on MDN.
```re example
let date1 = Js.Date.fromFloat(123456654321.0); // 29 November 1973 21:30:54.321 GMT
@@ -544,7 +587,8 @@ futureTime == Js.Date.getTime(date1);
```re sig
let setMinutesSMs: (t, ~minutes: float, ~seconds: float, ~milliseconds: float, unit) => float;
```
-Sets the given `Date`’s minutes, seconds, and milliseconds to the values in the labeled arguments according to the current time zone. Returns the number of milliseconds since the epoch of the updated `Date`. *This function modifies the original `Date`.* See [`Date.setMinutes`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setMinutes) on MDN.
+
+Sets the given `Date`’s minutes, seconds, and milliseconds to the values in the labeled arguments according to the current time zone. Returns the number of milliseconds since the epoch of the updated `Date`. _This function modifies the original `Date`._ See [`Date.setMinutes`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setMinutes) on MDN.
```re example
let date1 = Js.Date.fromFloat(123456654321.0); // 29 November 1973 21:30:54.321 GMT
@@ -559,7 +603,8 @@ futureTime == Js.Date.getTime(date1);
```re sig
let setMonth: (t, float) => float;
```
-Sets the given `Date`’s month to the value in the second argument according to the current time zone. Returns the number of milliseconds since the epoch of the updated `Date`. *This function modifies the original `Date`.* See [`Date.setMonth`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setMonth) on MDN.
+
+Sets the given `Date`’s month to the value in the second argument according to the current time zone. Returns the number of milliseconds since the epoch of the updated `Date`. _This function modifies the original `Date`._ See [`Date.setMonth`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setMonth) on MDN.
```re example
let date1 = Js.Date.fromFloat(123456654321.0); // 29 November 1973 21:30:54.321 GMT
@@ -573,7 +618,8 @@ futureTime == Js.Date.getTime(date1);
```re sig
let setMonthD: (t, ~month: float, ~date: float, unit) => float;
```
-Sets the given `Date`’s month and day of month to the values in the labeled arguments according to the current time zone. Returns the number of milliseconds since the epoch of the updated `Date`. *This function modifies the original `Date`.* See [`Date.setMonth`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setMonth) on MDN.
+
+Sets the given `Date`’s month and day of month to the values in the labeled arguments according to the current time zone. Returns the number of milliseconds since the epoch of the updated `Date`. _This function modifies the original `Date`._ See [`Date.setMonth`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setMonth) on MDN.
```re example
let date1 = Js.Date.fromFloat(123456654321.0); // 29 November 1973 21:30:54.321 GMT
@@ -587,7 +633,8 @@ futureTime == Js.Date.getTime(date1);
```re sig
let setSeconds: (t, float) => float;
```
-Sets the given `Date`’s seconds to the value in the second argument according to the current time zone. Returns the number of milliseconds since the epoch of the updated `Date`. *This function modifies the original `Date`.* See [`Date.setSeconds`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setSeconds) on MDN.
+
+Sets the given `Date`’s seconds to the value in the second argument according to the current time zone. Returns the number of milliseconds since the epoch of the updated `Date`. _This function modifies the original `Date`._ See [`Date.setSeconds`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setSeconds) on MDN.
```re example
let date1 = Js.Date.fromFloat(123456654321.0); // 29 November 1973 21:30:54.321 GMT
@@ -601,7 +648,8 @@ futureTime == Js.Date.getTime(date1);
```re sig
let setSecondsMs: (t, ~seconds: float, ~milliseconds: float, unit) => float;
```
-Sets the given `Date`’s seconds and milliseconds to the values in the labeled arguments according to the current time zone. Returns the number of milliseconds since the epoch of the updated `Date`. *This function modifies the original `Date`.* See [`Date.setSeconds`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setSeconds) on MDN.
+
+Sets the given `Date`’s seconds and milliseconds to the values in the labeled arguments according to the current time zone. Returns the number of milliseconds since the epoch of the updated `Date`. _This function modifies the original `Date`._ See [`Date.setSeconds`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setSeconds) on MDN.
```re example
let date1 = Js.Date.fromFloat(123456654321.0); // 29 November 1973 21:30:54.321 GMT
@@ -616,7 +664,8 @@ futureTime == Js.Date.getTime(date1);
```re sig
let setTime: (t, float) => float;
```
-Sets the given `Date`’s value in terms of milliseconds since the epoch. Returns the number of milliseconds since the epoch of the updated `Date`. *This function modifies the original `Date`.* See [`Date.setTime`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setTime) on MDN.
+
+Sets the given `Date`’s value in terms of milliseconds since the epoch. Returns the number of milliseconds since the epoch of the updated `Date`. _This function modifies the original `Date`._ See [`Date.setTime`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setTime) on MDN.
```re example
let date1 = Js.Date.fromFloat(123456654321.0); // 29 November 1973 21:30:54.321 GMT
@@ -631,7 +680,8 @@ futureTime == Js.Date.getTime(date1);
```re sig
let setUTCDate: (t, float) => float;
```
-Sets the given `Date`’s day of month to the value in the second argument according to UTC. Returns the number of milliseconds since the epoch of the updated `Date`. *This function modifies the original `Date`.* See [`Date.setUTCDate`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setUTCDate) on MDN.
+
+Sets the given `Date`’s day of month to the value in the second argument according to UTC. Returns the number of milliseconds since the epoch of the updated `Date`. _This function modifies the original `Date`._ See [`Date.setUTCDate`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setUTCDate) on MDN.
```re example
let date1 = Js.Date.fromFloat(123456654321.0); // 29 November 1973 21:30:54.321 GMT
@@ -645,7 +695,8 @@ twoWeeksBefore == Js.Date.getTime(date1);
```re sig
let setUTCFullYear: (t, float) => float;
```
-Sets the given `Date`’s year to the value in the second argument according to UTC. Returns the number of milliseconds since the epoch of the updated `Date`. *This function modifies the original `Date`.* See [`Date.setUTCFullYear`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setUTCFullYear) on MDN.
+
+Sets the given `Date`’s year to the value in the second argument according to UTC. Returns the number of milliseconds since the epoch of the updated `Date`. _This function modifies the original `Date`._ See [`Date.setUTCFullYear`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setUTCFullYear) on MDN.
```re example
let date1 = Js.Date.fromFloat(123456654321.0); // 29 November 1973 21:30:54.321 GMT
@@ -659,7 +710,8 @@ nextYear == Js.Date.getTime(date1);
```re sig
let setUTCFullYearM: (t, ~year: float, ~month: float, unit) => float;
```
-Sets the given `Date`’s year and month to the values in the labeled arguments according to UTC. Returns the number of milliseconds since the epoch of the updated `Date`. *This function modifies the original `Date`.* See [`Date.setUTCFullYear`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setUTCFullYear) on MDN.
+
+Sets the given `Date`’s year and month to the values in the labeled arguments according to UTC. Returns the number of milliseconds since the epoch of the updated `Date`. _This function modifies the original `Date`._ See [`Date.setUTCFullYear`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setUTCFullYear) on MDN.
```re example
let date1 = Js.Date.fromFloat(123456654321.0); // 29 November 1973 21:30:54.321 GMT
@@ -673,7 +725,8 @@ future == Js.Date.getTime(date1);
```re sig
let setUTCFullYearMD: (t, ~year: float, ~month: float, ~date: float, unit) => float;
```
-Sets the given `Date`’s year, month, and day of month to the values in the labeled arguments according to UTC. Returns the number of milliseconds since the epoch of the updated `Date`. *This function modifies the original `Date`.* See [`Date.setUTCFullYear`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setUTCFullYear) on MDN.
+
+Sets the given `Date`’s year, month, and day of month to the values in the labeled arguments according to UTC. Returns the number of milliseconds since the epoch of the updated `Date`. _This function modifies the original `Date`._ See [`Date.setUTCFullYear`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setUTCFullYear) on MDN.
```re example
let date1 = Js.Date.fromFloat(123456654321.0); // 29 November 1973 21:30:54.321 GMT
@@ -687,7 +740,8 @@ future == Js.Date.getTime(date1);
```re sig
let setUTCHours: (t, float) => float;
```
-Sets the given `Date`’s hours to the value in the second argument according to UTC. Returns the number of milliseconds since the epoch of the updated `Date`. *This function modifies the original `Date`.* See [`Date.setUTCHours`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setUTCHours) on MDN.
+
+Sets the given `Date`’s hours to the value in the second argument according to UTC. Returns the number of milliseconds since the epoch of the updated `Date`. _This function modifies the original `Date`._ See [`Date.setUTCHours`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setUTCHours) on MDN.
```re example
let date1 = Js.Date.fromFloat(123456654321.0); // 29 November 1973 21:30:54.321 GMT
@@ -701,7 +755,8 @@ nextHour == Js.Date.getTime(date1);
```re sig
let setUTCHoursM: (t, ~hours: float, ~minutes: float, unit) => float;
```
-Sets the given `Date`’s hours and minutes to the values in the labeled arguments according to UTC. Returns the number of milliseconds since the epoch of the updated `Date`. *This function modifies the original `Date`.* See [`Date.setUTCHours`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setUTCHours) on MDN.
+
+Sets the given `Date`’s hours and minutes to the values in the labeled arguments according to UTC. Returns the number of milliseconds since the epoch of the updated `Date`. _This function modifies the original `Date`._ See [`Date.setUTCHours`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setUTCHours) on MDN.
```re example
let date1 = Js.Date.fromFloat(123456654321.0); // 29 November 1973 21:30:54.321 GMT
@@ -715,11 +770,12 @@ futureTime == Js.Date.getTime(date1);
```re sig
let setUTCHoursMS: (t, ~hours: float, ~minutes: float, ~seconds: float, unit) => float;
```
-Sets the given `Date`’s hours, minutes, and seconds to the values in the labeled arguments according to UTC. Returns the number of milliseconds since the epoch of the updated `Date`. *This function modifies the original `Date`.* See [`Date.setUTCHours`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setUTCHours) on MDN.
+
+Sets the given `Date`’s hours, minutes, and seconds to the values in the labeled arguments according to UTC. Returns the number of milliseconds since the epoch of the updated `Date`. _This function modifies the original `Date`._ See [`Date.setUTCHours`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setUTCHours) on MDN.
```re example
let date1 = Js.Date.fromFloat(123456654321.0); // 29 November 1973 21:30:54.321 GMT
-let futureTime = Js.Date.setUTCHoursMS(date1, ~hours=22.0, ~minutes=46.0,
+let futureTime = Js.Date.setUTCHoursMS(date1, ~hours=22.0, ~minutes=46.0,
~seconds=37.0, ());
date1 == Js.Date.fromString("1973-11-29T22:46:37.321Z00:00");
futureTime == Js.Date.getTime(date1);
@@ -730,11 +786,12 @@ futureTime == Js.Date.getTime(date1);
```re sig
let setUTCHoursMSMs: (t, ~hours: float, ~minutes: float, ~seconds: float, ~milliseconds: float, unit) => float;
```
-Sets the given `Date`’s hours, minutes, seconds, and milliseconds to the values in the labeled arguments according to UTC. Returns the number of milliseconds since the epoch of the updated `Date`. *This function modifies the original `Date`.* See [`Date.setUTCHours`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setUTCHours) on MDN.
+
+Sets the given `Date`’s hours, minutes, seconds, and milliseconds to the values in the labeled arguments according to UTC. Returns the number of milliseconds since the epoch of the updated `Date`. _This function modifies the original `Date`._ See [`Date.setUTCHours`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setUTCHours) on MDN.
```re example
let date1 = Js.Date.fromFloat(123456654321.0); // 29 November 1973 21:30:54.321 GMT
-let futureTime = Js.Date.setUTCHoursMSMs(date1, ~hours=22.0, ~minutes=46.0,
+let futureTime = Js.Date.setUTCHoursMSMs(date1, ~hours=22.0, ~minutes=46.0,
~seconds=37.0, ~milliseconds=494.0, ());
date1 == Js.Date.fromString("1973-11-29T22:46:37.494Z00:00");
futureTime == Js.Date.getTime(date1);
@@ -745,7 +802,8 @@ futureTime == Js.Date.getTime(date1);
```re sig
let setUTCMilliseconds: (t, float) => float;
```
-Sets the given `Date`’s milliseconds to the value in the second argument according to UTC. Returns the number of milliseconds since the epoch of the updated `Date`. *This function modifies the original `Date`.* See [`Date.setUTCMilliseconds`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setUTCMilliseconds) on MDN.
+
+Sets the given `Date`’s milliseconds to the value in the second argument according to UTC. Returns the number of milliseconds since the epoch of the updated `Date`. _This function modifies the original `Date`._ See [`Date.setUTCMilliseconds`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setUTCMilliseconds) on MDN.
```re example
let date1 = Js.Date.fromFloat(123456654321.0); // 29 November 1973 21:30:54.321 GMT
@@ -759,7 +817,8 @@ futureTime == Js.Date.getTime(date1);
```re sig
let setUTCMinutes: (t, float) => float;
```
-Sets the given `Date`’s minutes to the value in the second argument according to the current time zone. Returns the number of milliseconds since the epoch of the updated `Date`. *This function modifies the original `Date`.* See [`Date.setUTCMinutes`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setUTCMinutes) on MDN.
+
+Sets the given `Date`’s minutes to the value in the second argument according to the current time zone. Returns the number of milliseconds since the epoch of the updated `Date`. _This function modifies the original `Date`._ See [`Date.setUTCMinutes`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setUTCMinutes) on MDN.
```re example
let date1 = Js.Date.fromFloat(123456654321.0); // 29 November 1973 21:30:54.321 GMT
@@ -773,7 +832,8 @@ futureTime == Js.Date.getTime(date1);
```re sig
let setUTCMinutesS: (t, ~minutes: float, ~seconds: float, unit) => float;
```
-Sets the given `Date`’s minutes and seconds to the values in the labeled arguments according to UTC. Returns the number of milliseconds since the epoch of the updated `Date`. *This function modifies the original `Date`.* See [`Date.setUTCMinutes`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setUTCMinutes) on MDN.
+
+Sets the given `Date`’s minutes and seconds to the values in the labeled arguments according to UTC. Returns the number of milliseconds since the epoch of the updated `Date`. _This function modifies the original `Date`._ See [`Date.setUTCMinutes`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setUTCMinutes) on MDN.
```re example
let date1 = Js.Date.fromFloat(123456654321.0); // 29 November 1973 21:30:54.321 GMT
@@ -787,7 +847,8 @@ futureTime == Js.Date.getTime(date1);
```re sig
let setUTCMinutesSMs: (t, ~minutes: float, ~seconds: float, ~milliseconds: float, unit) => float;
```
-Sets the given `Date`’s minutes, seconds, and milliseconds to the values in the labeled arguments according to UTC. Returns the number of milliseconds since the epoch of the updated `Date`. *This function modifies the original `Date`.* See [`Date.setUTCMinutes`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setUTCMinutes) on MDN.
+
+Sets the given `Date`’s minutes, seconds, and milliseconds to the values in the labeled arguments according to UTC. Returns the number of milliseconds since the epoch of the updated `Date`. _This function modifies the original `Date`._ See [`Date.setUTCMinutes`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setUTCMinutes) on MDN.
```re example
let date1 = Js.Date.fromFloat(123456654321.0); // 29 November 1973 21:30:54.321 GMT
@@ -802,7 +863,8 @@ futureTime == Js.Date.getTime(date1);
```re sig
let setUTCMonth: (t, float) => float;
```
-Sets the given `Date`’s month to the value in the second argument according to UTC. Returns the number of milliseconds since the epoch of the updated `Date`. *This function modifies the original `Date`.* See [`Date.setUTCMonth`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setUTCMonth) on MDN.
+
+Sets the given `Date`’s month to the value in the second argument according to UTC. Returns the number of milliseconds since the epoch of the updated `Date`. _This function modifies the original `Date`._ See [`Date.setUTCMonth`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setUTCMonth) on MDN.
```re example
let date1 = Js.Date.fromFloat(123456654321.0); // 29 November 1973 21:30:54.321 GMT
@@ -816,7 +878,8 @@ futureTime == Js.Date.getTime(date1);
```re sig
let setUTCMonthD: (t, ~month: float, ~date: float, unit) => float;
```
-Sets the given `Date`’s month and day of month to the values in the labeled arguments according to UTC. Returns the number of milliseconds since the epoch of the updated `Date`. *This function modifies the original `Date`.* See [`Date.setUTCMonth`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setUTCMonth) on MDN.
+
+Sets the given `Date`’s month and day of month to the values in the labeled arguments according to UTC. Returns the number of milliseconds since the epoch of the updated `Date`. _This function modifies the original `Date`._ See [`Date.setUTCMonth`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setUTCMonth) on MDN.
```re example
let date1 = Js.Date.fromFloat(123456654321.0); // 29 November 1973 21:30:54.321 GMT
@@ -830,7 +893,8 @@ futureTime == Js.Date.getTime(date1);
```re sig
let setUTCSeconds: (t, float) => float;
```
-Sets the given `Date`’s seconds to the value in the second argument according to UTC. Returns the number of milliseconds since the epoch of the updated `Date`. *This function modifies the original `Date`.* See [`Date.setUTCSeconds`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setUTCSeconds) on MDN.
+
+Sets the given `Date`’s seconds to the value in the second argument according to UTC. Returns the number of milliseconds since the epoch of the updated `Date`. _This function modifies the original `Date`._ See [`Date.setUTCSeconds`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setUTCSeconds) on MDN.
```re example
let date1 = Js.Date.fromFloat(123456654321.0); // 29 November 1973 21:30:54.321 GMT
@@ -844,7 +908,8 @@ futureTime == Js.Date.getTime(date1);
```re sig
let setUTCSecondsMs: (t, ~seconds: float, ~milliseconds: float, unit) => float;
```
-Sets the given `Date`’s seconds and milliseconds to the values in the labeled arguments according to UTC. Returns the number of milliseconds since the epoch of the updated `Date`. *This function modifies the original `Date`.* See [`Date.setUTCSeconds`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setUTCSeconds) on MDN.
+
+Sets the given `Date`’s seconds and milliseconds to the values in the labeled arguments according to UTC. Returns the number of milliseconds since the epoch of the updated `Date`. _This function modifies the original `Date`._ See [`Date.setUTCSeconds`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setUTCSeconds) on MDN.
```re example
let date1 = Js.Date.fromFloat(123456654321.0); // 29 November 1973 21:30:54.321 GMT
@@ -859,6 +924,7 @@ futureTime == Js.Date.getTime(date1);
```re sig
let setUTCTime: (t, float) => float;
```
+
Same as [`setTime()`](#settime).
## setYear
@@ -866,6 +932,7 @@ Same as [`setTime()`](#settime).
```re sig
let setYear: (t, float) => float;
```
+
Deprecated. Use [`setFullYear()`](#setfullyear) instead.
## toDateString
@@ -873,6 +940,7 @@ Deprecated. Use [`setFullYear()`](#setfullyear) instead.
```re sig
let toDateString: t => string;
```
+
Returns the date (day of week, year, month, and day of month) portion of a `Date` in English. See [`Date.toDateString`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toDateString) on MDN.
```re example
@@ -884,6 +952,7 @@ Js.Date.toDateString(exampleDate) == "Thu Nov 29 1973";
```re sig
let toGMTString: t => string;
```
+
Deprecated. Use [`toUTCString()`](#toutcstring) instead.
## toISOString
@@ -891,6 +960,7 @@ Deprecated. Use [`toUTCString()`](#toutcstring) instead.
```re sig
let toISOString: t => string;
```
+
Returns a simplified version of the ISO 8601 format for the date. See [`Date.toISOString`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString) on MDN.
```re example
@@ -902,6 +972,7 @@ Js.Date.toISOString(exampleDate) == "1973-11-29T21:30:54.321Z";
```re sig
let toJSON: t => string;
```
+
Deprecated. This method is unsafe. It will be changed to return `option` in a future release. Please use `toJSONUnsafe()` instead.
## toJSONUnsafe
@@ -909,6 +980,7 @@ Deprecated. This method is unsafe. It will be changed to return `option` in a fu
```re sig
let toJSONUnsafe: t => string;
```
+
Returns a string representation of the given date. See [`Date.toJSON`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toJSON) on MDN.
```re example
@@ -928,12 +1000,12 @@ Js.Date.toLocaleDateString(exampleDate) == "11/29/1973"; // for en_US.utf8
Js.Date.toLocaleDateString(exampleDate) == "29.11.73"; // for de_DE.utf8
```
-
## toLocaleString
```re sig
let toLocaleString: t => string;
```
+
Returns the time and date for the given `Date` in the current locale format. See [`Date.toLocaleString`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString) on MDN.
```re example
@@ -946,6 +1018,7 @@ Js.Date.toLocaleString(exampleDate) == "29.11.1973, 22:30:54"; // for de_DE.utf8
```re sig
let toLocaleTimeString: t => string;
```
+
Returns the time of day for the given `Date` in the current locale format. See [`Date.toLocaleTimeString`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleTimeString) on MDN.
```re example
@@ -958,6 +1031,7 @@ Js.Date.toLocaleTimeString(exampleDate) == "22:30:54"; // for de_DE.utf8
```re sig
let toString: t => string;
```
+
Returns a string representing the date and time of day for the given `Date` in the current locale and time zone. See [`Date.toString`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toString) on MDN.
```re example
@@ -970,7 +1044,7 @@ Js.Date.toString(exampleDate) == "Thu Nov 29 1973 22:30:54 GMT+0100 (Central Eur
let toTimeString: t => string;
```
-Returns a string representing the time of day for the given `Date` in the current locale and time zone. See [`Date.toTimeString`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toTimeString) on MDN.
+Returns a string representing the time of day for the given `Date` in the current locale and time zone. See [`Date.toTimeString`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toTimeString) on MDN.
```re example
Js.Date.toTimeString(exampleDate) == "22:30:54 GMT+0100 (Central European Standard Time)";
diff --git a/pages/docs/manual/v8.0.0/api/js/dict.mdx b/pages/docs/manual/v8.0.0/api/js/dict.mdx
index 5bc29f5f1..642969029 100644
--- a/pages/docs/manual/v8.0.0/api/js/dict.mdx
+++ b/pages/docs/manual/v8.0.0/api/js/dict.mdx
@@ -29,7 +29,7 @@ This Dictionary type is mostly used with the Js_json.t type.
type key = string;
```
-The type for dictionary keys. This means that dictionaries *must* use `string`s as their keys.
+The type for dictionary keys. This means that dictionaries _must_ use `string`s as their keys.
## get
@@ -49,6 +49,7 @@ Js.Dict.get(ages, "Paul") == None;
```re sig
let unsafeGet: (t('a), key) => 'a;
```
+
`Js.Dict.unsafeGet(key)` returns the value if the key exists, otherwise an `undefined` value is returned. Use this only when you are sure the key exists (i.e. when having used the `keys()` function to check that the key is valid).
```re example
@@ -62,7 +63,7 @@ Js.Dict.unsafeGet(ages, "Paul"); // returns undefined
let set: (t('a), key, 'a) => unit;
```
-`Js.Dict.set(dict, key, value)` sets the key/value in the dictionary `dict`. If the key does not exist, and entry will be created for it. *This function modifies the original dictionary.*
+`Js.Dict.set(dict, key, value)` sets the key/value in the dictionary `dict`. If the key does not exist, and entry will be created for it. _This function modifies the original dictionary._
```re example
Js.Dict.set(ages, "Maria", 31)
diff --git a/pages/docs/manual/v8.0.0/api/js/float.mdx b/pages/docs/manual/v8.0.0/api/js/float.mdx
index abc3c583d..a7cec6ce8 100644
--- a/pages/docs/manual/v8.0.0/api/js/float.mdx
+++ b/pages/docs/manual/v8.0.0/api/js/float.mdx
@@ -6,11 +6,12 @@ Provide utilities for JS float.
-## _NaN
+## \_NaN
```re sig
let _NaN: float;
```
+
The special value "Not a Number".
## isNaN
@@ -19,7 +20,7 @@ The special value "Not a Number".
let isNaN: float => bool;
```
-Tests if the given value is _NaN.
+Tests if the given value is \_NaN.
Note that both `_NaN == _NaN` and `_NaN === _NaN` will return false. `isNaN` is therefore necessary to test for `_NaN`.
Returns true if the given value is `_NaN`, false otherwise.
@@ -171,7 +172,7 @@ Returns a `string` representing the given value in fixed-point or scientific not
The output will be rounded or padded with zeroes if necessary.
-`toPrecisionWithPrecision` differs from `toFixedWithPrecision` in that the former will count all digits against the precision, while the latter will count only the digits after the decimal point.
+`toPrecisionWithPrecision` differs from `toFixedWithPrecision` in that the former will count all digits against the precision, while the latter will count only the digits after the decimal point.
`toPrecisionWithPrecision` will also use scientific notation if the specified precision is less than the number for digits before the decimal point.
Raises `RangeError` if `digits` is not in the range accepted by this function.
diff --git a/pages/docs/manual/v8.0.0/api/js/json.mdx b/pages/docs/manual/v8.0.0/api/js/json.mdx
index 3403d9129..4126f8a04 100644
--- a/pages/docs/manual/v8.0.0/api/js/json.mdx
+++ b/pages/docs/manual/v8.0.0/api/js/json.mdx
@@ -41,7 +41,6 @@ type tagged_t =
| JSONArray(array(t));
```
-
## classify
```re sig
@@ -136,7 +135,7 @@ let boolean: bool => t;
`boolean(b)` makes a JSON boolean of the `bool` `b`.
-## object_
+## object\_
```re sig
let object_: Js_dict.t(t) => t;
@@ -182,7 +181,7 @@ let booleanArray: array(bool) => t;
let objectArray: array(Js_dict.t(t)) => t;
```
-`objectArray(a) makes a JSON array of the `JsDict.t` array `a`.
+`objectArray(a) makes a JSON array of the `JsDict.t`array`a`.
## parseExn
@@ -302,17 +301,3 @@ let stringifyAny: 'a => option(string);
/* prints `["foo", "bar"]` */
Js.log(Js.Json.stringifyAny([|"foo", "bar"|]));
```
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/pages/docs/manual/v8.0.0/api/js/math.mdx b/pages/docs/manual/v8.0.0/api/js/math.mdx
index 19d05c8e5..1195d6c1c 100644
--- a/pages/docs/manual/v8.0.0/api/js/math.mdx
+++ b/pages/docs/manual/v8.0.0/api/js/math.mdx
@@ -6,7 +6,7 @@ Provide utilities for JS Math. Note: The constants `_E`, `_LN10`, `_LN2`, `_LOG1
-## _E
+## \_E
```re sig
let _E: float;
@@ -14,7 +14,7 @@ let _E: float;
Euler's number; ≈ 2.718281828459045. See [`Math.E`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/E) on MDN.
-## _LN2
+## \_LN2
```re sig
let _LN2: float;
@@ -22,7 +22,7 @@ let _LN2: float;
Natural logarithm of 2; ≈ 0.6931471805599453. See [`Math.LN2`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/LN2) on MDN.
-## _LN10
+## \_LN10
```re sig
let _LN10: float;
@@ -30,7 +30,7 @@ let _LN10: float;
Natural logarithm of 10; ≈ 2.302585092994046. See [`Math.LN10`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/LN10) on MDN.
-## _LOG2E
+## \_LOG2E
```re sig
let _LOG2E: float;
@@ -38,7 +38,7 @@ let _LOG2E: float;
Base 2 logarithm of E; ≈ 1.4426950408889634. See [`Math.LOG2E`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/LOG2E) on MDN.
-## _LOG10E
+## \_LOG10E
```re sig
let _LOG10E: float;
@@ -46,7 +46,7 @@ let _LOG10E: float;
Base 10 logarithm of E; ≈ 0.4342944819032518. See [`Math.LOG10E`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/LOG10E) on MDN.
-## _PI
+## \_PI
```re sig
let _PI: float;
@@ -54,7 +54,7 @@ let _PI: float;
Pi - ratio of the circumference to the diameter of a circle; ≈ 3.141592653589793. See [`Math.PI`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/PI) on MDN.
-## _SQRT1_2
+## \_SQRT1_2
```re sig
let _SQRT1_2: float;
@@ -62,7 +62,7 @@ let _SQRT1_2: float;
Square root of 1/2; ≈ 0.7071067811865476. See [`Math.SQRT1_2`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/SQRT1_2) on MDN.
-## _SQRT2
+## \_SQRT2
```re sig
let _SQRT2: float;
@@ -140,7 +140,7 @@ Hyperbolic arctangent (in radians) of argument; returns `NaN` if the argument is
let atan2: (~y: float, ~x: float, unit) => float;
```
-Returns the angle (in radians) of the quotient `y /. x`. It is also the angle between the *x*-axis and point (*x*, *y*). See [`Math.atan2`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/atan2) on MDN.
+Returns the angle (in radians) of the quotient `y /. x`. It is also the angle between the _x_-axis and point (_x_, _y_). See [`Math.atan2`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/atan2) on MDN.
```re example
Js.Math.atan2(~y=0.0, ~x=10.0, ()) == 0.0 ;
@@ -178,6 +178,7 @@ Js.Math.unsafe_ceil_int(1.0e15); // result is outside range of int datatype
```re sig
let unsafe_ceil: float => int;
```
+
Deprecated; please use [`unsafe_ceil_int`](#unsafe_ceil_int) instead.
## ceil_int
@@ -255,7 +256,7 @@ Hyperbolic cosine of argument, which must be specified in radians. See [`Math.co
let exp: float => float;
```
-Natural exponentional; returns *e* (the base of natural logarithms) to the power of the given argument. See [`Math.exp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/exp) on MDN.
+Natural exponentional; returns _e_ (the base of natural logarithms) to the power of the given argument. See [`Math.exp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/exp) on MDN.
## expm1
@@ -263,7 +264,7 @@ Natural exponentional; returns *e* (the base of natural logarithms) to the power
let expm1: float => float;
```
-Returns *e* (the base of natural logarithms) to the power of the given argument minus 1. See [`Math.expm1`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/expm1) on MDN.
+Returns _e_ (the base of natural logarithms) to the power of the given argument minus 1. See [`Math.expm1`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/expm1) on MDN.
## unsafe_floor_int
@@ -326,6 +327,7 @@ Js.Math.floor_float(3.0) == 3.0;
Js.Math.floor_float(-3.1) == -4.0;
Js.Math.floor_float(2_150_000_000.3) == 2_150_000_000.0;
```
+
## fround
```re sig
@@ -373,7 +375,7 @@ let imul: (int, int) => int;
let log: float => float;
```
-Returns the natural logarithm of its argument; this is the number *x* such that *e**x* equals the argument. Returns `NaN` for negative arguments. See [`Math.log`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/log) on MDN.
+Returns the natural logarithm of its argument; this is the number _x_ such that _e__x_ equals the argument. Returns `NaN` for negative arguments. See [`Math.log`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/log) on MDN.
```re example
Js.Math.log(Js.Math._E) == 1.0;
@@ -421,14 +423,13 @@ Js.Math.log2(0.125) == -3.0;
Js.Math.log2(Js.Math._SQRT2) == 0.5000000000000001; // due to precision
```
-
## max_int
```re sig
let max_int: (int, int) => int;
```
-Returns the maximum of its two integer arguments. See [`Math.max`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/max) on MDN.
+Returns the maximum of its two integer arguments. See [`Math.max`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/max) on MDN.
## maxMany_int
@@ -436,7 +437,7 @@ Returns the maximum of its two integer arguments. See [`Math.max`](https://deve
let maxMany_int: array(int) => int;
```
-Returns the maximum of the integers in the given array. See [`Math.max`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/max) on MDN.
+Returns the maximum of the integers in the given array. See [`Math.max`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/max) on MDN.
## max_float
@@ -462,7 +463,6 @@ let min_int: (int, int) => int;
Returns the minimum of its two integer arguments. See [`Math.min`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/min) on MDN.
-
## minMany_int
```re sig
@@ -487,7 +487,6 @@ let minMany_float: array(float) => float;
Returns the minimum of the floating point values in the given array. See [`Math.min`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/min) on MDN.
-
## pow_int
```re sig
@@ -497,10 +496,9 @@ let pow_int: (~base: int, ~exp: int) => int;
Raises the given base to the given exponent. (Arguments and result are integers.) See [`Math.pow`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/pow) on MDN.
```re example
-Js.Math.pow_int(~base=3, ~exp=4) == 81;
+Js.Math.pow_int(~base=3, ~exp=4) == 81;
```
-
## pow_float
```re sig
@@ -539,7 +537,7 @@ A call to `random_int(minVal, maxVal)` returns a random number in the half-close
let unsafe_round: float => int;
```
-Rounds its argument to nearest integer. For numbers with a fractional portion of exactly 0.5, the argument is rounded to the next integer in the direction of positive infinity. This function may return values not representable by `int`, whose range is -2147483648 to 2147483647. This is because, in JavaScript, there are only 64-bit floating point numbers, which can represent integers in the range ±(253 -1) exactly. See [`Math.round`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round) on MDN.
+Rounds its argument to nearest integer. For numbers with a fractional portion of exactly 0.5, the argument is rounded to the next integer in the direction of positive infinity. This function may return values not representable by `int`, whose range is -2147483648 to 2147483647. This is because, in JavaScript, there are only 64-bit floating point numbers, which can represent integers in the range ±(253 -1) exactly. See [`Math.round`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round) on MDN.
```re example
Js.Math.unsafe_round(3.7) == 4;
@@ -555,7 +553,6 @@ let round: float => float;
Rounds to nearest integral value (expressed as a float). See [`Math.round`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round) on MDN.
-
## sign_int
```re sig
@@ -569,6 +566,7 @@ Returns the sign of its integer argument: -1 if negative, 0 if zero, 1 if positi
```re sig
let sign_float: float => float;
```
+
Returns the sign of its float argument: -1.0 if negative, 0.0 if zero, 1.0 if positive. See [`Math.sign`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign) on MDN.
## sin
diff --git a/pages/docs/manual/v8.0.0/api/js/option.mdx b/pages/docs/manual/v8.0.0/api/js/option.mdx
index f1522d0b3..b0f29795f 100644
--- a/pages/docs/manual/v8.0.0/api/js/option.mdx
+++ b/pages/docs/manual/v8.0.0/api/js/option.mdx
@@ -17,6 +17,7 @@ type t('a) = option('a);
```re sig
let some: 'a => option('a);
```
+
Wraps the given value in `Some()`
```re example
@@ -68,14 +69,14 @@ If the argument to `getExn()` is of the form `Some(value)`, returns `value`. If
let equal: ((. 'a, 'b) => bool, option('a), option('b)) => bool;
```
-The first argument to `equal` is an uncurried function `eq()` that takes two arguments and returns `true` if they are considered to be equal. The second and third arguments are `option` values.
+The first argument to `equal` is an uncurried function `eq()` that takes two arguments and returns `true` if they are considered to be equal. The second and third arguments are `option` values.
If the second and third arguments are of the form:
-* `Some(v1)` and `Some(v2)`: returns `eq(v1, v2)`
-* `Some(v1)` and `None`: returns `false`
-* `None` and `Some(v2)`: returns `false`
-* `None` and `None`: returns `true`
+- `Some(v1)` and `Some(v2)`: returns `eq(v1, v2)`
+- `Some(v1)` and `None`: returns `false`
+- `None` and `Some(v2)`: returns `false`
+- `None` and `None`: returns `true`
```re example
let clockEqual = (. a, b) => (a mod 12 == b mod 12);
@@ -142,9 +143,9 @@ let default: ('a, option('a)) => 'a;
let filter: ((. 'a) => bool, option('a)) => option('a);
```
-The first argument to `filter()` is an uncurried function that takes a plain value and returns a boolean. The second argument is an `option` value.
+The first argument to `filter()` is an uncurried function that takes a plain value and returns a boolean. The second argument is an `option` value.
-If the second argument is of the form `Some(v)` and `f(v)` is `true`,
+If the second argument is of the form `Some(v)` and `f(v)` is `true`,
the return value is `Some(v)`. Otherwise, the return value is `None`.
```re example
diff --git a/pages/docs/manual/v8.0.0/api/js/promise.mdx b/pages/docs/manual/v8.0.0/api/js/promise.mdx
index e2a555a7e..443553ba6 100644
--- a/pages/docs/manual/v8.0.0/api/js/promise.mdx
+++ b/pages/docs/manual/v8.0.0/api/js/promise.mdx
@@ -78,7 +78,7 @@ let all6: ((t('a0), t('a1), t('a2), t('a3), t('a4), t('a5))) => t(('a0, 'a1, 'a2
let race: array(t('a)) => t('a);
```
-## then_
+## then\_
```re sig
let then_: ('a => t('b), t('a)) => t('b);
diff --git a/pages/docs/manual/v8.0.0/api/js/string-2.mdx b/pages/docs/manual/v8.0.0/api/js/string-2.mdx
index c5ecd9eb4..49bd3df88 100644
--- a/pages/docs/manual/v8.0.0/api/js/string-2.mdx
+++ b/pages/docs/manual/v8.0.0/api/js/string-2.mdx
@@ -55,10 +55,10 @@ let fromCharCodeMany: array(int) => t;
let fromCodePoint: int => t;
```
-`fromCodePoint(n)` creates a `string` containing the character corresponding to that numeric code point.
-If the number is not a valid code point, it raises `RangeError`.
+`fromCodePoint(n)` creates a `string` containing the character corresponding to that numeric code point.
+If the number is not a valid code point, it raises `RangeError`.
Thus, `fromCodePoint(0x1F63A)` will produce a correct value, unlike `fromCharCode(0x1F63A)`, and `fromCodePoint(-5)` will raise a `RangeError`. See [`String.fromCodePoint`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/fromCodePoint) on MDN.
-
+
```re example
Js.String2.fromCodePoint(65) == "A";
Js.String2.fromCodePoint(0x3c8) == {js|ψ|js};
@@ -96,7 +96,7 @@ Js.String2.length("abcd") == 4;
let get: (t, int) => t;
```
-`get(s, n)` returns as a `string` the character at the given index number.
+`get(s, n)` returns as a `string` the character at the given index number.
If `n` is out of range, this function returns `undefined`,so at some point this function may be modified to return `option(string)`.
```re example
@@ -111,7 +111,7 @@ Js.String2.get({js|Rẽasöń|js}, 5) == {js|ń|js};
let charAt: (t, int) => t;
```
-`charAt(s, n)` gets the character at index `n` within string `s`.
+`charAt(s, n)` gets the character at index `n` within string `s`.
If `n` is negative or greater than the length of `s`, it returns the empty string.
If the string contains characters outside the range \u0000-\uffff, it will return the first 16-bit value at that position in the string. See [`String.charAt`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/charAt) on MDN.
@@ -127,7 +127,7 @@ Js.String2.charAt({js|Rẽasöń|js}, 5) == {js|ń|js};
let charCodeAt: (t, int) => float;
```
-`charCodeAt(s, n)` returns the character code at position `n` in string `s`; the result is in the range 0-65535, unlke `codePointAt`, so it will not work correctly for characters with code points greater than or equal to 0x10000.
+`charCodeAt(s, n)` returns the character code at position `n` in string `s`; the result is in the range 0-65535, unlke `codePointAt`, so it will not work correctly for characters with code points greater than or equal to 0x10000.
The return type is `float` because this function returns NaN if `n` is less than zero or greater than the length of the string. See [`String.charCodeAt`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/charCodeAt) on MDN.
```re example
@@ -141,7 +141,7 @@ Js.String2.codePointAt({js|😺|js}, 0) == Some(0x1f63a);
let codePointAt: (t, int) => option(int);
```
-`codePointAt(s, n)` returns the code point at position `n` within string `s` as a `Some(value)`.
+`codePointAt(s, n)` returns the code point at position `n` within string `s` as a `Some(value)`.
The return value handles code points greater than or equal to 0x10000.
If there is no code point at the given position, the function returns `None`. See [`String.codePointAt`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/codePointAt) on MDN.
@@ -252,6 +252,7 @@ Js.String2.indexOf("bookseller", "xyz") == -1;
```re sig
let indexOfFrom: (t, t, int) => int;
```
+
`indexOfFrom(str, searchValue, start)` returns the position at which `searchValue` was found within `str` starting at character position `start`, or -1 if `searchValue` is not found in that portion of `str`.
The return value is relative to the beginning of the string, no matter where the search started from. See [`String.indexOf`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf) on MDN.
@@ -299,6 +300,7 @@ let localeCompare: (t, t) => float;
```
`localeCompare(reference, comparison)` returns
+
- a negative value if reference comes before comparison in sort order
- zero if reference and comparison have the same sort order
- a positive value if reference comes after comparison in sort order
@@ -319,9 +321,10 @@ let match: (t, Js_re.t) => option(array(t));
```
`match(str, regexp)` matches a `string` against the given `regexp`. If there is no match, it returns `None`. For regular expressions without the g modifier, if there is a match, the return value is `Some(array)` where the array contains:
+
- The entire matched string
- Any capture groups if the regexp had parentheses
-For regular expressions with the g modifier, a matched expression returns `Some(array)` with all the matched substrings and no capture groups. See [`String.match`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match) on MDN.
+ For regular expressions with the g modifier, a matched expression returns `Some(array)` with all the matched substrings and no capture groups. See [`String.match`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match) on MDN.
```re example
Js.String2.match("The better bats", [%re "/b[aeiou]t/"]) == Some([|"bet"|]);
@@ -338,7 +341,7 @@ let normalize: t => t;
`normalize(str)` returns the normalized Unicode string using Normalization Form Canonical (NFC) Composition.
Consider the character ã, which can be represented as the single codepoint \u00e3 or the combination of a lower case letter A \u0061 and a combining tilde \u0303.
-Normalization ensures that both can be stored in an equivalent binary representation. See [`String.normalize`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/normalize) on MDN. See also [Unicode technical report #15](https://unicode.org/reports/tr15/) for details.
+Normalization ensures that both can be stored in an equivalent binary representation. See [`String.normalize`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/normalize) on MDN. See also [Unicode technical report #15](https://unicode.org/reports/tr15/) for details.
## normalizeByForm
@@ -347,6 +350,7 @@ let normalizeByForm: (t, t) => t;
```
ES2015: `normalize(str, form)` returns the normalized Unicode string using the specified form of normalization, which may be one of:
+
- "NFC" — Normalization Form Canonical Composition.
- "NFD" — Normalization Form Canonical Decomposition.
- "NFKC" — Normalization Form Compatibility Composition.
@@ -479,6 +483,7 @@ let slice: (t, ~from: int, ~to_: int) => t;
```
`slice(str, from:n1, to_:n2)` returns the substring of `str` starting at character `n1` up to but not including `n2`.
+
- If either `n1` or `n2` is negative, then it is evaluated as `length(str - n1)` or `length(str - n2)`.
- If `n2` is greater than the length of `str`, then it is treated as `length(str)`.
- If `n1` is greater than `n2`, slice returns the empty string.
@@ -499,6 +504,7 @@ let sliceToEnd: (t, ~from: int) => t;
```
`sliceToEnd(str, from:n)` returns the substring of `str` starting at character `n` to the end of the string.
+
- If `n` is negative, then it is evaluated as `length(str - n)`.
- If `n` is greater than the length of `str`, then sliceToEnd returns the empty string.
@@ -609,6 +615,7 @@ let substr: (t, ~from: int) => t;
```
`substr(str, ~from:n)` returns the substring of `str` from position `n` to the end of the string.
+
- If `n` is less than zero, the starting position is the length of `str - n`.
- If `n` is greater than or equal to the length of `str`, returns the empty string.
@@ -627,6 +634,7 @@ let substrAtMost: (t, ~from: int, ~length: int) => t;
```
`substrAtMost(str, ~from: pos, ~length: n)` returns the substring of `str` of length `n` starting at position `pos`.
+
- If `pos` is less than zero, the starting position is the length of `str - pos`.
- If `pos` is greater than or equal to the length of `str`, returns the empty string.
- If `n` is less than or equal to zero, returns the empty string.
@@ -646,6 +654,7 @@ let substring: (t, ~from: int, ~to_: int) => t;
```
`substring(str, ~from: start, ~to_: finish)` returns characters `start` up to but not including finish from `str`.
+
- If `start` is less than zero, it is treated as zero.
- If `finish` is zero or negative, the empty string is returned.
- If `start` is greater than `finish`, the `start` and `finish` points are swapped.
@@ -665,6 +674,7 @@ let substringToEnd: (t, ~from: int) => t;
```
`substringToEnd(str, ~from: start)` returns the substring of `str` from position `start` to the end.
+
- If `start` is less than or equal to zero, the entire string is returned.
- If `start` is greater than or equal to the length of `str`, the empty string is returned.
@@ -705,7 +715,7 @@ let toLocaleLowerCase: t => t;
let toUpperCase: t => t;
```
-`toUpperCase(str)` converts `str` to upper case using the locale-insensitive case mappings in the Unicode Character Database.
+`toUpperCase(str)` converts `str` to upper case using the locale-insensitive case mappings in the Unicode Character Database.
Notice that the conversion can expand the number of letters in the result; for example the German ß capitalizes to two Ses in a row. See [`String.toUpperCase`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toUpperCase) on MDN.
```re example
diff --git a/pages/docs/manual/v8.0.0/api/js/string.mdx b/pages/docs/manual/v8.0.0/api/js/string.mdx
index 43296c34e..c5a6fc6e3 100644
--- a/pages/docs/manual/v8.0.0/api/js/string.mdx
+++ b/pages/docs/manual/v8.0.0/api/js/string.mdx
@@ -55,10 +55,10 @@ let fromCharCodeMany: array(int) => t;
let fromCodePoint: int => t;
```
-`fromCodePoint(n)` creates a `string` containing the character corresponding to that numeric code point.
-If the number is not a valid code point, it raises `RangeError`.
+`fromCodePoint(n)` creates a `string` containing the character corresponding to that numeric code point.
+If the number is not a valid code point, it raises `RangeError`.
Thus, `fromCodePoint(0x1F63A)` will produce a correct value, unlike `fromCharCode(0x1F63A)`, and `fromCodePoint(-5)` will raise a `RangeError`. See [`String.fromCodePoint`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/fromCodePoint) on MDN.
-
+
```re example
Js.String2.fromCodePoint(65) == "A";
Js.String2.fromCodePoint(0x3c8) == {js|ψ|js};
@@ -96,7 +96,7 @@ Js.String2.length("abcd") == 4;
let get: (t, int) => t;
```
-`get(s, n)` returns as a `string` the character at the given index number.
+`get(s, n)` returns as a `string` the character at the given index number.
If `n` is out of range, this function returns `undefined`, so at some point this function may be modified to return `option(string)`.
```re example
@@ -111,7 +111,7 @@ Js.String2.get({js|Rẽasöń|js}, 5) == {js|ń|js};
let charAt: (int, t) => t;
```
-`charAt(n, s)` gets the character at index `n` within string `s`.
+`charAt(n, s)` gets the character at index `n` within string `s`.
If `n` is negative or greater than the length of `s`, it returns the empty string.
If the string contains characters outside the range \u0000-\uffff, it will return the first 16-bit value at that position in the string. See [`String.charAt`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/charAt) on MDN.
@@ -127,7 +127,7 @@ Js.String.charAt(5, {js|Rẽasöń|js}) == {js|ń|js};
let charCodeAt: (int, t) => float;
```
-`charCodeAt(n, s)` returns the character code at position `n` in string `s`; the result is in the range 0-65535, unlke `codePointAt`, so it will not work correctly for characters with code points greater than or equal to 0x10000.
+`charCodeAt(n, s)` returns the character code at position `n` in string `s`; the result is in the range 0-65535, unlke `codePointAt`, so it will not work correctly for characters with code points greater than or equal to 0x10000.
The return type is `float` because this function returns NaN if `n` is less than zero or greater than the length of the string. See [`String.charCodeAt`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/charCodeAt) on MDN.
```re example
@@ -141,7 +141,7 @@ Js.String.codePointAt(0, {js|😺|js}) == Some(0x1f63a);
let codePointAt: (int, t) => option(int);
```
-`codePointAt(n, s)` returns the code point at position `n` within string `s` as a `Some(value)`.
+`codePointAt(n, s)` returns the code point at position `n` within string `s` as a `Some(value)`.
The return value handles code points greater than or equal to 0x10000.
If there is no code point at the given position, the function returns `None`. See [`String.codePointAt`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/codePointAt) on MDN.
@@ -252,6 +252,7 @@ Js.String.indexOf("xyz", "bookseller") == -1;
```re sig
let indexOfFrom: (t, t, int) => int;
```
+
`indexOfFrom(searchValue, start, str)` returns the position at which `searchValue` was found within `str` starting at character position `start`, or -1 if `searchValue` is not found in that portion of `str`.
The return value is relative to the beginning of the string, no matter where the search started from. See [`String.indexOf`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf) on MDN.
@@ -299,6 +300,7 @@ let localeCompare: (t, t) => float;
```
`localeCompare(comparison, reference)` returns
+
- a negative value if reference comes before comparison in sort order
- zero if reference and comparison have the same sort order
- a positive value if reference comes after comparison in sort order
@@ -319,9 +321,10 @@ let match: (Js_re.t, t) => option(array(t));
```
`match(regexp, str)` matches a `string` against the given `regexp`. If there is no match, it returns `None`. For regular expressions without the g modifier, if there is a match, the return value is `Some(array)` where the array contains:
+
- The entire matched string
- Any capture groups if the regexp had parentheses
-For regular expressions with the g modifier, a matched expression returns `Some(array)` with all the matched substrings and no capture groups. See [`String.match`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match) on MDN.
+ For regular expressions with the g modifier, a matched expression returns `Some(array)` with all the matched substrings and no capture groups. See [`String.match`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match) on MDN.
```re example
Js.String.match([%re "/b[aeiou]t/"], "The better bats") == Some([|"bet"|]);
@@ -338,7 +341,7 @@ let normalize: t => t;
`normalize(str)` returns the normalized Unicode string using Normalization Form Canonical (NFC) Composition.
Consider the character ã, which can be represented as the single codepoint \u00e3 or the combination of a lower case letter A \u0061 and a combining tilde \u0303.
-Normalization ensures that both can be stored in an equivalent binary representation. See [`String.normalize`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/normalize) on MDN. See also [Unicode technical report #15](https://unicode.org/reports/tr15/) for details.
+Normalization ensures that both can be stored in an equivalent binary representation. See [`String.normalize`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/normalize) on MDN. See also [Unicode technical report #15](https://unicode.org/reports/tr15/) for details.
## normalizeByForm
@@ -347,6 +350,7 @@ let normalizeByForm: (t, t) => t;
```
ES2015: `normalize(form, str)` returns the normalized Unicode string using the specified form of normalization, which may be one of:
+
- "NFC" — Normalization Form Canonical Composition.
- "NFD" — Normalization Form Canonical Decomposition.
- "NFKC" — Normalization Form Compatibility Composition.
@@ -479,6 +483,7 @@ let slice: (~from: int, ~to_: int, t) => t;
```
`slice(from:n1, to_:n2, str)` returns the substring of `str` starting at character `n1` up to but not including `n2`.
+
- If either `n1` or `n2` is negative, then it is evaluated as `length(str - n1)` or `length(str - n2)`.
- If `n2` is greater than the length of `str`, then it is treated as `length(str)`.
- If `n1` is greater than `n2`, slice returns the empty string.
@@ -499,6 +504,7 @@ let sliceToEnd: (~from: int, t) => t;
```
`sliceToEnd(str, from:n)` returns the substring of `str` starting at character `n` to the end of the string.
+
- If `n` is negative, then it is evaluated as `length(str - n)`.
- If `n` is greater than the length of `str`, then sliceToEnd returns the empty string.
@@ -625,6 +631,7 @@ let substr: (~from: int, t) => t;
```
`substr(~from:n, str)` returns the substring of `str` from position `n` to the end of the string.
+
- If `n` is less than zero, the starting position is the length of `str - n`.
- If `n` is greater than or equal to the length of `str`, returns the empty string.
@@ -643,6 +650,7 @@ let substrAtMost: (~from: int, ~length: int, t) => t;
```
`substrAtMost(~from: pos, ~length: n, str)` returns the substring of `str` of length `n` starting at position `pos`.
+
- If `pos` is less than zero, the starting position is the length of `str - pos`.
- If `pos` is greater than or equal to the length of `str`, returns the empty string.
- If `n` is less than or equal to zero, returns the empty string.
@@ -662,6 +670,7 @@ let substring: (~from: int, ~to_: int, t) => t;
```
`substring(~from: start, ~to_: finish, str)` returns characters `start` up to but not including finish from `str`.
+
- If `start` is less than zero, it is treated as zero.
- If `finish` is zero or negative, the empty string is returned.
- If `start` is greater than `finish`, the `start` and `finish` points are swapped.
@@ -681,6 +690,7 @@ let substringToEnd: (~from: int, t) => t;
```
`substringToEnd(~from: start, str)` returns the substring of `str` from position `start` to the end.
+
- If `start` is less than or equal to zero, the entire string is returned.
- If `start` is greater than or equal to the length of `str`, the empty string is returned.
@@ -721,7 +731,7 @@ let toLocaleLowerCase: t => t;
let toUpperCase: t => t;
```
-`toUpperCase(str)` converts `str` to upper case using the locale-insensitive case mappings in the Unicode Character Database.
+`toUpperCase(str)` converts `str` to upper case using the locale-insensitive case mappings in the Unicode Character Database.
Notice that the conversion can expand the number of letters in the result; for example the German ß capitalizes to two Ses in a row. See [`String.toUpperCase`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toUpperCase) on MDN.
```re example
diff --git a/pages/docs/manual/v8.0.0/api/js/typed-array-2.mdx b/pages/docs/manual/v8.0.0/api/js/typed-array-2.mdx
index 3df37be41..d374bec11 100644
--- a/pages/docs/manual/v8.0.0/api/js/typed-array-2.mdx
+++ b/pages/docs/manual/v8.0.0/api/js/typed-array-2.mdx
@@ -19,13 +19,23 @@ type array_like('a);
```
## module ArrayBuffer
+
## module Int8Array
+
## module Uint8Array
+
## module Uint8ClampedArray
+
## module Int16Array
+
## module Uint16Array
+
## module Int32Array
+
## module Uint32Array
+
## module Float32Array
+
## module Float64Array
+
## module DataView
diff --git a/pages/docs/manual/v8.0.0/api/js/typed-array-2_array-buffer.mdx b/pages/docs/manual/v8.0.0/api/js/typed-array-2_array-buffer.mdx
index 0e5415ab1..34ee237db 100644
--- a/pages/docs/manual/v8.0.0/api/js/typed-array-2_array-buffer.mdx
+++ b/pages/docs/manual/v8.0.0/api/js/typed-array-2_array-buffer.mdx
@@ -20,7 +20,6 @@ let make: int => t;
Takes length. initializes elements to 0.
-
## byteLength
```re sig
diff --git a/pages/docs/manual/v8.0.0/api/js/typed-array-2_float-32-array.mdx b/pages/docs/manual/v8.0.0/api/js/typed-array-2_float-32-array.mdx
index 08912039f..f1f59321e 100644
--- a/pages/docs/manual/v8.0.0/api/js/typed-array-2_float-32-array.mdx
+++ b/pages/docs/manual/v8.0.0/api/js/typed-array-2_float-32-array.mdx
@@ -314,7 +314,7 @@ let some: ((. elt) => bool, t) => bool;
let somei: ((. elt, int) => bool, t) => bool;
```
-## _BYTES_PER_ELEMENT
+## \_BYTES_PER_ELEMENT
```re sig
let _BYTES_PER_ELEMENT: int;
@@ -361,5 +361,3 @@ Raises `Js.Exn.Error` raise Js exception.
```re sig
let from: Js_typed_array2.array_like(elt) => t;
```
-
-
diff --git a/pages/docs/manual/v8.0.0/api/js/typed-array-2_float-64-array.mdx b/pages/docs/manual/v8.0.0/api/js/typed-array-2_float-64-array.mdx
index 52a523d2a..f61bc84c2 100644
--- a/pages/docs/manual/v8.0.0/api/js/typed-array-2_float-64-array.mdx
+++ b/pages/docs/manual/v8.0.0/api/js/typed-array-2_float-64-array.mdx
@@ -314,7 +314,7 @@ let some: ((. elt) => bool, t) => bool;
let somei: ((. elt, int) => bool, t) => bool;
```
-## _BYTES_PER_ELEMENT
+## \_BYTES_PER_ELEMENT
```re sig
let _BYTES_PER_ELEMENT: int;
diff --git a/pages/docs/manual/v8.0.0/api/js/typed-array-2_int-16-array.mdx b/pages/docs/manual/v8.0.0/api/js/typed-array-2_int-16-array.mdx
index 68c04f2cf..3bf2c8b9c 100644
--- a/pages/docs/manual/v8.0.0/api/js/typed-array-2_int-16-array.mdx
+++ b/pages/docs/manual/v8.0.0/api/js/typed-array-2_int-16-array.mdx
@@ -314,7 +314,7 @@ let some: ((. elt) => bool, t) => bool;
let somei: ((. elt, int) => bool, t) => bool;
```
-## _BYTES_PER_ELEMENT
+## \_BYTES_PER_ELEMENT
```re sig
let _BYTES_PER_ELEMENT: int;
diff --git a/pages/docs/manual/v8.0.0/api/js/typed-array-2_int-32-array.mdx b/pages/docs/manual/v8.0.0/api/js/typed-array-2_int-32-array.mdx
index c6464d4df..3160e5acc 100644
--- a/pages/docs/manual/v8.0.0/api/js/typed-array-2_int-32-array.mdx
+++ b/pages/docs/manual/v8.0.0/api/js/typed-array-2_int-32-array.mdx
@@ -314,7 +314,7 @@ let some: ((. elt) => bool, t) => bool;
let somei: ((. elt, int) => bool, t) => bool;
```
-## _BYTES_PER_ELEMENT
+## \_BYTES_PER_ELEMENT
```re sig
let _BYTES_PER_ELEMENT: int;
diff --git a/pages/docs/manual/v8.0.0/api/js/typed-array-2_int-8-array.mdx b/pages/docs/manual/v8.0.0/api/js/typed-array-2_int-8-array.mdx
index d1691dc6e..3b80b300f 100644
--- a/pages/docs/manual/v8.0.0/api/js/typed-array-2_int-8-array.mdx
+++ b/pages/docs/manual/v8.0.0/api/js/typed-array-2_int-8-array.mdx
@@ -314,7 +314,7 @@ let some: ((. elt) => bool, t) => bool;
let somei: ((. elt, int) => bool, t) => bool;
```
-## _BYTES_PER_ELEMENT
+## \_BYTES_PER_ELEMENT
```re sig
let _BYTES_PER_ELEMENT: int;
diff --git a/pages/docs/manual/v8.0.0/api/js/typed-array-2_uint-16-array.mdx b/pages/docs/manual/v8.0.0/api/js/typed-array-2_uint-16-array.mdx
index 3514b9ddd..f48817c3c 100644
--- a/pages/docs/manual/v8.0.0/api/js/typed-array-2_uint-16-array.mdx
+++ b/pages/docs/manual/v8.0.0/api/js/typed-array-2_uint-16-array.mdx
@@ -314,7 +314,7 @@ let some: ((. elt) => bool, t) => bool;
let somei: ((. elt, int) => bool, t) => bool;
```
-## _BYTES_PER_ELEMENT
+## \_BYTES_PER_ELEMENT
```re sig
let _BYTES_PER_ELEMENT: int;
diff --git a/pages/docs/manual/v8.0.0/api/js/typed-array-2_uint-32-array.mdx b/pages/docs/manual/v8.0.0/api/js/typed-array-2_uint-32-array.mdx
index cf2ea4280..c04c8ac09 100644
--- a/pages/docs/manual/v8.0.0/api/js/typed-array-2_uint-32-array.mdx
+++ b/pages/docs/manual/v8.0.0/api/js/typed-array-2_uint-32-array.mdx
@@ -314,7 +314,7 @@ let some: ((. elt) => bool, t) => bool;
let somei: ((. elt, int) => bool, t) => bool;
```
-## _BYTES_PER_ELEMENT
+## \_BYTES_PER_ELEMENT
```re sig
let _BYTES_PER_ELEMENT: int;
diff --git a/pages/docs/manual/v8.0.0/api/js/typed-array-2_uint-8-array.mdx b/pages/docs/manual/v8.0.0/api/js/typed-array-2_uint-8-array.mdx
index 68f5f6ac2..e43293454 100644
--- a/pages/docs/manual/v8.0.0/api/js/typed-array-2_uint-8-array.mdx
+++ b/pages/docs/manual/v8.0.0/api/js/typed-array-2_uint-8-array.mdx
@@ -314,7 +314,7 @@ let some: ((. elt) => bool, t) => bool;
let somei: ((. elt, int) => bool, t) => bool;
```
-## _BYTES_PER_ELEMENT
+## \_BYTES_PER_ELEMENT
```re sig
let _BYTES_PER_ELEMENT: int;
diff --git a/pages/docs/manual/v8.0.0/api/js/typed-array-2_uint-8-clamped-array.mdx b/pages/docs/manual/v8.0.0/api/js/typed-array-2_uint-8-clamped-array.mdx
index c2d4d4646..42299a5de 100644
--- a/pages/docs/manual/v8.0.0/api/js/typed-array-2_uint-8-clamped-array.mdx
+++ b/pages/docs/manual/v8.0.0/api/js/typed-array-2_uint-8-clamped-array.mdx
@@ -314,7 +314,7 @@ let some: ((. elt) => bool, t) => bool;
let somei: ((. elt, int) => bool, t) => bool;
```
-## _BYTES_PER_ELEMENT
+## \_BYTES_PER_ELEMENT
```re sig
let _BYTES_PER_ELEMENT: int;
diff --git a/pages/docs/manual/v8.0.0/api/js/typed-array.mdx b/pages/docs/manual/v8.0.0/api/js/typed-array.mdx
index d80d022d5..cc34eb8cb 100644
--- a/pages/docs/manual/v8.0.0/api/js/typed-array.mdx
+++ b/pages/docs/manual/v8.0.0/api/js/typed-array.mdx
@@ -25,14 +25,25 @@ module type Type = {type t;};
```
## module ArrayBuffer
+
## module type S
+
## module Int8Array
+
## module Uint8Array
+
## module Uint8ClampedArray
+
## module Int16Array
+
## module Uint16Array
+
## module Int32Array
+
## module Uint32Array
+
## module Float32Array
-## module Float64Array
+
+## module Float64Array
+
## module DataView
diff --git a/pages/docs/manual/v8.0.0/api/js/typed-array_float-32-array.mdx b/pages/docs/manual/v8.0.0/api/js/typed-array_float-32-array.mdx
index e90e15832..bfb095530 100644
--- a/pages/docs/manual/v8.0.0/api/js/typed-array_float-32-array.mdx
+++ b/pages/docs/manual/v8.0.0/api/js/typed-array_float-32-array.mdx
@@ -314,7 +314,7 @@ let some: ((. elt) => bool, t) => bool;
let somei: ((. elt, int) => bool, t) => bool;
```
-## _BYTES_PER_ELEMENT
+## \_BYTES_PER_ELEMENT
```re sig
let _BYTES_PER_ELEMENT: int;
diff --git a/pages/docs/manual/v8.0.0/api/js/typed-array_float-64-array.mdx b/pages/docs/manual/v8.0.0/api/js/typed-array_float-64-array.mdx
index e122f4648..6d0cf20a7 100644
--- a/pages/docs/manual/v8.0.0/api/js/typed-array_float-64-array.mdx
+++ b/pages/docs/manual/v8.0.0/api/js/typed-array_float-64-array.mdx
@@ -314,7 +314,7 @@ let some: ((. elt) => bool, t) => bool;
let somei: ((. elt, int) => bool, t) => bool;
```
-## _BYTES_PER_ELEMENT
+## \_BYTES_PER_ELEMENT
```re sig
let _BYTES_PER_ELEMENT: int;
diff --git a/pages/docs/manual/v8.0.0/api/js/typed-array_int-16-array.mdx b/pages/docs/manual/v8.0.0/api/js/typed-array_int-16-array.mdx
index eb7fc8175..a77ed5973 100644
--- a/pages/docs/manual/v8.0.0/api/js/typed-array_int-16-array.mdx
+++ b/pages/docs/manual/v8.0.0/api/js/typed-array_int-16-array.mdx
@@ -314,7 +314,7 @@ let some: ((. elt) => bool, t) => bool;
let somei: ((. elt, int) => bool, t) => bool;
```
-## _BYTES_PER_ELEMENT
+## \_BYTES_PER_ELEMENT
```re sig
let _BYTES_PER_ELEMENT: int;
diff --git a/pages/docs/manual/v8.0.0/api/js/typed-array_int-32-array.mdx b/pages/docs/manual/v8.0.0/api/js/typed-array_int-32-array.mdx
index c4385d7ce..7424bae43 100644
--- a/pages/docs/manual/v8.0.0/api/js/typed-array_int-32-array.mdx
+++ b/pages/docs/manual/v8.0.0/api/js/typed-array_int-32-array.mdx
@@ -314,7 +314,7 @@ let some: ((. elt) => bool, t) => bool;
let somei: ((. elt, int) => bool, t) => bool;
```
-## _BYTES_PER_ELEMENT
+## \_BYTES_PER_ELEMENT
```re sig
let _BYTES_PER_ELEMENT: int;
diff --git a/pages/docs/manual/v8.0.0/api/js/typed-array_int-8-array.mdx b/pages/docs/manual/v8.0.0/api/js/typed-array_int-8-array.mdx
index 49d19a61e..60e1c5187 100644
--- a/pages/docs/manual/v8.0.0/api/js/typed-array_int-8-array.mdx
+++ b/pages/docs/manual/v8.0.0/api/js/typed-array_int-8-array.mdx
@@ -314,7 +314,7 @@ let some: ((. elt) => bool, t) => bool;
let somei: ((. elt, int) => bool, t) => bool;
```
-## _BYTES_PER_ELEMENT
+## \_BYTES_PER_ELEMENT
```re sig
let _BYTES_PER_ELEMENT: int;
diff --git a/pages/docs/manual/v8.0.0/api/js/typed-array_type-s.mdx b/pages/docs/manual/v8.0.0/api/js/typed-array_type-s.mdx
index 46b5b85da..1640c6865 100644
--- a/pages/docs/manual/v8.0.0/api/js/typed-array_type-s.mdx
+++ b/pages/docs/manual/v8.0.0/api/js/typed-array_type-s.mdx
@@ -307,4 +307,3 @@ let some: ((. elt) => bool, t) => bool;
```re sig
let somei: ((. elt, int) => bool, t) => bool;
```
-
diff --git a/pages/docs/manual/v8.0.0/api/js/typed-array_uint-16-array.mdx b/pages/docs/manual/v8.0.0/api/js/typed-array_uint-16-array.mdx
index eba8edf91..a2aec5b41 100644
--- a/pages/docs/manual/v8.0.0/api/js/typed-array_uint-16-array.mdx
+++ b/pages/docs/manual/v8.0.0/api/js/typed-array_uint-16-array.mdx
@@ -314,7 +314,7 @@ let some: ((. elt) => bool, t) => bool;
let somei: ((. elt, int) => bool, t) => bool;
```
-## _BYTES_PER_ELEMENT
+## \_BYTES_PER_ELEMENT
```re sig
let _BYTES_PER_ELEMENT: int;
diff --git a/pages/docs/manual/v8.0.0/api/js/typed-array_uint-32-array.mdx b/pages/docs/manual/v8.0.0/api/js/typed-array_uint-32-array.mdx
index b848c13a1..34005a11e 100644
--- a/pages/docs/manual/v8.0.0/api/js/typed-array_uint-32-array.mdx
+++ b/pages/docs/manual/v8.0.0/api/js/typed-array_uint-32-array.mdx
@@ -314,7 +314,7 @@ let some: ((. elt) => bool, t) => bool;
let somei: ((. elt, int) => bool, t) => bool;
```
-## _BYTES_PER_ELEMENT
+## \_BYTES_PER_ELEMENT
```re sig
let _BYTES_PER_ELEMENT: int;
diff --git a/pages/docs/manual/v8.0.0/api/js/typed-array_uint-8-array.mdx b/pages/docs/manual/v8.0.0/api/js/typed-array_uint-8-array.mdx
index d785b66e9..0804a9979 100644
--- a/pages/docs/manual/v8.0.0/api/js/typed-array_uint-8-array.mdx
+++ b/pages/docs/manual/v8.0.0/api/js/typed-array_uint-8-array.mdx
@@ -314,7 +314,7 @@ let some: ((. elt) => bool, t) => bool;
let somei: ((. elt, int) => bool, t) => bool;
```
-## _BYTES_PER_ELEMENT
+## \_BYTES_PER_ELEMENT
```re sig
let _BYTES_PER_ELEMENT: int;
diff --git a/pages/docs/manual/v8.0.0/api/js/typed-array_uint-8-clamped-array.mdx b/pages/docs/manual/v8.0.0/api/js/typed-array_uint-8-clamped-array.mdx
index 1653dfde2..eb39c8315 100644
--- a/pages/docs/manual/v8.0.0/api/js/typed-array_uint-8-clamped-array.mdx
+++ b/pages/docs/manual/v8.0.0/api/js/typed-array_uint-8-clamped-array.mdx
@@ -314,7 +314,7 @@ let some: ((. elt) => bool, t) => bool;
let somei: ((. elt, int) => bool, t) => bool;
```
-## _BYTES_PER_ELEMENT
+## \_BYTES_PER_ELEMENT
```re sig
let _BYTES_PER_ELEMENT: int;
diff --git a/pages/docs/manual/v8.0.0/api/js/types.mdx b/pages/docs/manual/v8.0.0/api/js/types.mdx
index 4ccce8b2b..2d3965e65 100644
--- a/pages/docs/manual/v8.0.0/api/js/types.mdx
+++ b/pages/docs/manual/v8.0.0/api/js/types.mdx
@@ -37,6 +37,7 @@ type function_val;
```
## t
+
```re sig
type t('a) =
| Undefined: t(undefined_val)
diff --git a/pages/docs/manual/v8.0.0/array-and-list.mdx b/pages/docs/manual/v8.0.0/array-and-list.mdx
index 229c4a078..598fe9cda 100644
--- a/pages/docs/manual/v8.0.0/array-and-list.mdx
+++ b/pages/docs/manual/v8.0.0/array-and-list.mdx
@@ -15,9 +15,11 @@ Arrays are our main ordered data structure. They work the same way as JavaScript
```re
let myArray = [|"hello", "world", "how are you"|];
```
+
```ml
let myArray = [|"hello"; "world"; "how are you"|]
```
+
```js
var myArray = ["hello", "world", "how are you"];
```
@@ -43,6 +45,7 @@ myArray[0] = "hey"; // now [|"hey", "world", "how are you"|]
let pushedValue = Js.Array2.push(myArray, "bye");
```
+
```ml
let myArray = [|"hello"; "world"; "how are you"|]
@@ -50,6 +53,7 @@ let firstItem = myArray(0) (* "hello" *)
let () = myArray.(0) <- "hey" (* now [|"hey"; "world"; "how are you"|] *)
```
+
```js
var myArray = ["hello", "world", "how are you"];
@@ -76,9 +80,11 @@ ReScript provides a singly linked list too. Lists are:
```re
let myList = [1, 2, 3];
```
+
```ml
let myList = [1; 2; 3]
```
+
```js
var myList = {
hd: 1,
@@ -86,9 +92,9 @@ var myList = {
hd: 2,
tl: {
hd: 3,
- tl: 0
- }
- }
+ tl: 0,
+ },
+ },
};
```
@@ -114,10 +120,12 @@ Use the spread syntax:
let myList = [1, 2, 3];
let anotherList = [0, ...myList];
```
+
```ml
let myList = [1; 2; 3]
let anotherList = 0 :: myList
```
+
```js
var myList = {
hd: 1,
@@ -125,14 +133,14 @@ var myList = {
hd: 2,
tl: {
hd: 3,
- tl: 0
- }
- }
+ tl: 0,
+ },
+ },
};
var anotherList = {
hd: 0,
- tl: myList
+ tl: myList,
};
```
@@ -157,12 +165,14 @@ let message =
| [a, ...rest] => "The head of the list is the string " ++ Js.Int.toString(a)
};
```
+
```ml
let message =
match myList with
| [] -> "This list is empty"
| a::rest -> "The head of the list is the string " ^ (Js.Int.toString a)
```
+
```js
var message = myList
? "The head of the list is the string " + (1).toString()
diff --git a/pages/docs/manual/v8.0.0/bind-to-global-js-values.mdx b/pages/docs/manual/v8.0.0/bind-to-global-js-values.mdx
index 44272b926..9d64fc58a 100644
--- a/pages/docs/manual/v8.0.0/bind-to-global-js-values.mdx
+++ b/pages/docs/manual/v8.0.0/bind-to-global-js-values.mdx
@@ -16,10 +16,12 @@ Some JS values, like `setTimeout`, live in the global scope. You can bind to the
[@bs.val] external setTimeout: (unit => unit, int) => float = "setTimeout";
[@bs.val] external clearTimeout: float => unit = "clearTimeout";
```
+
```ml
external setTimeout: (unit -> unit) -> int -> float = "setTimeout" [@@bs.val]
external clearTimeout: float -> unit = "clearTimeout" [@@bs.val]
```
+
```js
// Empty output
```
@@ -50,6 +52,7 @@ type timerId;
let id = setTimeout(() => Js.log("hello"), 100);
clearTimeout(id);
```
+
```ml
type timerId
external setTimeout: (unit -> unit) -> int -> timerId = "setTimeout" [@@bs.val]
@@ -58,6 +61,7 @@ external clearTimeout: timerId -> unit = "clearTimeout" [@@bs.val]
let id = setTimeout (fun () -> Js.log "hello") 100
let () = clearTimeout id
```
+
```js
var id = setTimeout(function (param) {
console.log("hello");
@@ -82,10 +86,12 @@ If you want to bind to a value inside a global module, e.g. `Math.random`, attac
[@bs.scope "Math"] [@bs.val] external random: unit => float = "random";
let someNumber = random();
```
+
```ml
external random : unit -> float = "random" [@@bs.scope "Math"][@@bs.val]
let someNumber = random ()
```
+
```js
var someNumber = Math.random();
```
@@ -100,10 +106,12 @@ you can bind to an arbitrarily deep object by passing a tuple to `bs.scope`:
[@bs.val] [@bs.scope ("window", "location", "ancestorOrigins")]
external length: int = "length";
```
+
```ml
external length: int = "length"
[@@bs.val][@@bs.scope ("window", "location", "ancestorOrigins")]
```
+
```js
// Empty output
```
@@ -126,11 +134,13 @@ switch ([%external __DEV__]) {
| None => Js.log("production mode")
};
```
+
```ml
let () = match [%external __DEV__] with
| Some _ -> Js.log "dev mode"
| None -> Js.log "production mode"
```
+
```js
var match = typeof __DEV__ === "undefined" ? undefined : __DEV__;
@@ -155,13 +165,15 @@ switch ([%external __filename]) {
| None => Js.log("non-node environment")
};
```
+
```ml
let () = match [%external __filename] with
| Some f -> Js.log f
| None -> Js.log "non-node environment"
```
+
```js
-var match = typeof (__filename) === "undefined" ? undefined : (__filename);
+var match = typeof __filename === "undefined" ? undefined : __filename;
if (match !== undefined) {
console.log(match);
diff --git a/pages/docs/manual/v8.0.0/bind-to-js-function.mdx b/pages/docs/manual/v8.0.0/bind-to-js-function.mdx
index 3aed460ca..09b23d5e5 100644
--- a/pages/docs/manual/v8.0.0/bind-to-js-function.mdx
+++ b/pages/docs/manual/v8.0.0/bind-to-js-function.mdx
@@ -15,11 +15,13 @@ Binding a JS function is like binding any other value:
[@bs.module "path"] external dirname: string => string = "dirname";
let root = dirname("/User/github"); // returns "User"
```
+
```ml
(* Import nodejs' path.dirname *)
external dirname: string -> string = "dirname" [@@bs.module "path"]
let root = dirname "/User/github" (* returns "User" *)
```
+
```js
var Path = require("path");
var root = Path.dirname("/User/github");
@@ -37,10 +39,10 @@ ReScript has [labeled arguments](function.md#labeled-arguments) (that can also b
// MyGame.js
function draw(x, y, border) {
- // suppose `border` is optional and defaults to false
+ // suppose `border` is optional and defaults to false
}
-draw(10, 20)
-draw(20, 20, true)
+draw(10, 20);
+draw(20, 20, true);
```
It'd be nice if on ReScript's side, we can bind & call `draw` while labeling things a bit:
@@ -54,6 +56,7 @@ external draw: (~x: int, ~y: int, ~border: bool=?, unit) => unit = "draw";
draw(~x=10, ~y=20, ~border=true, ());
draw(~x=10, ~y=20, ());
```
+
```ml
external draw: x:int -> y:int -> ?border:bool -> unit -> unit = "draw"
[@@bs.module "MyGame"]
@@ -61,6 +64,7 @@ external draw: x:int -> y:int -> ?border:bool -> unit -> unit = "draw"
let () = draw ~x:10 ~y:20 ~border:true ()
let () = draw ~x:10 ~y:20 ()
```
+
```js
var MyGame = require("MyGame");
@@ -85,6 +89,7 @@ external draw: (~x: int, ~y: int, ~border: bool=?, unit) => unit = "draw";
draw(~x=10, ~y=20, ());
draw(~y=20, ~x=10, ());
```
+
```ml
external draw: x:int -> y:int -> ?border:bool -> unit -> unit = "draw"
[@@bs.module "MyGame"]
@@ -92,6 +97,7 @@ external draw: x:int -> y:int -> ?border:bool -> unit -> unit = "draw"
let () = draw ~x:10 ~y:20 ()
let () = draw ~y:20 ~x:10 ()
```
+
```js
var MyGame = require("MyGame");
@@ -114,6 +120,7 @@ type document; // abstract type for a document object
let el = getElementById(doc, "myId");
```
+
```ml
type document (* abstract type for a document object *)
external getElementById: document -> string -> Dom.element = "getElementById" [@@bs.send]
@@ -121,6 +128,7 @@ external doc: document = "document" [@@bs.val ]
let el = getElementById doc "myId"
```
+
```js
var el = document.getElementById("myId");
```
@@ -145,12 +153,14 @@ external join: array(string) => string = "join";
let v = join([|"a", "b"|]);
```
+
```ml
external join : string array -> string = "join"
[@@bs.module "path"][@@bs.variadic]
let v = join [|"a"; "b"|]
```
+
```js
var Path = require("path");
var v = Path.join("a", "b");
@@ -175,11 +185,13 @@ If you can exhaustively enumerate the many forms an overloaded JS function can t
[@bs.module "MyGame"] external drawDog: (~giveName: string) => unit = "draw";
[@bs.module "MyGame"] external draw: (string, ~useRandomAnimal: bool) => unit = "draw";
```
+
```ml
external drawCat: unit -> unit = "draw" [@@bs.module "MyGame"]
external drawDog: giveName:string -> unit = "draw" [@@bs.module "MyGame"]
external draw: string -> useRandomAnimal:bool -> unit = "draw" [@@bs.module "MyGame"]
```
+
```js
// Empty output
```
@@ -221,6 +233,7 @@ external padLeft: (
padLeft("Hello World", `Int(4));
padLeft("Hello World", `Str("Message from ReScript: "));
```
+
```ml
external padLeft:
string ->
@@ -233,6 +246,7 @@ external padLeft:
let _ = padLeft "Hello World" (`Int 4)
let _ = padLeft "Hello World" (`Str "Message from ReScript: ")
```
+
```js
padLeft("Hello World", 4);
padLeft("Hello World", "Message from ReScript: ");
@@ -260,6 +274,7 @@ external readFileSync: (
readFileSync(~name="xx.txt", `useAscii);
```
+
```ml
external readFileSync:
name:string ->
@@ -272,6 +287,7 @@ external readFileSync:
let _ = readFileSync ~name:"xx.txt" `useAscii
```
+
```js
var Fs = require("fs");
Fs.readFileSync("xx.txt", "ascii");
@@ -299,6 +315,7 @@ external testIntType: (
=> int = "testIntType";
testIntType(`inBinary);
```
+
```ml
external testIntType: (([
| `onClosed
@@ -309,6 +326,7 @@ external testIntType: (([
let _ = testIntType `inBinary
```
+
```js
testIntType(21);
```
@@ -341,6 +359,7 @@ let register = rl =>
->on(`close(event => ()))
->on(`line(line => Js.log(line)));
```
+
```ml
type readline
@@ -357,11 +376,12 @@ let register rl =
|. on (`close (fun event -> ()))
|. on (`line (fun line -> Js.log line))
```
+
```js
function register(rl) {
return rl
- .on("close", function($$event) {})
- .on("line", function(line) {
+ .on("close", function ($$event) {})
+ .on("line", function (line) {
console.log(line);
});
}
@@ -388,6 +408,7 @@ processOnExit(exitCode =>
Js.log("error code: " ++ Js.Int.toString(exitCode))
);
```
+
```ml
external processOnExit:
(_ [@bs.as "exit"]) ->
@@ -399,6 +420,7 @@ let () = processOnExit (fun exitCode ->
Js.log ("error code: " ^ (Js.Int.toString exitCode))
)
```
+
```js
process.on("exit", function (exitCode) {
console.log("error code: " + exitCode.toString());
@@ -407,7 +429,7 @@ process.on("exit", function (exitCode) {
-The `[@bs.as "exit"]` and the placeholder `_` argument together indicates that you want the first argument to compile to the string `"exit"`. You can also use any JSON literal with `bs.as`: `` [@bs.as {json|true|json}] ``, `` [@bs.as {json|{"name": "John"}|json}] ``, etc.
+The `[@bs.as "exit"]` and the placeholder `_` argument together indicates that you want the first argument to compile to the string `"exit"`. You can also use any JSON literal with `bs.as`: `[@bs.as {json|true|json}]`, `[@bs.as {json|{"name": "John"}|json}]`, etc.
## Curry & Uncurry
@@ -422,6 +444,7 @@ let add: (int, int, int) => int;
let addFive: (int, int) => int;
let twelve: int;
```
+
```mli
val add: (int * int * int) => int
val addFive: (int * int) => int
@@ -460,12 +483,14 @@ type timerId;
let id = setTimeout((.) => Js.log("hello"), 1000);
```
+
```ml
type timerId
external setTimeout: ((unit -> unit) [@bs]) -> int -> timerId = "setTimeout" [@@bs.val]
let id = setTimeout ((fun () -> Js.log "hello") [@bs]) 1000
```
+
```js
var id = setTimeout(function () {
console.log("hello");
@@ -492,10 +517,12 @@ Then try `@bs.uncurry`:
[@bs.send] external map: (array('a), [@bs.uncurry] ('a => 'b)) => array('b) = "map";
map([|1, 2, 3|], x => x + 1);
```
+
```ml
external map: 'a array -> (('a -> 'b) [@bs.uncurry]) -> 'b array = "map" [@@bs.send]
let _ = map [|1; 2; 3|] (fun x -> x + 1)
```
+
```js
// Empty output
```
@@ -509,9 +536,9 @@ In general, `bs.uncurry` is recommended; the compiler will do lots of optimizati
Many JS libraries have callbacks which rely on this (the source), for example:
```js
-x.onload = function(v) {
- console.log(this.response + v)
-}
+x.onload = function (v) {
+ console.log(this.response + v);
+};
```
Here, `this` would point to `x` (actually, it depends on how `onload` is called, but we digress). It's not correct to declare `x.onload` of type `(. unit) -> unit`. Instead, we introduced a special attribute, `bs.this`, which allows us to type `x` as so:
@@ -525,6 +552,7 @@ type x;
[@bs.get] external resp: x => int = "response";
setOnload(x, [@bs.this] ((o, v) => Js.log(resp(o) + v)));
```
+
```ml
type x
external x: x = "x" [@@bs.val]
@@ -532,6 +560,7 @@ external setOnload: x -> ((x -> int -> unit) [@bs.this]) -> unit = "onload" [@@b
external resp: x -> int = "response" [@@bs.get]
let _ = setOnload x ((fun o v -> Js.log ((resp o) + v)) [@bs.this])
```
+
```js
x.onload = function (v) {
var o = this;
@@ -564,6 +593,7 @@ let test = dom => {
}
};
```
+
```ml
type element
type dom
@@ -576,6 +606,7 @@ let test dom =
| None -> 1
| Some _ui -> 2
```
+
```js
function test(dom) {
var elem = dom.getElementById("haha");
@@ -586,7 +617,6 @@ function test(dom) {
return 2;
}
}
-
```
diff --git a/pages/docs/manual/v8.0.0/bind-to-js-object.mdx b/pages/docs/manual/v8.0.0/bind-to-js-object.mdx
index ea72db842..c5952aac0 100644
--- a/pages/docs/manual/v8.0.0/bind-to-js-object.mdx
+++ b/pages/docs/manual/v8.0.0/bind-to-js-object.mdx
@@ -36,6 +36,7 @@ type person = {
let johnName = john.name;
```
+
```ml
type person = {
name: string;
@@ -47,6 +48,7 @@ external john: person = "john" [@@bs.module "MySchool"]
let johnName = john.name
```
+
```js
var MySchool = require("MySchool");
@@ -75,6 +77,7 @@ type person = {
let johnName = john##name;
```
+
```ml
type person = <
name: string;
@@ -86,6 +89,7 @@ external john: person = "john" [@@bs.module "MySchool"]
let johnName = ## john name
```
+
```js
var MySchool = require("MySchool");
@@ -105,12 +109,15 @@ type textarea;
[@bs.set] external setName: (textarea, string) => unit = "name";
[@bs.get] external getName: textarea => string = "name";
```
+
```ml
type textarea;
external setName: textarea -> string -> unit = "name" [@@bs.set]
external getName: textarea -> string = "name" [@@bs.get]
```
+
```js
+
```
@@ -129,6 +136,7 @@ let i32arr = create(3);
i32arr->set(0, 42);
Js.log(i32arr->get(0));
```
+
```ml
type t
external create: int -> t = "Int32Array" [@@bs.new]
@@ -139,6 +147,7 @@ let i32arr = create 3
let () = i32arr |. (set 0 42)
let () = Js.log (i32arr |. (get 0))
```
+
```js
var i32arr = new Int32Array(3);
i32arr[0] = 42;
@@ -168,12 +177,14 @@ type t;
let date = createDate();
```
+
```ml
type t
external createDate: unit -> t = "Date" [@@bs.new]
let date = createDate ()
```
+
```js
var date = new Date();
```
@@ -189,11 +200,13 @@ type t;
[@bs.new] [@bs.module] external book: unit => t = "Book";
let myBook = book();
```
+
```ml
type t
external book: unit -> t = "Book" [@@bs.new][@@bs.module]
let myBook = book ()
```
+
```js
var Book = require("Book");
var myBook = new Book();
diff --git a/pages/docs/manual/v8.0.0/build-overview.mdx b/pages/docs/manual/v8.0.0/build-overview.mdx
index 0d8fc9c61..8dd1ab754 100644
--- a/pages/docs/manual/v8.0.0/build-overview.mdx
+++ b/pages/docs/manual/v8.0.0/build-overview.mdx
@@ -33,6 +33,7 @@ Add `-w` to keep the built-in watcher running. Any new file change will be picke
**Note**: third-party libraries (in `node_modules`) aren't watched, as doing so may exceed the node.js watcher count limit. If you're doing quick and dirty modifications inside `node_modules`, you have to do `bsb -clean-world -make-world` to rebuild them.
**Note 3**: If you are developing across multiple devices, you may find the `-ws` configuration useful in order to have live-reloading across the network. Possible configurations are:
+
- `bsb -make-world -w -ws _` (default)
- `bsb -make-world -w -ws 0.0.0.0:9999`
- `bsb -make-world -w -ws 5000`
diff --git a/pages/docs/manual/v8.0.0/build-performance.mdx b/pages/docs/manual/v8.0.0/build-performance.mdx
index 595213534..107a7f104 100644
--- a/pages/docs/manual/v8.0.0/build-performance.mdx
+++ b/pages/docs/manual/v8.0.0/build-performance.mdx
@@ -20,7 +20,11 @@ Run the above command at your ReScript project's root; it'll spit out a JSON fil
import Image from "src/components/Image";
-
+
## Under the Hood
diff --git a/pages/docs/manual/v8.0.0/control-flow.mdx b/pages/docs/manual/v8.0.0/control-flow.mdx
index 40f557bca..195eb1a3e 100644
--- a/pages/docs/manual/v8.0.0/control-flow.mdx
+++ b/pages/docs/manual/v8.0.0/control-flow.mdx
@@ -23,6 +23,7 @@ let message = if (isMorning) {
"Hello!"
};
```
+
```ml
let message =
if isMorning then
@@ -30,6 +31,7 @@ let message =
else
"Hello!"
```
+
```js
var message = isMorning ? "Good morning!" : "Hello!";
```
@@ -45,10 +47,12 @@ if (showMenu) {
displayMenu();
};
```
+
```ml
if showMenu then
displayMenu ()
```
+
```js
if (showMenu) {
displayMenu();
@@ -68,15 +72,17 @@ if (showMenu) {
();
};
```
+
```ml
if showMenu then
displayMenu ()
else
()
```
+
```js
if (showMenu) {
- displayMenu()
+ displayMenu();
}
```
@@ -99,9 +105,11 @@ We also have ternary sugar, but **we encourage you to prefer if-else when possib
```re
let message = isMorning ? "Good morning!" : "Hello!"
```
+
```ml
(* Doesn't exist in older ML syntax *)
```
+
```js
var message = isMorning ? "Good morning!" : "Hello!";
```
@@ -121,13 +129,15 @@ for (i in startValueInclusive to endValueInclusive) {
Js.log(i);
};
```
+
```ml
for i = startValueInclusive to endValueInclusive do
Js.log i
done
```
+
```js
-for(var i = startValueInclusive; i <= endValueInclusive; ++i){
+for (var i = startValueInclusive; i <= endValueInclusive; ++i) {
console.log(i);
}
```
@@ -142,14 +152,16 @@ for (x in 1 to 3) {
Js.log(x);
};
```
+
```ml
(* prints: 1 2 3, one per line *)
for x = 1 to 3 do
Js.log x;
done
```
+
```js
-for(var x = 1; x <= 3; ++x){
+for (var x = 1; x <= 3; ++x) {
console.log(x);
}
```
@@ -165,13 +177,15 @@ for (i in startValueInclusive downto endValueInclusive) {
Js.log(i);
};
```
+
```ml
for i = startValueInclusive downto endValueInclusive do
Js.log i
done
```
+
```js
-for(var i = startValueInclusive; i >= endValueInclusive; --i){
+for (var i = startValueInclusive; i >= endValueInclusive; --i) {
console.log(i);
}
```
@@ -186,14 +200,16 @@ for (x in 3 downto 1) {
Js.log(x);
};
```
+
```ml
(* prints: 3 2 1, one per line)
for x = 3 downto 1 do
Js.log x;
done
```
+
```js
-for(var x = 3; x >= 1; --x){
+for (var x = 3; x >= 1; --x) {
console.log(x);
}
```
@@ -211,11 +227,13 @@ while (testCondition) {
// body here
};
```
+
```ml
while testCondition do
(* body here *)
done
```
+
```js
while (testCondition) {
// body here
@@ -241,6 +259,7 @@ while (!break.contents) {
};
};
```
+
```ml
let () = break <- ref false
let () = while not break.contents do
@@ -250,18 +269,19 @@ let () = while not break.contents do
Js.log "Still running"
done
```
+
```js
var $$break = {
- contents: false
+ contents: false,
};
-while(!$$break.contents) {
+while (!$$break.contents) {
if (Math.random() > 0.3) {
$$break.contents = true;
} else {
console.log("Still running");
}
-};
+}
```
diff --git a/pages/docs/manual/v8.0.0/converting-from-js.mdx b/pages/docs/manual/v8.0.0/converting-from-js.mdx
index 54cf9337c..2cf6ca1bb 100644
--- a/pages/docs/manual/v8.0.0/converting-from-js.mdx
+++ b/pages/docs/manual/v8.0.0/converting-from-js.mdx
@@ -7,6 +7,7 @@ canonical: "/docs/manual/latest/converting-from-js"
# Converting from JS
ReScript offers a unique project conversion methodology which:
+
- Ensures minimal disruption to your teammates (very important!).
- Remove the typical friction of verifying conversion's correctness and performance guarantees.
- Doesn't force you to search for pre-made binding libraries made by others. **ReScript doesn't need the equivalent of TypeScript's `DefinitelyTyped`**.
@@ -22,7 +23,7 @@ Run `npm install --save-dev bs-platform` on your project, then imitate our [New
Let's work on converting a file called `src/main.js`.
```js
-const school = require('school');
+const school = require("school");
const defaultId = 10;
@@ -54,6 +55,7 @@ function queryResult(usePayload, payload) {
}
"]
```
+
```ml
[%%raw "
const school = require('school');
@@ -69,11 +71,12 @@ function queryResult(usePayload, payload) {
}
"]
```
+
```js
// Generated by BUCKLESCRIPT, PLEASE EDIT WITH CARE
-'use strict';
+"use strict";
-const school = require('school');
+const school = require("school");
const defaultId = 10;
@@ -124,6 +127,7 @@ function queryResult(usePayload, payload) {
}
"]
```
+
```ml
let defaultId = 10
@@ -139,6 +143,7 @@ function queryResult(usePayload, payload) {
}
"]
```
+
```js
// Generated by BUCKLESCRIPT, PLEASE EDIT WITH CARE
'use strict';
@@ -180,6 +185,7 @@ let queryResult = (usePayload, payload) => {
}
};
```
+
```ml
[%%raw "
const school = require('school');
@@ -193,7 +199,9 @@ let queryResult usePayload payload =
else
school.getStudentById(defaultId)
```
+
```js
+
```
@@ -223,6 +231,7 @@ let queryResult = (usePayload, payload) => {
}
}
```
+
```ml
[%%raw "
const school = require('school');
@@ -236,7 +245,9 @@ let queryResult usePayload payload =
else
school##getStudentById defaultId
```
+
```js
+
```
@@ -258,6 +269,7 @@ let queryResult = (usePayload, payload) => {
}
}
```
+
```ml
external school: 'whatever = "school" [@@bs.module]
@@ -269,9 +281,10 @@ let queryResult usePayload payload =
else
school##getStudentById defaultId
```
+
```js
// Generated by BUCKLESCRIPT, PLEASE EDIT WITH CARE
-'use strict';
+"use strict";
var School = require("school");
@@ -324,6 +337,7 @@ let queryResult = (usePayload, payload) => {
}
}
```
+
```ml
type school
type student
@@ -342,9 +356,10 @@ let queryResult usePayload payload =
else
school |. (getStudentById defaultId)
```
+
```js
// Generated by BUCKLESCRIPT, PLEASE EDIT WITH CARE
-'use strict';
+"use strict";
var School = require("school");
@@ -366,6 +381,7 @@ exports.queryResult = queryResult;
We've:
+
- introduced an opaque types for `school` and `student` to prevent misusages their values
- typed the payload as a record with only the `student` field
- typed `getStudentById` as the sole method of `student`
diff --git a/pages/docs/manual/v8.0.0/embed-raw-javascript.mdx b/pages/docs/manual/v8.0.0/embed-raw-javascript.mdx
index cd9400144..433c71aef 100644
--- a/pages/docs/manual/v8.0.0/embed-raw-javascript.mdx
+++ b/pages/docs/manual/v8.0.0/embed-raw-javascript.mdx
@@ -21,6 +21,7 @@ function greet(m) {
}
|}];
```
+
```ml
[%%raw {|
// look ma, regular JavaScript!
@@ -30,11 +31,12 @@ function greet(m) {
}
|}]
```
+
```js
// look ma, regular JavaScript!
var message = "hello";
function greet(m) {
- console.log(m)
+ console.log(m);
}
```
@@ -58,6 +60,7 @@ let add = [%raw {|
Js.log(add(1, 2));
```
+
```ml
let add = [%raw {|
function(a, b) {
@@ -68,10 +71,11 @@ let add = [%raw {|
let () = Js.log (add 1 2)
```
+
```js
-var add = function(a, b) {
+var add = function (a, b) {
console.log("hello from raw JavaScript!");
- return a + b
+ return a + b;
};
console.log(add(1, 2));
@@ -80,6 +84,7 @@ console.log(add(1, 2));
The above code:
+
- declared a ReScript variable `add`,
- with the raw JavaScript value of a function declaration,
- then called that function in ReScript.
@@ -98,15 +103,17 @@ let f = (x, y) => {
x + y;
};
```
+
```ml
let f x y =
[%debugger ];
x + y
```
+
```js
function f(x, y) {
debugger;
- return x + y | 0;
+ return (x + y) | 0;
}
```
diff --git a/pages/docs/manual/v8.0.0/exception.mdx b/pages/docs/manual/v8.0.0/exception.mdx
index 2ecf45f94..e26a20418 100644
--- a/pages/docs/manual/v8.0.0/exception.mdx
+++ b/pages/docs/manual/v8.0.0/exception.mdx
@@ -26,6 +26,7 @@ let result =
| Not_found => 0 /* Default value if getItem throws */
};
```
+
```ml
let getItem items =
if callSomeFunctionThatThrows () then
@@ -38,6 +39,7 @@ let result =
try getItem [|1; 2; 3|] with
| Not_found -> 0 (* Default value if getItem throws *)
```
+
```js
function getItem(items) {
if (callSomeFunctionThatThrows()) {
@@ -45,7 +47,7 @@ function getItem(items) {
}
throw {
RE_EXN_ID: "Not_found",
- Error: new Error()
+ Error: new Error(),
};
}
@@ -77,24 +79,25 @@ switch (List.find(i => i === theItem, myItems)) {
| exception Not_found => Js.log("No such item found!")
};
```
+
```ml
let () = match List.find (fun i -> i == theItem) myItems with
| item -> Js.log item
| exception Not_found ->
Js.log "No such item found!"
```
+
```js
var exit = 0;
var item;
try {
- item = List.find(function(i) {
+ item = List.find(function (i) {
return i === theItem;
}, myItems);
exit = 1;
-}
-catch (raw_exn){
+} catch (raw_exn) {
var exn = Caml_js_exceptions.internalToOCamlException(raw_exn);
if (exn.RE_EXN_ID === "Not_found") {
console.log("No such item found!");
@@ -119,11 +122,13 @@ exception InputClosed(string);
// later on
raise(InputClosed("The stream has closed!"));
```
+
```ml
exception InputClosed of string
(* later on *)
raise(InputClosed "The stream has closed!")
```
+
```js
var Caml_exceptions = require("./stdlib/caml_exceptions.js");
@@ -132,7 +137,7 @@ var InputClosed = Caml_exceptions.create("MyFile.InputClosed");
throw {
RE_EXN_ID: InputClosed,
_1: "The stream has closed!",
- Error: new Error()
+ Error: new Error(),
};
```
@@ -153,6 +158,7 @@ try (someJSFunctionThatThrows()) {
}
};
```
+
```ml
let () = try someJSFunctionThatThrows () with
| Js.Exn.Error obj ->
@@ -160,6 +166,7 @@ let () = try someJSFunctionThatThrows () with
| Some m -> Js.log ("Caught a JS exception! Message: " ^ m)
| None -> ()
```
+
```js
var Js_exn = require("./stdlib/js_exn.js");
var Caml_js_exceptions = require("./stdlib/caml_js_exceptions.js");
@@ -194,10 +201,12 @@ let myTest = () => {
Js.Exn.raiseError("Hello!");
};
```
+
```ml
let myTest () =
Js.Exn.raiseError "Hello!"
```
+
```js
var Js_exn = require("./stdlib/js_exn.js");
@@ -213,9 +222,9 @@ Then you can catch it from the JS side:
```js
// after importing `myTest`...
try {
- myTest()
+ myTest();
} catch (e) {
- console.log(e.message) // "Hello!"
+ console.log(e.message); // "Hello!"
}
```
@@ -232,12 +241,14 @@ let myTest = () => {
raise(BadArgument({myMessage: "Oops!"}));
};
```
+
```ml
exception BadArgument of {myMessage: string}
let myTest () =
raise(BadArgument {myMessage = "Oops!"})
```
+
```js
var Caml_exceptions = require("./stdlib/caml_exceptions.js");
@@ -247,7 +258,7 @@ function myTest() {
throw {
RE_EXN_ID: BadArgument,
myMessage: "Oops!",
- Error: new Error()
+ Error: new Error(),
};
}
```
@@ -259,10 +270,10 @@ Then, in your JS:
```js
// after importing `myTest`...
try {
- myTest()
+ myTest();
} catch (e) {
- console.log(e.myMessage) // "Oops!"
- console.log(e.Error.stack) // the stack trace
+ console.log(e.myMessage); // "Oops!"
+ console.log(e.Error.stack); // the stack trace
}
```
@@ -285,12 +296,14 @@ try (someOtherJSFunctionThatThrows()) {
| Js.Exn.Error(obj) => ... // catch the JS exception
};
```
+
```ml
try someOtherJSFunctionThatThrows() with
| Not_found -> ... (* catch a ReScript exception *)
| Invalid_argument _ -> ... (* catch a second ReScript exception *)
| Js.Exn.Error obj -> ... (* catch the JS exception *)
```
+
```js
var Js_exn = require("./stdlib/js_exn.js");
var Caml_js_exceptions = require("./stdlib/caml_js_exceptions.js");
diff --git a/pages/docs/manual/v8.0.0/external.mdx b/pages/docs/manual/v8.0.0/external.mdx
index dea30c09c..153fb7857 100644
--- a/pages/docs/manual/v8.0.0/external.mdx
+++ b/pages/docs/manual/v8.0.0/external.mdx
@@ -9,6 +9,7 @@ canonical: "/docs/manual/latest/external"
`external` is the primary ReScript feature for bringing in and using JavaScript values.
`external` is like a let binding, but:
+
- The right side of `=` isn't a value; it's the name of the JS value you're referring to.
- The type for the binding is mandatory, since we need to know what the type of that JS value is.
- Can only exist at the top level of a file or module.
@@ -18,9 +19,11 @@ canonical: "/docs/manual/latest/external"
```re
[@bs.val] external setTimeout: (unit => unit, int) => float = "setTimeout";
```
+
```ml
external setTimeout: (unit -> unit) -> int -> float = "setTimeout" [@@bs.val]
```
+
```js
// Empty output
```
@@ -59,6 +62,7 @@ let loc = document##location;
// set a property
document##location##href = "rescript-lang.org";
```
+
```ml
(* The type of document is just some random type 'a *)
(* that we won't bother to specify *)
@@ -75,8 +79,9 @@ let loc = document##location
(* set a property *)
document##location##href = "rescript-lang.org"
```
+
```js
-document.addEventListener("mouseup", function(_event) {
+document.addEventListener("mouseup", function (_event) {
console.log("clicked!");
});
diff --git a/pages/docs/manual/v8.0.0/function.mdx b/pages/docs/manual/v8.0.0/function.mdx
index 49c778c24..4861bb1d4 100644
--- a/pages/docs/manual/v8.0.0/function.mdx
+++ b/pages/docs/manual/v8.0.0/function.mdx
@@ -15,9 +15,11 @@ ReScript functions are declared with an arrow and return an expression, just lik
```re
let greet = (name) => "Hello " ++ name;
```
+
```ml
let greet name = "Hello " ^ name
```
+
```js
function greet(name) {
return "Hello " + name;
@@ -33,9 +35,11 @@ This declares a function and assigns to it the name `greet`, which you can call
```re
greet("world!"); // "Hello world!"
```
+
```ml
greet "world!" (* "Hello world!" *)
```
+
```js
greet("world!");
```
@@ -50,13 +54,15 @@ Multi-arguments functions have arguments separated by comma:
let add = (x, y, z) => x + y + z;
add(1, 2, 3); // 6
```
+
```ml
let add x y z = (x + y) + z
let () = add 1 2 3
```
+
```js
function add(x, y, z) {
- return (x + y | 0) + z | 0;
+ return (((x + y) | 0) + z) | 0;
}
```
@@ -72,11 +78,13 @@ let greetMore = (name) => {
part1 ++ " " ++ name;
};
```
+
```ml
let greetMore name =
let part1 = "Hello" in
part1 ^ " " ^ name
```
+
```js
function greetMore(name) {
return "Hello " + name;
@@ -100,12 +108,14 @@ let addCoordinates = (x, y) => {
// ...
addCoordinates(5, 6); // which is x, which is y?
```
+
```ml
let addCoordinates x t =
(* use x and y here *)
(* ... *)
addCoordinates 5 6 (* which is x, which is y? *)
```
+
```js
function addCoordinates(x, y) {
// use x and y here
@@ -127,12 +137,14 @@ let addCoordinates = (~x, ~y) => {
// ...
addCoordinates(~x=5, ~y=6);
```
+
```ml
let addCoordinates ~x ~y =
(* use x and y here *)
(* ... *)
addCoordinates ~x=5 ~y=6
```
+
```js
function addCoordinates(x, y) {
// use x and y here
@@ -150,9 +162,11 @@ You can provide the arguments in **any order**:
```re
addCoordinates(~y=6, ~x=5);
```
+
```ml
addCoordinates ~y=6 ~x=5
```
+
```js
addCoordinates(5, 6);
```
@@ -172,6 +186,7 @@ let drawCircle = (~radius as r, ~color as c) => {
drawCircle(~radius=10, ~color="red");
```
+
```ml
let drawCircle ~radius:r ~color:c =
setColor c;
@@ -180,6 +195,7 @@ let drawCircle ~radius:r ~color:c =
let () = drawCircle ~radius:10 ~color:"red"
```
+
```js
function drawCircle(r, c) {
setColor(c);
@@ -202,10 +218,12 @@ let drawCircle = (~radius as r: int, ~color as c: string) => {
// code here
};
```
+
```ml
let drawCircle ~radius:(r : int) ~color:(c : string) =
(* code *)
```
+
```js
function drawCircle(r, c) {
// code here
@@ -230,6 +248,7 @@ let drawCircle = (~color, ~radius=?, ()) => {
};
};
```
+
```ml
(* radius can be omitted *)
let drawCircle ~color ?radius () =
@@ -238,6 +257,7 @@ let drawCircle ~color ?radius () =
| None -> startAt 1 1
| Some r_ -> startAt r_ r_
```
+
```js
var Caml_option = require("./stdlib/caml_option.js");
@@ -277,6 +297,7 @@ let drawCircle: (~color: color, ~radius: int=?, unit) => unit =
};
};
```
+
```ml
let drawCircle: color:color -> ?radius:int -> unit -> unit =
fun ~color:(color : color) ?radius:(radius : int option) () ->
@@ -285,6 +306,7 @@ let drawCircle: color:color -> ?radius:int -> unit -> unit =
| None -> startAt 1 1
| Some r_ -> startAt r_ r_
```
+
```js
function drawCircle(color, radius, param) {
setColor(color);
@@ -317,18 +339,21 @@ let result =
| Some(r) => drawCircle(~color, ~radius=r, ())
};
```
+
```ml
let result =
match payloadRadius with
| None -> drawCircle ~color ()
| Some r -> drawCircle ~color ~radius:r ()
```
+
```js
var r = payloadRadius;
-var result = r !== undefined
- ? drawCircle(color, Caml_option.valFromOption(r), undefined)
- : drawCircle(color, undefined);
+var result =
+ r !== undefined
+ ? drawCircle(color, Caml_option.valFromOption(r), undefined)
+ : drawCircle(color, undefined);
```
@@ -340,9 +365,11 @@ This quickly gets tedious. We provide a shortcut:
```re
let result = drawCircle(~color, ~radius=?payloadRadius, ());
```
+
```ml
let result = drawCircle ~color ?radius:payloadRadius ()
```
+
```js
var result = drawCircle(1, undefined, undefined);
```
@@ -363,11 +390,13 @@ let drawCircle = (~radius=1, ~color, ()) => {
startAt(radius, radius);
};
```
+
```ml
let drawCircle ?(radius=1) ~color () =
setColor color;
startAt radius radius
```
+
```js
function drawCircle(radiusOpt, color, param) {
var radius = radiusOpt !== undefined ? radiusOpt : 1;
@@ -387,15 +416,17 @@ ReScript chooses the sane default of preventing a function to be called recursiv
```re
let rec neverTerminate = () => neverTerminate()
```
+
```ml
let rec neverTerminate () = neverTerminate ()
```
+
```js
function neverTerminate(_param) {
- while(true) {
+ while (true) {
_param = undefined;
- continue ;
- };
+ continue;
+ }
}
```
@@ -414,6 +445,7 @@ let rec listHas = (list, item) =>
| [a, ...rest] => a === item || listHas(rest, item)
};
```
+
```ml
(* Recursively check every item on the list until one equals the `item` *)
(* argument. If a match is found, return `true`, otherwise return `false` *)
@@ -423,9 +455,10 @@ let rec listHas list item =
| [] -> false
| a::rest -> (a == item) || (listHas rest item)
```
+
```js
function listHas(_list, item) {
- while(true) {
+ while (true) {
var list = _list;
if (!list) {
return false;
@@ -434,8 +467,8 @@ function listHas(_list, item) {
return true;
}
_list = list.tl;
- continue ;
- };
+ continue;
+ }
}
```
@@ -454,23 +487,25 @@ Mutually recursive functions start like a single recursive function using the
let rec callSecond = () => callFirst()
and callFirst = () => callSecond();
```
+
```ml
let rec callSecond () = callFirst ()
and callFirst () = callSecond ()
```
+
```js
function callSecond(_param) {
- while(true) {
+ while (true) {
_param = undefined;
- continue ;
- };
+ continue;
+ }
}
function callFirst(_param) {
- while(true) {
+ while (true) {
_param = undefined;
- continue ;
- };
+ continue;
+ }
}
```
@@ -487,13 +522,15 @@ let add = (. x, y) => x + y;
add(. 1, 2);
```
+
```ml
let add = (fun x y -> x + y) [@bs]
let () = add 1 2 [@bs]
```
+
```js
function add(x, y) {
- return x + y | 0;
+ return (x + y) | 0;
}
add(1, 2);
@@ -536,6 +573,7 @@ let add = (~first as x=?, ~second as y=?) => switch (x) {...};
// with punning
let add = (~first=?, ~second=?) => switch (first) {...};
```
+
```ml
(* anonymous function *)
fun x y -> 1
@@ -587,6 +625,7 @@ let add = (~first as x: option(int)=?, ~second as y: option(int)=?) : int => swi
// Inside the function, `first` and `second` are `option(int)`.
let add = (~first: option(int)=?, ~second: option(int)=?) : int => switch (first) {...};
```
+
```ml
(* anonymous function *)
fun (x: int) (y: int) : int -> 1
@@ -627,6 +666,7 @@ add(~first=?Some(1), ~second=?Some(2));
// with punning
add(~first?, ~second?);
```
+
```ml
add x y
@@ -663,6 +703,7 @@ add(~first=1: int, ~second=2: int);
add(~first=?Some(1): option(int), ~second=?Some(2): option(int));
// no punning sugar when you want to type annotate
```
+
```ml
(* labeled *)
add ~first:(1: int) ~second:(2: int)
@@ -692,6 +733,7 @@ type add = (~first: int, ~second: int) => int;
// labeled
type add = (~first: int=?, ~second: int=?, unit) => int;
```
+
```ml
(* first arg type, second arg type, return type *)
type add = int -> int -> int
@@ -714,6 +756,7 @@ To annotate a function from the implementation file (`.re`) in your interface fi
```re
let add: (int, int) => int;
```
+
```ml
val add: int -> int -> int
```
diff --git a/pages/docs/manual/v8.0.0/generate-converters-accessors.mdx b/pages/docs/manual/v8.0.0/generate-converters-accessors.mdx
index 095404569..418eb3e8e 100644
--- a/pages/docs/manual/v8.0.0/generate-converters-accessors.mdx
+++ b/pages/docs/manual/v8.0.0/generate-converters-accessors.mdx
@@ -44,14 +44,14 @@ type action =
```js
function submit(param_0) {
- return /* Submit */[param_0];
+ return /* Submit */ [param_0];
}
-var click = /* Click */0;
+var click = /* Click */ 0;
-var cancel = /* Cancel */1;
+var cancel = /* Cancel */ 1;
-exports.click = click;
+exports.click = click;
exports.submit = submit;
exports.cancel = cancel;
```
@@ -61,6 +61,7 @@ exports.cancel = cancel;
Variants constructors with payloads generate functions, payload-less constructors generate plain integers (the internal representation of variants).
**Note**:
+
- The generated accessors are lower-cased.
- You can now use these helpers on the JavaScript side! But don't rely on their actual values please.
@@ -89,7 +90,6 @@ Please note that in case you just want to _pipe a payload into a constructor_, y
Use `[@bs.deriving accessors]` on a record type to create accessors for its record field names.
-
```reason
@@ -126,11 +126,11 @@ function name(param) {
var pets = [
{
- name: "bob"
+ name: "bob",
},
{
- name: "bob2"
- }
+ name: "bob2",
+ },
];
console.log(Belt_Array.map(pets, name).join("&"));
@@ -146,7 +146,6 @@ console.log(Belt_Array.map(pets, name).join("&"));
Use `[@bs.deriving jsConverter]` on a record type to create convertion functions between records / JS object runtime values.
-
```reason
@@ -308,9 +307,9 @@ type fruit =
```ocaml
type fruit =
- | Apple
- | Orange
- | Kiwi
+ | Apple
+ | Orange
+ | Kiwi
| Watermelon [@@bs.deriving jsConverter]
```
@@ -362,7 +361,7 @@ switch (fruitFromJs(100)) {
```ocaml
type fruit =
- | Apple
+ | Apple
| Orange [@bs.as 10]
| Kiwi [@bs.as 100]
| Watermelon [@@bs.deriving jsConverter]
@@ -394,7 +393,7 @@ type fruit =
```ocaml
type fruit =
- | Apple
+ | Apple
| Kiwi [@bs.as 100]
| Watermelon [@@bs.deriving { jsConverter = newType }]
```
@@ -442,7 +441,7 @@ let error = fruitFromJs(100); /* nope, can't take a random int */
```ocaml
type fruit =
- | Apple
+ | Apple
| Kiwi [@bs.as 100]
| Watermelon [@@bs.deriving { jsConverter = newType }]
@@ -480,7 +479,7 @@ let kiwiString = fruitToJs(`Kiwi); /* "miniCoconut" */
```ocaml
type fruit = [
- | `Apple
+ | `Apple
| `Kiwi [@bs.as "miniCoconut"]
| `Watermelon
] [@@bs.deriving jsConverter]
@@ -495,8 +494,8 @@ You can also use `[@bs.deriving {jsConverter: newType}]` to generate abstract ty
## Convert Record Type to Abstract Record
-> **Note**: For ReScript >= v7, we recommend using [plain records to compile to JS objects](bind-to-js-object#bind-to-record-like-js-objects).
-> This feature might still be useful for certain scenarios, but the ergonomics might be worse
+> **Note**: For ReScript >= v7, we recommend using [plain records to compile to JS objects](bind-to-js-object#bind-to-record-like-js-objects).
+> This feature might still be useful for certain scenarios, but the ergonomics might be worse
Use `[@bs.deriving abstract]` on a record type to expand the type into a creation, and a set of getter / setter functions for fields and methods.
@@ -553,7 +552,7 @@ let joe = person ~name:"Joe" ~age:20 ~job:"teacher"
var joe = {
name: "Joe",
age: 20,
- job: "teacher"
+ job: "teacher",
};
```
@@ -589,7 +588,7 @@ let d = data ~type_:"message" ~ariaLabel:"hello"
```js
var d = {
type: "message",
- "aria-label": "hello"
+ "aria-label": "hello",
};
```
@@ -625,7 +624,7 @@ let joe = person ~age:20 ~job:"teacher" ()
```js
var joe = {
age: 20,
- job: "teacher"
+ job: "teacher",
};
```
@@ -902,7 +901,7 @@ let cat = Cat.t(~name="Snowball", ~isLazy=true);
/* We can use each nameGet function separately now */
let shoutPersonName = Person.(person->nameGet->Js.String.toUpperCase);
-/* Note how we use a local open Cat.([some expression]) to
+/* Note how we use a local open Cat.([some expression]) to
get access to Cat's nameGet function */
let whisperCatName = Cat.(cat->nameGet->Js.String.toLowerCase);
```
@@ -936,7 +935,6 @@ This is very handy because you can make some of those labelled parameters option
For example, suppose you need a JavaScript object like this:
-
```js
var homeRoute = {
method: "GET",
@@ -948,7 +946,6 @@ var homeRoute = {
But only the first three fields are required; the options field is optional. You can declare the binding function like so:
-
```reason
diff --git a/pages/docs/manual/v8.0.0/import-export.mdx b/pages/docs/manual/v8.0.0/import-export.mdx
index 6700304d0..2cb57673a 100644
--- a/pages/docs/manual/v8.0.0/import-export.mdx
+++ b/pages/docs/manual/v8.0.0/import-export.mdx
@@ -16,13 +16,15 @@ Unlike JavaScript, ReScript doesn't have or need import statements:
// Inside School.re
let studentMessage = Student.message;
```
+
```ml
(* Inside School.re *)
let studentMessage = Student.message
```
+
```js
var Student = require("./Student.bs");
-var studentMessage = Student.message
+var studentMessage = Student.message;
```
diff --git a/pages/docs/manual/v8.0.0/import-from-export-to-js.mdx b/pages/docs/manual/v8.0.0/import-from-export-to-js.mdx
index 495ffcf1f..07af4500d 100644
--- a/pages/docs/manual/v8.0.0/import-from-export-to-js.mdx
+++ b/pages/docs/manual/v8.0.0/import-from-export-to-js.mdx
@@ -21,11 +21,13 @@ Use the `bs.module` [external](external.md):
[@bs.module "path"] external dirname: string => string = "dirname";
let root = dirname("/User/github"); // returns "User"
```
+
```ml
(* Import nodejs' path.dirname *)
external dirname: string -> string = "dirname" [@@bs.module "path"]
let root = dirname "/User/github" (* returns "User" *)
```
+
```js
var Path = require("path");
var root = Path.dirname("/User/github");
@@ -51,10 +53,12 @@ By omitting the string argument to `bs.module`, you bind to the whole JS module:
[@bs.module] external leftPad: string => int => string = "./leftPad";
let paddedResult = leftPad("hi", 5);
```
+
```ml
external leftPad: string -> int -> string = "./leftPad" [@@bs.module]
let paddedResult = leftPad "hi" 5
```
+
```js
var LeftPad = require("./leftPad");
var paddedResult = LeftPad("hi", 5);
@@ -72,10 +76,12 @@ If your JS project is using ES6, you're likely using Babel to compile it to regu
[@bs.module "./student"] external studentName: string = "default";
Js.log(studentName);
```
+
```ml
external studentName: string = "default" [@@bs.module "./student"]
let () = Js.log studentName
```
+
```js
var Student = require("./student");
console.log(Student.default);
@@ -105,7 +111,7 @@ export default name = "Al";
```js
// teacher.js
-import studentName from 'student.js';
+import studentName from "student.js";
```
Technically, since a ReScript file maps to a module, there's no such thing as "default" export, only named ones. However, we've made an exception to support default module when you do the following:
@@ -116,10 +122,12 @@ Technically, since a ReScript file maps to a module, there's no such thing as "d
/* FavoriteStudent.re */
let default = "Bob";
```
+
```re
(* FavoriteStudent.re *)
let default = "Bob"
```
+
```js
var $$default = "Bob";
@@ -134,11 +142,11 @@ You can then require the default as normal JS side:
```js
// teacher2.js
-import studentName from 'FavoriteStudent.js';
+import studentName from "FavoriteStudent.js";
```
**Note**: the above JS snippet _only_ works if you're using that ES6 import/export syntax in JS. If you're still using `require`, you'd need to do:
```js
-let studentName = require('FavoriteStudent').default;
+let studentName = require("FavoriteStudent").default;
```
diff --git a/pages/docs/manual/v8.0.0/interop-cheatsheet.mdx b/pages/docs/manual/v8.0.0/interop-cheatsheet.mdx
index 2dda1acc1..0dd7dbfff 100644
--- a/pages/docs/manual/v8.0.0/interop-cheatsheet.mdx
+++ b/pages/docs/manual/v8.0.0/interop-cheatsheet.mdx
@@ -16,13 +16,15 @@ canonical: "/docs/manual/latest/interop-cheatsheet"
let add = [%raw "(a, b) => a + b"];
[%%raw "const a = 1"];
```
+
```ml
let add = [%raw "(a, b) => a + b"]
[%%raw "const a = 1"]
```
+
```js
-var add = ((a, b) => a + b);
-const a = 1
+var add = (a, b) => a + b;
+const a = 1;
```
@@ -34,9 +36,11 @@ const a = 1
```re
[@bs.val] external setTimeout: (unit => unit, int) => float = "setTimeout";
```
+
```ml
external setTimeout: (unit -> unit) -> int -> float = "setTimeout" [@@bs.val]
```
+
```js
// Empty output
```
@@ -56,6 +60,7 @@ let someNumber = random();
[@bs.val] [@bs.scope ("window", "location", "ancestorOrigins")]
external length: int = "length";
```
+
```ml
external random: unit -> float = "random"
[@@bs.val][@@bs.scope "Math"]
@@ -65,6 +70,7 @@ let someNumber = random ()
external length: int = "length"
[@@bs.val][@@bs.scope ("window", "location", "ancestorOrigins")]
```
+
```js
var someNumber = Math.random();
```
@@ -79,10 +85,12 @@ var someNumber = Math.random();
let a = Some(5); // compiles to 5
let b = None; // compiles to undefined
```
+
```ml
let a = Some 5 (* compiles to 5 *)
let b = None (* compiles to undefined *)
```
+
```js
var a = 5;
var b;
@@ -101,6 +109,7 @@ let result1: Js.Nullable.t(string) = Js.Nullable.return("hello");
let result2: Js.Nullable.t(int) = Js.Nullable.fromOption(Some(10));
let result3: option(int) = Js.Nullable.toOption(Js.Nullable.return(10));
```
+
```ml
let jsNull = Js.Nullable.null
let jsUndefined = Js.Nullable.undefined
@@ -108,6 +117,7 @@ let result1: string Js.Nullable.t = Js.Nullable.return "hello"
let result2: int Js.Nullable.t = Js.Nullable.fromOption (Some 10)
let result3: int option = Js.Nullable.toOption (Js.Nullable.return 10)
```
+
```js
var Caml_option = require("./stdlib/caml_option.js");
var Js_null_undefined = require("./stdlib/js_null_undefined.js");
@@ -141,6 +151,7 @@ var result3 = Caml_option.nullable_to_opt(10);
->filter(a => a mod 2 == 0)
->Js.log;
```
+
```ml
external map: 'a array -> ('a -> 'b) -> 'b array = "map" [@@bs.send]
external filter: 'a array -> ('a -> 'b) -> 'b array = "filter" [@@bs.send]
@@ -149,6 +160,7 @@ external filter: 'a array -> ('a -> 'b) -> 'b array = "filter" [@@bs.send]
|. filter(fun a -> a mod 2 = 0)
|. Js.log
```
+
```js
console.log(
[1, 2, 3]
@@ -157,7 +169,7 @@ console.log(
})
.filter(function (a) {
return a % 2 === 0;
- })
+ }),
);
```
@@ -171,10 +183,12 @@ console.log(
[@bs.module "path"] [@bs.variadic]
external join: array(string) => string = "join";
```
+
```ml
external join: string array -> string = "join"
[@@bs.module "path"][@@bs.variadic]
```
+
```js
// Empty output
```
@@ -189,10 +203,12 @@ external join: string array -> string = "join"
[@bs.module "Drawing"] external drawCat: unit => unit = "draw";
[@bs.module "Drawing"] external drawDog: (~giveName: string) => unit = "draw";
```
+
```ml
external drawCat: unit -> unit = "draw" [@@bs.module "Drawing"]
external drawDog: giveName:string -> unit = "draw" [@@bs.module "Drawing"]
```
+
```js
// Empty output
```
@@ -214,6 +230,7 @@ external padLeft: (
padLeft("Hello World", `Int(4));
padLeft("Hello World", `Str("Message from ReScript: "));
```
+
```ml
external padLeft:
string ->
@@ -226,6 +243,7 @@ external padLeft:
let _ = padLeft "Hello World" (`Int 4)
let _ = padLeft "Hello World" (`Str "Message from ReScript: ")
```
+
```js
padLeft("Hello World", 4);
padLeft("Hello World", "Message from ReScript: ");
@@ -248,11 +266,13 @@ external convertToFloat: int => float = "%identity";
let age = 10;
let gpa = 2.1 +. convertToFloat(age);
```
+
```ml
external convertToFloat: int => float = "%identity"
let age = 10
let gpa = 2.1 +. (convertToFloat age)
```
+
```js
var age = 10;
var gpa = 2.1 + 10;
diff --git a/pages/docs/manual/v8.0.0/json.mdx b/pages/docs/manual/v8.0.0/json.mdx
index 3e21ab7b0..613df25a3 100644
--- a/pages/docs/manual/v8.0.0/json.mdx
+++ b/pages/docs/manual/v8.0.0/json.mdx
@@ -23,6 +23,7 @@ external parseIntoMyData: string => data = "parse";
let result = parseIntoMyData({|{"names": ["Luke", "Christine"]}|});
let name1 = result.names[0];
```
+
```ml
(* declare the shape of the json you're binding to *)
type data = {names: string array}
@@ -34,8 +35,9 @@ external parseIntoMyData: string -> data = "parse"
let result = parseIntoMyData {|{"names": ["Luke", "Christine"]}|}
let name1 = (result.names).(0)
```
+
```js
-var result = JSON.parse("{\"names\": [\"Luke\", \"Christine\"]}");
+var result = JSON.parse('{"names": ["Luke", "Christine"]}');
var name1 = result.names[0];
```
@@ -52,14 +54,13 @@ Use `Js.Json.stringify`:
```re
Js.log(Js.Json.stringifyAny([|"Amy", "Joe"|]));
```
+
```ml
Js.log (Js.Json.stringifyAny [|"Amy"; "Joe"|])
```
+
```js
-console.log(JSON.stringify([
- "Amy",
- "Joe"
-]));
+console.log(JSON.stringify(["Amy", "Joe"]));
```
diff --git a/pages/docs/manual/v8.0.0/jsx.mdx b/pages/docs/manual/v8.0.0/jsx.mdx
index 6639bad08..7cf8b28f1 100644
--- a/pages/docs/manual/v8.0.0/jsx.mdx
+++ b/pages/docs/manual/v8.0.0/jsx.mdx
@@ -19,13 +19,15 @@ ReScript supports the JSX syntax, with some slight differences compared to the o
```re
;
```
+
```ml
(* doesn't exist in old ML syntax *)
```
+
```js
React.createElement(
MyComponent.make,
- MyComponent.makeProps("ReScript", undefined)
+ MyComponent.makeProps("ReScript", undefined),
);
```
@@ -38,13 +40,15 @@ becomes
```re
[@JSX] MyComponent.createElement(~name="ReScript", ~children=[], ());
```
+
```ml
MyComponent.createElement ~name:"ReScript" ~children:[] [@JSX]
```
+
```js
React.createElement(
MyComponent.make,
- MyComponent.makeProps("ReScript", undefined)
+ MyComponent.makeProps("ReScript", undefined),
);
```
@@ -57,13 +61,20 @@ React.createElement(
```re
child1 child2
;
```
+
```ml
(* doesn't exist in old ML syntax *)
```
+
```js
-React.createElement("div", {
- onClick: handler
-}, child1, child2);
+React.createElement(
+ "div",
+ {
+ onClick: handler,
+ },
+ child1,
+ child2,
+);
```
@@ -75,13 +86,20 @@ becomes
```re
[@JSX] div(~onClick=handler, ~children=[child1, child2], ());
```
+
```ml
div ~onClick:handler ~children:[child1; child2] () [@@JSX]
```
+
```js
-React.createElement("div", {
- onClick: handler
-}, child1, child2);
+React.createElement(
+ "div",
+ {
+ onClick: handler,
+ },
+ child1,
+ child2,
+);
```
@@ -93,9 +111,11 @@ React.createElement("div", {
```re
<> child1 child2 >;
```
+
```ml
(* doesn't exist in old ML syntax *)
```
+
```js
React.createElement(React.Fragment, undefined, child1, child2);
```
@@ -109,9 +129,11 @@ becomes
```re
[@JSX] [child1, child2];
```
+
```ml
[child1; child2] [@@JSX]
```
+
```js
React.createElement(React.Fragment, undefined, child1, child2);
```
@@ -125,11 +147,18 @@ React.createElement(React.Fragment, undefined, child1, child2);
```re
child1 child2 ;
```
+
```ml
(* doesn't exist in old ML syntax *)
```
+
```js
-React.createElement(MyComponent.make, MyComponent.makeProps(null, undefined), child1, child2);
+React.createElement(
+ MyComponent.make,
+ MyComponent.makeProps(null, undefined),
+ child1,
+ child2,
+);
```
@@ -141,11 +170,18 @@ This is the syntax for passing a list of two items, `child1` and `child2`, to th
```re
[@JSX] MyComponent.createElement(~children=[child1, child2], ());
```
+
```ml
MyComponent.createElement ~children:[child1; child2] () [@@JSX]
```
+
```js
-React.createElement(MyComponent.make, MyComponent.makeProps(null, undefined), child1, child2);
+React.createElement(
+ MyComponent.make,
+ MyComponent.makeProps(null, undefined),
+ child1,
+ child2,
+);
```
@@ -163,11 +199,16 @@ To solve the above problem, we've introduced
```re
...myChild ;
```
+
```ml
(* doesn't exist in old ML syntax *)
```
+
```js
-React.createElement(MyComponent.make, MyComponent.makeProps(myChild, undefined));
+React.createElement(
+ MyComponent.make,
+ MyComponent.makeProps(myChild, undefined),
+);
```
@@ -179,11 +220,16 @@ This passes the value `myChild` _without_ wrapping it in a list (or array, in th
```re
[@JSX] MyComponent.createElement(~children=myChild, ());
```
+
```ml
MyComponent.createElement ~children:myChild () [@@JSX]
```
+
```js
-React.createElement(MyComponent.make, MyComponent.makeProps(myChild, undefined));
+React.createElement(
+ MyComponent.make,
+ MyComponent.makeProps(myChild, undefined),
+);
```
@@ -197,9 +243,11 @@ This is extra useful in the cases where you are handled `myChild` that is alread
...("Hello", "Submit") ;
```
+
```ml
(* doesn't exist in old ML syntax *)
```
+
```js
React.createElement(
make,
@@ -207,10 +255,13 @@ React.createElement(
return React.createElement("div", {
className: theClassName,
});
- }, undefined)
+ }, undefined),
);
-React.createElement(MyForm.make, MyForm.makeProps(["Hello", "Submit"], undefined));
+React.createElement(
+ MyForm.make,
+ MyForm.makeProps(["Hello", "Submit"], undefined),
+);
```
@@ -233,9 +284,11 @@ Here's a JSX tag that shows most of the features.
{React.string("hello")}
;
```
+
```ml
(* doesn't exist in old ML syntax *)
```
+
```js
React.createElement(
MyComponent.make,
@@ -246,8 +299,8 @@ React.createElement(
"hello",
handleClick,
React.createElement("div", undefined, "hello"),
- undefined
- )
+ undefined,
+ ),
);
```
@@ -256,7 +309,7 @@ React.createElement(
## Departures From JS JSX
- Attributes and children don't mandate `{}`, but we show them anyway for ease of learning. Once you format your file, some of them go away and some turn into parentheses.
-- There is no support for JSX prop spread: ` `. Though somewhat related, we do have children spread, described above: ` ...children `.
+- There is no support for JSX prop spread: ` `. Though somewhat related, we do have children spread, described above: ` ...children `.
- Punning!
### Punning
@@ -270,13 +323,15 @@ Reason JSX supports punning. ` ` is just a shorthand for ` ;
```
+
```ml
(* doesn't exist in old ML syntax *)
```
+
```js
React.createElement(
MyComponent.make,
- MyComponent.makeProps(isLoading, text, onClick, undefined)
+ MyComponent.makeProps(isLoading, text, onClick, undefined),
);
```
diff --git a/pages/docs/manual/v8.0.0/lazy-values.mdx b/pages/docs/manual/v8.0.0/lazy-values.mdx
index a19828f35..eb57e9934 100644
--- a/pages/docs/manual/v8.0.0/lazy-values.mdx
+++ b/pages/docs/manual/v8.0.0/lazy-values.mdx
@@ -37,6 +37,7 @@ Lazy.force(getFiles)->Js.log;
// The second call will just return the already calculated files
Lazy.force(getFiles)->Js.log;
```
+
```ml
(* We only want getFiles to read the file system once, *)
(* so we wrap it in a lazy value *)
@@ -51,6 +52,7 @@ let () = (Lazy.force getFiles) |. Js.log
(* The second call will just return the already calculated files *)
let () = (Lazy.force getFiles) |. Js.log
```
+
```js
var Fs = require("fs");
var CamlinternalLazy = require("./stdlib/camlinternalLazy.js");
@@ -82,6 +84,7 @@ let getFiles = () => {
// Here we wrap our function in the lazy value
let lazyGetFiles = Lazy.from_fun(getFiles);
```
+
```ml
(* Example for wrapping a function with 0 parameters *)
let getFiles () =
@@ -90,6 +93,7 @@ let getFiles () =
(* Here we wrap our function in the lazy value *)
let lazyGetFiles = Lazy.from_fun getFiles
```
+
```js
var Fs = require("fs");
var Lazy = require("./stdlib/lazy.js");
@@ -115,6 +119,7 @@ let doesFileExist = name => {
// since we can't use Lazy.from_fun
let lazyDoesFileExist = lazy(doesFileExist("blog.re"));
```
+
```ml
(* Example for wrapping a function with parameters *)
let doesFileExist name =
@@ -124,6 +129,7 @@ let doesFileExist name =
(* since we can't use Lazy.from_fun *)
let lazyDoesFileExist = lazy(doesFileExist "blog.re")
```
+
```js
var Fs = require("fs");
var Caml_option = require("./stdlib/caml_option.js");
@@ -132,7 +138,7 @@ function doesFileExist(name) {
return Caml_option.undefined_to_opt(
Fs.readdirSync("./pages").find(function (s) {
return name === s;
- })
+ }),
);
}
@@ -160,12 +166,14 @@ let computation = lazy(1);
// Returns 1
Lazy.force(computation);
```
+
```ml
let computation = lazy 1;
(* Returns 1 *)
Lazy.force computation
```
+
```js
var CamlinternalLazy = require("./stdlib/camlinternalLazy.js");
@@ -192,6 +200,7 @@ switch computation {
| _ => Js.log("not ok")
};
```
+
```ml
(* Extract a lazy value via pattern matching *)
let computation = lazy "computed"
@@ -200,6 +209,7 @@ let () = match computation with
| lazy "computed" -> Js.log "ok"
| _ -> Js.log "not ok"
```
+
```js
var CamlinternalLazy = require("./stdlib/camlinternalLazy.js");
@@ -230,12 +240,14 @@ let lazy(word) = lazy("hello");
// Output: "hello"
Js.log(word);
```
+
```ml
let lazy word = lazy "hello"
(* Output: "hello" *)
Js.log word
```
+
```js
var CamlinternalLazy = require("./stdlib/camlinternalLazy.js");
@@ -262,6 +274,7 @@ let (lazy(word1), lazy(word2)) = lazyValues;
Js.log2(word1, word2);
let lazy(word) = lazy("hello");
```
+
```ml
(* Destructing a tuple *)
let lazyValues = (lazy "hello", lazy "world")
@@ -271,6 +284,7 @@ let (lazy word1, lazy word2) = lazyValues
Js.log2(word1, word2)
let lazy word = lazy "hello"
```
+
```js
var CamlinternalLazy = require("./stdlib/camlinternalLazy.js");
@@ -320,11 +334,13 @@ try (Lazy.force(readFile)) {
| Not_found => Js.log("No file")
};
```
+
```ml
let readFile = lazy (raise Not_found)
let () = try Lazy.force readFile with
| Not_found -> Js.log "No file"
```
+
```js
var CamlinternalLazy = require("./stdlib/camlinternalLazy.js");
var Caml_js_exceptions = require("./stdlib/caml_js_exceptions.js");
diff --git a/pages/docs/manual/v8.0.0/let-binding.mdx b/pages/docs/manual/v8.0.0/let-binding.mdx
index 834509559..fe4cfc8a1 100644
--- a/pages/docs/manual/v8.0.0/let-binding.mdx
+++ b/pages/docs/manual/v8.0.0/let-binding.mdx
@@ -15,11 +15,13 @@ let greeting = "hello!";
let score = 10;
let newScore = 10 + score;
```
+
```ml
let greeting = "hello!"
let score = 10
let newScore = 10 + score
```
+
```js
var greeting = "hello!";
var score = 10;
@@ -42,6 +44,7 @@ let message = {
};
// `part1` and `part2` not accessible here!
```
+
```ml
let message =
let part1 = "hello" in
@@ -50,6 +53,7 @@ let message =
(* `part1` and `part2` not accessible here! *)
```
+
```js
var message = "hello world";
```
@@ -71,12 +75,14 @@ if (displayGreeting) {
}
// `message` not accessible here!
```
+
```re
if displayGreeting then
let message = "Enjoying the docs so far?" in
Js.log message
(* `message` not accessible here! *)
```
+
```js
if (displayGreeting) {
console.log("Enjoying the docs so far?");
@@ -118,11 +124,13 @@ let result1 = 0;
let result2 = calculate(result1);
let result3 = calculateSomeMore(result2);
```
+
```ml
let result1 = 0
let result2 = calculate result1
let result3 = calculateSomeMore result2
```
+
```js
var result1 = 0;
var result2 = calculate(0);
@@ -140,11 +148,13 @@ let result = 0;
let result = calculate(result);
let result = calculateSomeMore(result);
```
+
```ml
let result = 0
let result = calculate result
let result = calculateSomeMore result
```
+
```js
var result = calculate(0);
var result$1 = calculateSomeMore(result);
@@ -164,12 +174,14 @@ Js.log(result); // prints "hello"
let result = 1;
Js.log(result); // prints 1
```
+
```ml
let result = "hello"
let () = Js.log result (* prints "hello" *)
let result = 1
let () = Js.log result (* prints 1 *)
```
+
```js
var result = 1;
console.log("hello");
@@ -181,13 +193,12 @@ console.log(1);
The binding you refer to is whatever's the closest upward. No mutation here!
If you need _real_ mutation, e.g. passing a value around, have it modified by many pieces of code, we provide a slightly heavier [mutation feature](mutation.md).
-
## Private let bindings
Private let bindings are introduced in the release [7.2](https://rescript-lang.org/blog/bucklescript-release-7-2).
-In the module system, everything is public by default,
-the only way to hide some values is by providing a separate signature to
+In the module system, everything is public by default,
+the only way to hide some values is by providing a separate signature to
list public fields and their types:
```res
@@ -198,6 +209,7 @@ module A: {
let b = 4
}
```
+
`%private` gives you an option to mark private fields directly
```res
@@ -207,15 +219,14 @@ module A = {
}
```
-`%private` also applies to file level modules, so in some cases,
+`%private` also applies to file level modules, so in some cases,
users do not need to provide a separate interface file just to hide some particular values.
-Note interface files are still recommended as a general best practice since they give you better
-separate compilation units and also they're better for documentation.
+Note interface files are still recommended as a general best practice since they give you better
+separate compilation units and also they're better for documentation.
Still, `%private` is useful in the following scenarios:
- Code generators. Some code generators want to hide some values but it is sometimes very hard or time consuming for code generators to synthesize the types for public fields.
- Quick prototyping. During prototyping, we still want to hide some values, but the interface file is not stable yet. `%private` provides you such convenience.
-
diff --git a/pages/docs/manual/v8.0.0/module.mdx b/pages/docs/manual/v8.0.0/module.mdx
index 568f74e20..5e54d2bc5 100644
--- a/pages/docs/manual/v8.0.0/module.mdx
+++ b/pages/docs/manual/v8.0.0/module.mdx
@@ -31,6 +31,7 @@ module School = {
};
};
```
+
```ml
module School = struct
type profession = Teacher | Director
@@ -42,6 +43,7 @@ module School = struct
| Director -> "A director"
end
```
+
```js
function getProfession(person) {
if (person) {
@@ -52,8 +54,8 @@ function getProfession(person) {
}
var School = {
- person1: /* Teacher */0,
- getProfession: getProfession
+ person1: /* Teacher */ 0,
+ getProfession: getProfession,
};
```
@@ -68,12 +70,14 @@ using the `.` notation. This demonstrates modules' utility for namespacing.
let anotherPerson: School.profession = School.Teacher;
Js.log(School.getProfession(anotherPerson)); /* "A teacher" */
```
+
```ml
let anotherPerson: School.profession = School.Teacher
Js.log (School.getProfession anotherPerson) (* "A teacher" *)
```
+
```js
-var anotherPerson = /* Teacher */0;
+var anotherPerson = /* Teacher */ 0;
console.log("A teacher");
```
@@ -92,6 +96,7 @@ module MyModule = {
let message = MyModule.NestedModule.message;
```
+
```ml
module MyModule = struct
module NestedModule = struct
@@ -101,13 +106,14 @@ end
let message = MyModule.NestedModule.message
```
+
```js
var NestedModule = {
- message: message
+ message: message,
};
var MyModule = {
- NestedModule: NestedModule
+ NestedModule: NestedModule,
};
var message = MyModule.NestedModule.message;
@@ -125,9 +131,11 @@ module's name. Instead of writing:
```re
let p = School.getProfession(School.person1);
```
+
```ml
let p = School.getProfession School.person1
```
+
```js
var p = School.getProfession(School.person1);
```
@@ -142,10 +150,12 @@ We can write:
open School;
let p = getProfession(person1);
```
+
```ml
open School
let p = getProfession person1
```
+
```js
var p = School.getProfession(School.person1);
```
@@ -165,12 +175,14 @@ let p = {
};
/* School's content isn't visible here anymore */
```
+
```ml
let p =
let open School in
getProfession person1
(* School's content isn't visible here anymore *)
```
+
```js
var p = School.getProfession(School.person1);
```
@@ -199,6 +211,7 @@ module ActualComponent = {
let render = () => defaultGreeting ++ " " ++ getAudience(~excited=true);
};
```
+
```ml
module BaseComponent = struct
let defaultGreeting = "Hello"
@@ -213,6 +226,7 @@ module ActualComponent = struct
let render () = defaultGreeting ^ " " ^ (getAudience ~excited:true)
end
```
+
```js
function getAudience(excited) {
if (excited) {
@@ -224,7 +238,7 @@ function getAudience(excited) {
var BaseComponent = {
defaultGreeting: "Hello",
- getAudience: getAudience
+ getAudience: getAudience,
};
var defaultGreeting = "Hey";
@@ -236,7 +250,7 @@ function render(param) {
var ActualComponent = {
getAudience: getAudience,
defaultGreeting: defaultGreeting,
- render: render
+ render: render,
};
```
@@ -271,6 +285,7 @@ module type EstablishmentType = {
let getProfession: profession => string;
};
```
+
```ml
(* Picking up previous section's example *)
module type EstablishmentType = sig
@@ -278,6 +293,7 @@ module type EstablishmentType = sig
val getProfession: profession -> string
end
```
+
```js
// Empty output
```
@@ -322,6 +338,7 @@ module Company: EstablishmentType = {
let person2 = ...
};
```
+
```ml
module Company: EstablishmentType = struct
type profession = CEO | Designer | Engineer | ...
@@ -331,6 +348,7 @@ module Company: EstablishmentType = struct
let person2 = ...
end
```
+
```js
function getProfession(person) {
...
@@ -371,6 +389,7 @@ module type ActualComponent = {
let render: unit => string;
};
```
+
```ml
module type BaseComponent = sig
val defaultGreeting: string
@@ -383,6 +402,7 @@ module type ActualComponent = sig
val render: unit -> string
end
```
+
```js
// Empty output
```
@@ -404,12 +424,14 @@ module type MyList = {
let myListFun: list('a) => list('a);
};
```
+
```ml
module type MyList = sig
include module type of List
val myListFun: 'a list -> 'a list
end
```
+
```js
// Empty output
```
@@ -431,11 +453,13 @@ in the ecosystem to also document the public API of their corresponding modules.
type state = int;
let render = (str) => str;
```
+
```ml
(* file React.ml (implementation. Compiles to module React) *)
type state = int
let render str = str
```
+
```js
function render(str) {
return str;
@@ -451,6 +475,7 @@ function render(str) {
type state = int;
let render: string => string;
```
+
```ml
(* file React.mli (interface. Compiles to the signature of React.re) *)
type state = int
@@ -463,7 +488,7 @@ val render: str -> str
Modules can be passed to functions! It would be the equivalent of passing a file
as a first-class item. However, modules are at a different "layer" of the
-language than other common concepts, so we can't pass them to *regular*
+language than other common concepts, so we can't pass them to _regular_
functions. Instead, we pass them to special functions called "functors".
The syntax for defining and using functors is very much like the syntax
@@ -471,7 +496,7 @@ for defining and using regular functions. The primary differences are:
- Functors use the `module` keyword instead of `let`.
- Functors take modules as arguments and return a module.
-- Functors *require* annotating arguments.
+- Functors _require_ annotating arguments.
- Functors must start with a capital letter (just like modules/signatures).
Here's an example `MakeSet` functor, that takes in a module of the type
@@ -501,6 +526,7 @@ module MakeSet = (Item: Comparable) => {
};
};
```
+
```ml
module type Comparable = sig
type t
@@ -519,13 +545,14 @@ module MakeSet (Item: Comparable) = struct
newItem::currentSet (* prepend to the set and return it *)
end
```
+
```js
var List = require("./stdlib/list.js");
function MakeSet(Item) {
- var add = function(currentSet, newItem) {
+ var add = function (currentSet, newItem) {
if (
- List.exists(function(x) {
+ List.exists(function (x) {
return Item.equal(x, newItem);
}, currentSet)
) {
@@ -561,6 +588,7 @@ module IntPair = {
/* IntPair abides by the Comparable signature required by MakeSet */
module SetOfIntPairs = MakeSet(IntPair);
```
+
```ml
module IntPair = struct
type t = int * int
@@ -571,6 +599,7 @@ end
(* IntPair abides by the Comparable signature required by MakeSet *)
module SetOfIntPairs = MakeSet(IntPair)
```
+
```js
function equal(param, param$1) {
if (param[0] === param$1[0]) {
@@ -621,6 +650,7 @@ module MakeSet: MakeSetType = (Item: Comparable) => {
...
};
```
+
```ml
module type Comparable = ...
@@ -634,6 +664,7 @@ module MakeSet: MakeSetType = functor (Item: Comparable) -> struct
...
end
```
+
```js
// Empty output
```
diff --git a/pages/docs/manual/v8.0.0/mutation.mdx b/pages/docs/manual/v8.0.0/mutation.mdx
index 050cd3275..02268505c 100644
--- a/pages/docs/manual/v8.0.0/mutation.mdx
+++ b/pages/docs/manual/v8.0.0/mutation.mdx
@@ -17,12 +17,14 @@ Let-bindings are immutable, but you can wrap it with a `ref`, exposed as a recor
```re
let myValue = ref(5);
```
+
```ml
let myValue = ref 5
```
+
```js
var myValue = {
- contents: 5
+ contents: 5,
};
```
@@ -37,9 +39,11 @@ You can get the actual value of a `ref` box through accessing its `contents` fie
```re
let five = myValue.contents; // 5
```
+
```ml
let five = myValue.contents (* 5 *)
```
+
```js
var five = myValue.contents;
```
@@ -55,9 +59,11 @@ Assign a new value to `myValue` like so:
```re
myValue.contents = 6;
```
+
```ml
myValue.contents = 6
```
+
```js
myValue.contents = 6;
```
@@ -71,9 +77,11 @@ We provide a syntax sugar for this:
```re
myValue := 6;
```
+
```ml
myValue := 6
```
+
```js
myValue.contents = 6;
```
diff --git a/pages/docs/manual/v8.0.0/newcomer-examples.mdx b/pages/docs/manual/v8.0.0/newcomer-examples.mdx
index 30c4921a7..bbf48af58 100644
--- a/pages/docs/manual/v8.0.0/newcomer-examples.mdx
+++ b/pages/docs/manual/v8.0.0/newcomer-examples.mdx
@@ -25,6 +25,7 @@ switch (possiblyNullValue2) {
| Some(message) => Js.log(message)
};
```
+
```ml
let possiblyNullValue1 = None
let possiblyNullValue2 = Some "Hello"
@@ -33,6 +34,7 @@ let () = match possiblyNullValue2 with
| None -> Js.log "Nothing to see here."
| Some(message) -> Js.log message
```
+
```js
var possiblyNullValue1;
var possiblyNullValue2 = "Hello";
@@ -42,7 +44,6 @@ if (possiblyNullValue2 !== undefined) {
} else {
console.log("Nothing to see here.");
}
-
```
@@ -59,6 +60,7 @@ type response('studentType) = {
student: 'studentType,
};
```
+
```ml
type universityStudent = {gpa: float}
@@ -67,6 +69,7 @@ type 'studentType response = {
student: 'studentType;
}
```
+
```js
// Empty output
```
@@ -83,12 +86,14 @@ let student1 = {
"age": 30,
};
```
+
```ml
let student1 = [%bs.obj {
name = "John";
age = 30
}]
```
+
```js
var student1 = {
name: "John",
@@ -113,6 +118,7 @@ let student1 = {
age: 30,
};
```
+
```ml
type payload = {
name: string;
@@ -124,6 +130,7 @@ let student1 = {
age = 30;
}
```
+
```js
var student1 = {
name: "John",
@@ -152,6 +159,7 @@ let greetByName = (possiblyNullName) => {
}
};
```
+
```ml
let greetByName possiblyNullName =
let optionName = Js.Nullable.toOption possiblyNullName in
@@ -159,6 +167,7 @@ let greetByName possiblyNullName =
| None -> "Hi"
| Some name -> "Hello " ^ name
```
+
```js
function greetByName(possiblyNullName) {
if (possiblyNullName == null) {
diff --git a/pages/docs/manual/v8.0.0/null-undefined-option.mdx b/pages/docs/manual/v8.0.0/null-undefined-option.mdx
index 1c3277ae6..5d86a7452 100644
--- a/pages/docs/manual/v8.0.0/null-undefined-option.mdx
+++ b/pages/docs/manual/v8.0.0/null-undefined-option.mdx
@@ -17,11 +17,13 @@ We represent the existence and nonexistence of a value by wrapping it with the `
```re
type option('a) = None | Some('a);
```
+
type 'a option = | None | Some of 'a
-```
+
+````
```js
// Empty output
-```
+````
@@ -38,9 +40,11 @@ Here's a normal value:
```re
let licenseNumber = 5;
```
+
```ml
let licenseNumber = 5
```
+
```js
var licenseNumber = 5;
```
@@ -59,6 +63,7 @@ let licenseNumber =
None;
};
```
+
```ml
let licenseNumber =
if personHasACar then
@@ -66,6 +71,7 @@ let licenseNumber =
else
None
```
+
```js
var licenseNumber = personHasACar ? 5 : undefined;
```
@@ -84,6 +90,7 @@ switch (licenseNumber) {
Js.log("The person's license number is " ++ Js.Int.toString(number));
};
```
+
```ml
let () = match licenseNumber with
| None ->
@@ -91,6 +98,7 @@ let () = match licenseNumber with
| Some number ->
Js.log ("The person's license number is " ^ (Js.Int.toString number))
```
+
```js
var number = licenseNumber;
@@ -114,9 +122,11 @@ The `option` type is common enough that we special-case it when compiling to Jav
```re
let x = Some(5);
```
+
```ml
let x = Some 5
```
+
```js
var x = 5;
```
@@ -130,9 +140,11 @@ simply compiles down to `5`, and
```re
let x = None;
```
+
```ml
let x = None
```
+
```js
var x;
```
@@ -150,9 +162,11 @@ The option-to-undefined translation isn't perfect, because on our side, `option`
```re
let x = Some(Some(Some(5)));
```
+
```ml
let x = Some (Some (Some 5))
```
+
```js
var x = 5;
```
@@ -166,9 +180,11 @@ This still compiles to `5`, but this gets troublesome:
```re
let x = Some(None);
```
+
```ml
let x = Some None
```
+
```js
var Caml_option = require("./stdlib/caml_option.js");
@@ -203,9 +219,11 @@ If you're receiving, for example, a JS string that can be `null` and `undefined`
```re
[@bs.module "MyConstant"] external myId: Js.Nullable.t(string) = "myId";
```
+
```ml
external myId: string Js.Nullable.t = "myId" [@@bs.module "MyConstant"]
```
+
```js
// Empty output
```
@@ -222,12 +240,14 @@ let personId: Js.Nullable.t(string) = Js.Nullable.return("abc123");
let result = validate(personId);
```
+
```ml
external validate: string Js.Nullable.t -> bool = "validate" [@@bs.module "MyIdValidator"]
let personId: string Js.Nullable.t = Js.Nullable.return "abc123"
let result = validate personId
```
+
```js
var MyIdValidator = require("MyIdValidator");
var personId = "abc123";
diff --git a/pages/docs/manual/v8.0.0/object.mdx b/pages/docs/manual/v8.0.0/object.mdx
index 15d76c063..25bbbc752 100644
--- a/pages/docs/manual/v8.0.0/object.mdx
+++ b/pages/docs/manual/v8.0.0/object.mdx
@@ -30,11 +30,13 @@ type person = {
"name": string
};
```
+
```re
type person = <
age :int;
name :string> Js.t
```
+
```js
// Empty output
```
@@ -55,16 +57,18 @@ let me = {
"name": "Big ReScript"
};
```
+
```ml
let me = [%bs.obj {
age = 5;
name = "Big ReScript";
}]
```
+
```js
var me = {
- "age": 5,
- "name": "Big ReScript"
+ age: 5,
+ name: "Big ReScript",
};
```
@@ -84,6 +88,7 @@ let me = {
"age": "hello!" // age is a string. No error.
};
```
+
```ml
type person = <
age :int
@@ -93,9 +98,10 @@ let me = [%bs.obj {
age = "hello!" (* age is a string. No error. *)
}]
```
+
```js
var me = {
- "age": "hello!"
+ age: "hello!",
};
```
@@ -110,6 +116,7 @@ let me: person = {
"age": "hello!"
}
```
+
```ml
let me: person = [%bs.obj {
age = "hello!"
@@ -127,9 +134,11 @@ Now the type system will error properly.
```re
let age = me##age;
```
+
```ml
let age = me##age
```
+
```js
var age = me["age"];
```
@@ -151,6 +160,7 @@ type student = {
student1##name = "Mary";
```
+
```ml
type student = <
age: int [@bs.set];
@@ -160,6 +170,7 @@ external student1: student = "student1" [@@bs.module "MyJSFile"]
student1##name = "Mary"
```
+
```js
var MyJSFile = require("MyJSFile");
MyJSFile.student1.name = "Mary";
@@ -189,6 +200,7 @@ let loc = document##location;
// set a property
document##location##href = "rescript-lang.org";
```
+
```ml
// The type of document is just some random type 'a
// that we won't bother to specify
@@ -205,8 +217,9 @@ let loc = document##location
// set a property
document##location##href = "rescript-lang.org"
```
+
```js
-document.addEventListener("mouseup", function(_event) {
+document.addEventListener("mouseup", function (_event) {
console.log("clicked!");
});
var loc = document.location;
diff --git a/pages/docs/manual/v8.0.0/overview.mdx b/pages/docs/manual/v8.0.0/overview.mdx
index cc92f72b1..8d3a7f309 100644
--- a/pages/docs/manual/v8.0.0/overview.mdx
+++ b/pages/docs/manual/v8.0.0/overview.mdx
@@ -13,33 +13,33 @@ canonical: "/docs/manual/latest/overview"
### Semicolon
-| JavaScript | Us |
-| ------------------------------------ | -------------------- |
-| Rules enforced by linter/formatter | No semicolon needed! |
+| JavaScript | Us |
+| ---------------------------------- | -------------------- |
+| Rules enforced by linter/formatter | No semicolon needed! |
### Comments
-| JavaScript | Us |
-| ----------------- | ----------- |
-| `/* Comment */` | Same |
-| `// Line comment` | Same |
+| JavaScript | Us |
+| ----------------- | ---- |
+| `/* Comment */` | Same |
+| `// Line comment` | Same |
### Variable
-| JavaScript | Us |
-| ----------------------- | ------------------------------ |
-| `const x = 5;` | `let x = 5` |
-| `var x = y;` | No equivalent (thankfully) |
+| JavaScript | Us |
+| ----------------------- | ------------------------------------- |
+| `const x = 5;` | `let x = 5` |
+| `var x = y;` | No equivalent (thankfully) |
| `let x = 5; x = x + 1;` | `let x = ref(5); x := x.contents + 1` |
### String & Character
-| JavaScript | Us |
-| --------------------------| ----------------------- |
-| `"Hello world!"` | Same |
-| `'Hello world!'` | Strings must use `"` |
-| `"hello " + "world"` | `"hello " ++ "world"` |
-| `` `hello ${message}` `` | `\{j|Hello $(message)|j}`|
+| JavaScript | Us |
+| ------------------------ | --------------------- | ---------------- | --- |
+| `"Hello world!"` | Same |
+| `'Hello world!'` | Strings must use `"` |
+| `"hello " + "world"` | `"hello " ++ "world"` |
+| `` `hello ${message}` `` | `\{j | Hello $(message) | j}` |
### Boolean
@@ -76,11 +76,11 @@ canonical: "/docs/manual/latest/overview"
### Array
-| JavaScript | Us |
-| --------------------- | ---------------------------------- |
-| `[1, 2, 3]` | [|1, 2, 3|]
|
-| `myArray[1] = 10` | Same |
-| `[1, "Bob", true]` | `(1, "Bob", true)` \* |
+| JavaScript | Us |
+| ------------------ | ---------------------------------- |
+| `[1, 2, 3]` | [|1, 2, 3|]
|
+| `myArray[1] = 10` | Same |
+| `[1, "Bob", true]` | `(1, "Bob", true)` \* |
\* Heterogenous arrays in JS are disallowed for us. Use tuple instead.
@@ -134,13 +134,12 @@ canonical: "/docs/manual/latest/overview"
-
### If-else
-| JavaScript | Us |
-| --------------------- | ------------------------------------------------------------------- |
-| `if (a) {b} else {c}` | `if (a) {b} else {c}` \* |
-| `a ? b : c` | Same |
+| JavaScript | Us |
+| --------------------- | --------------------------------------------------------------------------------- |
+| `if (a) {b} else {c}` | `if (a) {b} else {c}` \* |
+| `a ? b : c` | Same |
| `switch` | `switch` but [super-powered pattern matching!](pattern-matching-destructuring.md) |
\* Our conditionals are always expressions! You can write `let result = if (a) {"hello"} else {"bye"}`
@@ -176,9 +175,9 @@ canonical: "/docs/manual/latest/overview"
### Exception
-| JavaScript | Us |
-| ----------------------------------------- | ------------------------------------------ |
-| `throw new SomeError(...)` | `raise(SomeError(...))` |
+| JavaScript | Us |
+| ----------------------------------------- | --------------------------------- |
+| `throw new SomeError(...)` | `raise(SomeError(...))` |
| `try {a} catch (Err) {...} finally {...}` | `try a catch { \| Err => ...}` \* |
\* No finally.
@@ -220,25 +219,25 @@ The last expression of a block delimited by `{}` implicitly returns (including f
## Common Features' JS Output
-Feature | Example | JavaScript Output
---------------------------------|--------------------------------------|----------------------
-String | `"Hello"` | `"Hello"`
-String Interpolation | `\{j|Hello $(message)|j}` | `"Hello " + message`
-Character (disrecommended) | `'x'` | `120` (char code)
-Integer | `23`, `-23` | `23`, `-23`
-Float | `23.0`, `-23.0` | `23.0`, `-23.0`
-Integer Addition | `23 + 1` | `23 + 1`
-Float Addition | `23.0 +. 1.0` | `23.0 + 1.0`
-Integer Division/Multiplication | `2 / 23 * 1` | `2 / 23 * 1`
-Float Division/Multiplication | `2.0 /. 23.0 *. 1.0` | `2.0 / 23.0 * 1.0`
-Float Exponentiation | `2.0 ** 3.0` | `Math.pow(2.0, 3.0)`
-String Concatenation | `"Hello " ++ "World"` | `"Hello " + "World"`
-Comparison | `>`, `<`, `>=`, `<=` | `>`, `<`, `>=`, `<=`
-Boolean operation | `!`, `&&`, `\|\|` | `!`, `&&`, `\|\|`
-Shallow and deep Equality | `===`, `==` | `===`, `==`
-List (disrecommended) | `[1, 2, 3]` | `{hd: 1, tl: {hd: 2, tl: {hd: 3, tl: 0}}}`
-List Prepend | `[a1, a2, ...oldList]` | `{hd: a1, tl: {hd: a2, tl: theRest}}`
-Array | [|1, 2, 3|]
| `[1, 2, 3]`
-Record | `type t = {b: int}; let a = {b: 10}` | `var a = {b: 10}`
-Multiline Comment | `/* Comment here */` | Not in output
-Single line Comment | `// Comment here` | Not in output
+| Feature | Example | JavaScript Output |
+| ------------------------------- | ------------------------------------ | ------------------------------------------ | --- | -------------------- |
+| String | `"Hello"` | `"Hello"` |
+| String Interpolation | `\{j | Hello $(message) | j}` | `"Hello " + message` |
+| Character (disrecommended) | `'x'` | `120` (char code) |
+| Integer | `23`, `-23` | `23`, `-23` |
+| Float | `23.0`, `-23.0` | `23.0`, `-23.0` |
+| Integer Addition | `23 + 1` | `23 + 1` |
+| Float Addition | `23.0 +. 1.0` | `23.0 + 1.0` |
+| Integer Division/Multiplication | `2 / 23 * 1` | `2 / 23 * 1` |
+| Float Division/Multiplication | `2.0 /. 23.0 *. 1.0` | `2.0 / 23.0 * 1.0` |
+| Float Exponentiation | `2.0 ** 3.0` | `Math.pow(2.0, 3.0)` |
+| String Concatenation | `"Hello " ++ "World"` | `"Hello " + "World"` |
+| Comparison | `>`, `<`, `>=`, `<=` | `>`, `<`, `>=`, `<=` |
+| Boolean operation | `!`, `&&`, `\|\|` | `!`, `&&`, `\|\|` |
+| Shallow and deep Equality | `===`, `==` | `===`, `==` |
+| List (disrecommended) | `[1, 2, 3]` | `{hd: 1, tl: {hd: 2, tl: {hd: 3, tl: 0}}}` |
+| List Prepend | `[a1, a2, ...oldList]` | `{hd: a1, tl: {hd: a2, tl: theRest}}` |
+| Array | [|1, 2, 3|]
| `[1, 2, 3]` |
+| Record | `type t = {b: int}; let a = {b: 10}` | `var a = {b: 10}` |
+| Multiline Comment | `/* Comment here */` | Not in output |
+| Single line Comment | `// Comment here` | Not in output |
diff --git a/pages/docs/manual/v8.0.0/pattern-matching-destructuring.mdx b/pages/docs/manual/v8.0.0/pattern-matching-destructuring.mdx
index 275af4b23..07244c219 100644
--- a/pages/docs/manual/v8.0.0/pattern-matching-destructuring.mdx
+++ b/pages/docs/manual/v8.0.0/pattern-matching-destructuring.mdx
@@ -25,11 +25,13 @@ let coordinates = (10, 20, 30);
let (x, _, _) = coordinates;
Js.log(x); // 10
```
+
```ml
let coordinates = (10, 20, 30)
let (x, _, _) = coordinates
Js.log x (* 10 *)
```
+
```js
var coordinates = [10, 20, 30];
var x = 10;
@@ -62,6 +64,7 @@ let [|item1, item2, _|] = myArray; // 1 assigned to `item1`, 2 assigned to `item
let myList = [1, 2, 3];
let [head, ...tail] = myList; // 1 assigned to `head`, `[2, 3]` assigned to tail
```
+
```ml
// Record
type student = {name: string; age: int}
@@ -82,28 +85,25 @@ let [|item1; item2; _|] = myArray (* 1 assigned to `item1`, 2 assigned to `item2
let myList = [1; 2; 3]
let head::tail = myList (* 1 assigned to `head`, `[2, 3]` assigned to tail *)
```
+
```js
var student1 = {
name: "John",
- age: 10
+ age: 10,
};
var name = "John";
-var myResult = /* Success */{
- _0: "You did it!"
+var myResult = /* Success */ {
+ _0: "You did it!",
};
-var message = "You did it!"
+var message = "You did it!";
var myArray = [1, 2, 3];
if (myArray.length !== 2) {
throw {
RE_EXN_ID: "Match_failure",
- _1: [
- "playground.res",
- 14,
- 4
- ],
- Error: new Error()
+ _1: ["playground.res", 14, 4],
+ Error: new Error(),
};
}
var item1 = myArray[0];
@@ -115,9 +115,9 @@ var myList = {
hd: 2,
tl: {
hd: 3,
- tl: /* [] */0
- }
- }
+ tl: /* [] */ 0,
+ },
+ },
};
// ...
```
@@ -138,6 +138,7 @@ let displayMessage = (Success(m)) => {
}
displayMessage(Success("You did it!"));
```
+
```ml
type result =
| Success of string
@@ -148,14 +149,17 @@ let displayMessage (Success m) =
let () = displayMessage (Success "You did it!")
```
+
```js
function displayMessage(m) {
console.log(m._0);
}
-displayMessage(/* Success */{
- _0: "You did it!"
-});
+displayMessage(
+ /* Success */ {
+ _0: "You did it!",
+ },
+);
```
@@ -167,9 +171,11 @@ For a record, you can rename the field while destructuring:
```re
let {name: n} = student1; // "John" assigned to `n`
```
+
```ml
let {name = n} = student1 (* "John" assigned to `n` *)
```
+
```js
var n = "John";
```
@@ -190,12 +196,14 @@ type payload =
| GoodResult(string)
| NoResult;
```
+
```ml
type payload =
| BadResult of int
| GoodResult of string
| NoResult
```
+
```js
// Empty output
```
@@ -219,6 +227,7 @@ switch (data) {
Js.log("Bah.")
};
```
+
```ml
let data = GoodResult ("Product shipped!")
let () = match data with
@@ -228,10 +237,11 @@ let () = match data with
Js.log ("Something's wrong. The error code is: " ^ (Js.Int.toString errorCode))
| NoResult -> Js.log "Bah."
```
+
```js
var data = {
- TAG: /* GoodResult */1,
- _0: "Product shipped!"
+ TAG: /* GoodResult */ 1,
+ _0: "Product shipped!",
};
if (typeof data === "number") {
@@ -239,7 +249,9 @@ if (typeof data === "number") {
} else if (data.TAG) {
console.log("Success! Product shipped!");
} else {
- console.log("Something's wrong. The error code is: " + "Product shipped!".toString());
+ console.log(
+ "Something's wrong. The error code is: " + "Product shipped!".toString(),
+ );
}
```
@@ -269,6 +281,7 @@ type person =
reportCard: reportCard,
});
```
+
```ml
type status = Vacations of int | Sabbatical of int | Sick | Present
type reportCard = {passing: bool; gpa: float}
@@ -283,6 +296,7 @@ type person =
reportCard: reportCard;
}
```
+
```js
// Empty output
```
@@ -321,6 +335,7 @@ let message = switch (person1) {
{j|Good luck next semester $(name)!|j}
};
```
+
```ml
let message = match person1 with
| Teacher {name = "Mary" | "Joe"} ->
@@ -340,6 +355,7 @@ let message = match person1 with
| Student {name} ->
{j|Good luck next semester $(name)!|j}
```
+
```js
var message;
@@ -354,12 +370,12 @@ if (person1.TAG) {
match$2.gpa.toString() +
" you got there!"
: typeof match$1 === "number"
- ? match$1 !== 0
- ? "Good luck next semester " + name + "!"
- : "How are you feeling?"
- : person1.reportCard.gpa !== 0.0
- ? "Good luck next semester " + name + "!"
- : "Come back in " + match$1._0.toString() + " days!";
+ ? match$1 !== 0
+ ? "Good luck next semester " + name + "!"
+ : "How are you feeling?"
+ : person1.reportCard.gpa !== 0.0
+ ? "Good luck next semester " + name + "!"
+ : "Come back in " + match$1._0.toString() + " days!";
} else {
var name$1 = person1.name;
switch (name$1) {
@@ -376,6 +392,7 @@ if (person1.TAG) {
**Note** how we've:
+
- drilled deep down into the value concisely
- using a nested pattern check `"Mary" | "Joe"` and `Vacations | Sabbatical`
- while extracting the `daysLeft` number from the latter case
@@ -395,6 +412,7 @@ let categoryId = switch (isBig, myAnimal) {
| (false, Bird) => 5
};
```
+
```ml
type animal = Dog | Cat | Bird
let categoryId = match (isBig, myAnimal) with
@@ -404,6 +422,7 @@ let categoryId = match (isBig, myAnimal) with
| (false, (Dog | Cat)) -> 4
| (false, Bird) -> 5
```
+
```js
var categoryId = isBig ? (myAnimal + 1) | 0 : myAnimal >= 2 ? 5 : 4;
```
@@ -412,10 +431,10 @@ var categoryId = isBig ? (myAnimal + 1) | 0 : myAnimal >= 2 ? 5 : 4;
**Note** how pattern matching on a tuple is equivalent to a 2D table:
-isBig \ myAnimal | Dog | Cat | Bird
------------------|-----|-----|------
-true | 1 | 2 | 3
-false | 4 | 4 | 5
+| isBig \ myAnimal | Dog | Cat | Bird |
+| ---------------- | --- | --- | ---- |
+| true | 1 | 2 | 3 |
+| false | 4 | 4 | 5 |
### Ignore Part of a Value
@@ -429,11 +448,13 @@ switch (person) {
| Student(_) => Js.log("Hey student")
};
```
+
```ml
let () = match person with
| Teacher _ -> Js.log "Hi teacher"
| Student _ -> Js.log "Hey student"
```
+
```js
if (person.TAG) {
console.log("Hey student");
@@ -463,6 +484,7 @@ switch (person) {
}
};
```
+
```ml
let () = match person with
| Teacher _ -> () (* do nothing *)
@@ -472,6 +494,7 @@ let () = match person with
else
Js.log "Heyo"
```
+
```js
if (person.TAG) {
if (person.reportCard.gpa < 0.5) {
@@ -498,6 +521,7 @@ switch (person) {
Js.log("Heyo");
}
```
+
```ml
let () = match person with
| Teacher _ -> () (* do nothing *)
@@ -507,6 +531,7 @@ let () = match person with
(* fall-through, catch-all case *)
Js.log "Heyo"
```
+
```js
if (person.TAG) {
if (person.reportCard.gpa < 0.5) {
@@ -531,23 +556,24 @@ switch (List.find(i => i === theItem, myItems)) {
| exception Not_found => Js.log("No such item found!")
};
```
+
```ml
let () = match List.find (fun i -> i == theItem) myItems with
| item -> Js.log item
| exception Not_found -> Js.log "No such item found!"
```
+
```js
var exit = 0;
var item;
try {
- item = List.find(function(i) {
+ item = List.find(function (i) {
return i === theItem;
}, myItems);
exit = 1;
-}
-catch (raw_exn){
+} catch (raw_exn) {
var exn = Caml_js_exceptions.internalToOCamlException(raw_exn);
if (exn.RE_EXN_ID === "Not_found") {
console.log("No such item found!");
@@ -576,12 +602,14 @@ switch (coordinates) {
| (x, centerY, _) => /* code */
}
```
+
```ml
let coordinates = (10, 20, 30)
let centerY = 20
let () = match coordinates with
| (x, centerY, _) => (* code *)
```
+
```js
var coordinates = [10, 20, 30];
var centerY = 20;
@@ -618,6 +646,7 @@ let message = switch (person) {
"Good luck next semester " ++ name ++ "!"
}
```
+
```ml
let message = match person with
| Teacher {name = "Mary" | "Joe"} ->
@@ -634,18 +663,23 @@ let message = match person with
| Student {name} ->
"Good luck next semester "^ name ^ "!"
```
+
```js
if (person.TAG) {
var match$1 = person.status;
var name = person.name;
var match$2 = person.reportCard;
if (match$2.passing) {
- "Congrats " + name + ", nice GPA of " + match$2.gpa.toString() + " you got there!";
+ "Congrats " +
+ name +
+ ", nice GPA of " +
+ match$2.gpa.toString() +
+ " you got there!";
} else if (typeof match$1 === "number") {
if (match$1 !== 0) {
"Good luck next semester " + name + "!";
} else {
- "How are you feeling?";
+ ("How are you feeling?");
}
} else if (person.reportCard.gpa !== 0.0) {
"Good luck next semester " + name + "!";
@@ -660,12 +694,8 @@ if (person.TAG) {
default:
throw {
RE_EXN_ID: "Match_failure",
- _1: [
- "playground.res",
- 13,
- 0
- ],
- Error: new Error()
+ _1: ["playground.res", 13, 0],
+ Error: new Error(),
};
}
}
@@ -693,11 +723,13 @@ switch (myNullableValue) {
| None => Js.log("value is absent")
};
```
+
```ml
match myNullableValue with
| Some v -> Js.log "value is present"
| None -> Js.log "value is absent"
```
+
```js
if (myNullableValue !== undefined) {
console.log("value is present");
@@ -735,6 +767,7 @@ let optionBoolToBool = opt => {
}
}
```
+
```ml
let optionBoolToBool opt =
if opt = None
@@ -743,6 +776,7 @@ let optionBoolToBool opt =
true
else false
```
+
```js
function optionBoolToBool(opt) {
if (opt === undefined) {
@@ -767,12 +801,14 @@ let optionBoolToBool = opt => {
}
};
```
+
```ml
let optionBoolToBool opt =
match opt with
| None -> false
| Some a -> if a then true else false
```
+
```js
function optionBoolToBool(opt) {
if (opt !== undefined && opt) {
@@ -798,6 +834,7 @@ let optionBoolToBool = opt => {
}
};
```
+
```ml
let optionBoolToBool opt =
match opt with
@@ -805,6 +842,7 @@ let optionBoolToBool opt =
| Some true -> true
| Some false -> false
```
+
```js
function optionBoolToBool(opt) {
if (opt !== undefined && opt) {
@@ -829,12 +867,14 @@ let optionBoolToBool = opt => {
}
};
```
+
```ml
let optionBoolToBool opt =
match opt with
| Some true -> true
| _ -> false
```
+
```js
function optionBoolToBool(opt) {
if (opt !== undefined && opt) {
@@ -857,6 +897,7 @@ let optionBoolToBool opt =
| Some trueOrFalse -> trueOrFalse
| None -> false
```
+
```js
function optionBoolToBool(opt) {
if (opt !== undefined) {
diff --git a/pages/docs/manual/v8.0.0/pipe.mdx b/pages/docs/manual/v8.0.0/pipe.mdx
index e5138e25a..885ab0b48 100644
--- a/pages/docs/manual/v8.0.0/pipe.mdx
+++ b/pages/docs/manual/v8.0.0/pipe.mdx
@@ -15,9 +15,11 @@ Why would you use it? Imagine you have the following:
```re
validateAge(getAge(parseData(person)));
```
+
```ml
validateAge (getAge (parseData person))
```
+
```js
validateAge(getAge(parseData(person)));
```
@@ -34,12 +36,14 @@ person
->getAge
->validateAge;
```
+
```ml
person
|. parseData
|. getAge
|. validateAge
```
+
```js
validateAge(getAge(parseData(person)));
```
@@ -55,9 +59,11 @@ Basically, `parseData(person)` is transformed into `person->parseData`, and `get
```re
a(one, two, three);
```
+
```ml
a one two three
```
+
```js
a(one, two, three);
```
@@ -71,9 +77,11 @@ is the same as
```re
one->a(two, three);
```
+
```ml
one |. a two three
```
+
```js
a(one, two, three);
```
@@ -115,6 +123,7 @@ type request;
[@bs.send] external setWaitDuration: (request, int) => request = "setWaitDuration";
[@bs.send] external send: request => unit = "send";
```
+
```ml
external map: 'a array -> ('a -> 'b) -> 'b array = "map" [@@bs.send]
external filter: 'a array -> ('a -> bool) -> 'a array = "filter" [@@bs.send]
@@ -124,6 +133,7 @@ external asyncRequest: unit -> request = "asyncRequest" [@@bs.val]
external setWaitDuration: request -> int -> request = "setWaitDuration" [@@bs.send]
external send: request -> unit = "send" [@@bs.send]
```
+
```js
// Empty output
```
@@ -142,6 +152,7 @@ let result = Js.Array2.filter(
send(setWaitDuration(asyncRequest(), 4000));
```
+
```ml
let result = Js.Array2.filter
(Js.Array2.map [|1; 2; 3|] (fun a -> a + 1))
@@ -149,12 +160,15 @@ let result = Js.Array2.filter
let () = send (setWaitDuration (asyncRequest ()) 4000)
```
+
```js
-var result = [1, 2, 3].map(function(a) {
- return a + 1 | 0;
-}).filter(function(a) {
- return a % 2 === 0;
-});
+var result = [1, 2, 3]
+ .map(function (a) {
+ return (a + 1) | 0;
+ })
+ .filter(function (a) {
+ return a % 2 === 0;
+ });
asyncRequest().setWaitDuration(4000).send();
```
@@ -172,6 +186,7 @@ let result = [|1, 2, 3|]
asyncRequest()->setWaitDuration(4000)->send
```
+
```ml
let result = [|1; 2; 3|]
|. map(fun a -> a + 1)
@@ -179,12 +194,15 @@ let result = [|1; 2; 3|]
asyncRequest()->setWaitDuration(4000)->send
```
+
```js
-var result = [1, 2, 3].map(function(a) {
- return a + 1 | 0;
-}).filter(function(a) {
- return a % 2 === 0;
-});
+var result = [1, 2, 3]
+ .map(function (a) {
+ return (a + 1) | 0;
+ })
+ .filter(function (a) {
+ return a % 2 === 0;
+ });
asyncRequest().setWaitDuration(4000).send();
```
@@ -200,9 +218,11 @@ You can pipe into a variant's constructor as if it was a function:
```re
let result = name->preprocess->Some;
```
+
```ml
let result = name |. preprocess |. Some
```
+
```js
var result = preprocess(name);
```
@@ -216,9 +236,11 @@ We turn this into:
```re
let result = Some(preprocess(name));
```
+
```ml
let result = Some (preprocess name)
```
+
```js
var result = preprocess(name);
```
@@ -237,6 +259,7 @@ A placeholder is written as an underscore and it tells ReScript that you want to
let addTo7 = (x) => add3(3, x, 4);
let addTo7 = add3(3, _, 4);
```
+
```ml
(* doesn't exist in old ML syntax *)
```
@@ -253,10 +276,12 @@ Let's say you have a function `namePerson`, which takes a `person` then a `name`
makePerson(~age=47, ())
->namePerson("Jane");
```
+
```ml
makePerson ~age=47 ()
|. namePerson("Jane")
```
+
```js
namePerson(makePerson(47), "Jane");
```
@@ -271,9 +296,11 @@ If you have a name that you want to apply to a person object, you can use a plac
getName(input)
->namePerson(personDetails, _);
```
+
```ml
(* doesn't exist in old ML syntax *)
```
+
```js
var __x = getName(input);
namePerson(personDetails, __x);
@@ -289,9 +316,11 @@ This allows you to pipe into any positional argument. It also works for named ar
getName(input)
->namePerson(~person=personDetails, ~name=_);
```
+
```ml
(* doesn't exist in old ML syntax *)
```
+
```js
var __x = getName(input);
namePerson(personDetails, __x);
diff --git a/pages/docs/manual/v8.0.0/primitive-types.mdx b/pages/docs/manual/v8.0.0/primitive-types.mdx
index 73a59978a..e8e5513f2 100644
--- a/pages/docs/manual/v8.0.0/primitive-types.mdx
+++ b/pages/docs/manual/v8.0.0/primitive-types.mdx
@@ -19,11 +19,13 @@ let greeting = "Hello world!";
let multilineGreeting = "Hello
world!";
```
+
```ml
let greeting = "Hello world!"
let multilineGreeting = "Hello
world!";
```
+
```js
var greeting = "Hello world!";
var multilineGreeting = "Hello\n world!";
@@ -38,9 +40,11 @@ To concatenate strings, use `++`:
```re
let greetings = "Hello " ++ "world!";
```
+
```ml
let greetings = "Hello " ^ "world!"
```
+
```js
var greetings = "Hello world!";
```
@@ -62,12 +66,14 @@ World
$(name)
|j}
```
+
```ml
let greeting = {j|Hello
World
$(name)
|j}
```
+
```js
var greeting = "Hello\nWorld\n" + name + "\n";
```
@@ -101,11 +107,13 @@ ReScript has a type for a string with a single letter:
```re
let firstLetterOfAlphabet = 'a';
```
+
```ml
let firstLetterOfAlphabet = 'a'
```
+
```js
-var firstLetterOfAlphabet = /* "a" */97;
+var firstLetterOfAlphabet = /* "a" */ 97;
```
@@ -123,9 +131,11 @@ ReScript regular expressions compile cleanly to their JavaScript counterpart:
```re
let r = [%re "/b/g"];
```
+
```ml
let r = [%re "/b/g"]
```
+
```js
var r = /b/g;
```
diff --git a/pages/docs/manual/v8.0.0/promise.mdx b/pages/docs/manual/v8.0.0/promise.mdx
index 46adf62d7..d8fa52ec0 100644
--- a/pages/docs/manual/v8.0.0/promise.mdx
+++ b/pages/docs/manual/v8.0.0/promise.mdx
@@ -24,6 +24,7 @@ Js.Promise.make: (
) => unit
) => Js.Promise.t('a);
```
+
```mli
Js.Promise.make: (
resolve:(('a -> unit) [@bs]) ->
@@ -34,8 +35,7 @@ Js.Promise.make: (
-This type signature means that `make` takes a callback that takes 2 named arguments, `resolve` and `reject`. Both arguments are themselves [uncurried callbacks](
-function.md#uncurried-function) (with a dot). `make` returns the created promise.
+This type signature means that `make` takes a callback that takes 2 named arguments, `resolve` and `reject`. Both arguments are themselves [uncurried callbacks](function.md#uncurried-function) (with a dot). `make` returns the created promise.
## Usage
@@ -60,6 +60,7 @@ myPromise
Js.Promise.resolve(-2);
});
```
+
```ml
let myPromise = Js.Promise.make (fun ~resolve ~reject -> ((resolve 2) [@bs]))
@@ -77,6 +78,7 @@ let () = myPromise
Js.Promise.resolve -2
)
```
+
```js
var myPromise = new Promise(function (resolve, reject) {
return resolve(2);
diff --git a/pages/docs/manual/v8.0.0/record.mdx b/pages/docs/manual/v8.0.0/record.mdx
index d860476de..7ad957875 100644
--- a/pages/docs/manual/v8.0.0/record.mdx
+++ b/pages/docs/manual/v8.0.0/record.mdx
@@ -23,12 +23,14 @@ type person = {
name: string
};
```
+
```ml
type person = {
age: int;
name: string;
}
```
+
```js
// Empty output
```
@@ -47,16 +49,18 @@ let me = {
name: "Big ReScript"
};
```
+
```ml
let me = {
age = 5;
name = "Big ReScript";
}
```
+
```js
var me = {
age: 5,
- name: "Big ReScript"
+ name: "Big ReScript",
};
```
@@ -72,10 +76,12 @@ The type is found by looking above the `me` value. **Note**: if the type instead
// School.re
type person = {age: int, name: string};
```
+
```ml
(* School.ml *)
type person = {age: int; name: string}
```
+
```js
// Empty output
```
@@ -91,6 +97,7 @@ let me: School.person = {age: 20, name: "Big ReScript"};
/* or */
let me2 = {School.age: 20, name: "Big ReScript"};
```
+
```ml
(* Example.re *)
@@ -98,14 +105,15 @@ let me: School.person = {age = 20; name = "Big ReScript"}
(* or *)
let me2 = {School.age = 20; name = "Big ReScript"}
```
+
```js
var me = {
age: 20,
- name: "Big ReScript"
+ name: "Big ReScript",
};
var me2 = {
age: 20,
- name: "Big ReScript"
+ name: "Big ReScript",
};
```
@@ -122,9 +130,11 @@ Use the familiar dot notation:
```re
let name = me.name;
```
+
```ml
let name = me.name
```
+
```js
var name = "Big ReScript";
```
@@ -140,13 +150,15 @@ New records can be created from old records with the `...` spread operator. The
```re
let meNextYear = {...me, age: me.age + 1};
```
+
```ml
let meNextYear = {me with age = me.age + 1}
```
+
```js
var meNextYear = {
age: 21,
- name: "Big ReScript"
+ name: "Big ReScript",
};
```
@@ -169,6 +181,7 @@ type person = {
let baby = {name: "Baby ReScript", age: 5};
baby.age = baby.age + 1; // `baby.age` is now 6. Happy birthday!
```
+
```ml
type person = {
name: string;
@@ -178,13 +191,14 @@ type person = {
let baby = {name = "Baby ReScript"; age = 5}
let () = baby.age <- baby.age + 1 (* `baby.age` is now 6. Happy birthday! *)
```
+
```js
var baby = {
name: "Baby ReScript",
- age: 5
+ age: 5,
};
-baby.age = baby.age + 1 | 0;
+baby.age = (baby.age + 1) | 0;
```
@@ -201,12 +215,14 @@ type monster = {age: int, hasTentacles: bool};
let getAge = (entity) => entity.age;
```
+
```ml
type person = {age: int; name: string}
type monster = {age: int; hasTentacles: bool}
let getAge entity = entity.age
```
+
```js
function getAge(entity) {
return entity.age;
@@ -226,6 +242,7 @@ let me = {age: 5, name: "Baby ReScript"};
getAge(kraken);
getAge(me); // type error!
```
+
```ml
let kraken = {age = 9999; hasTentacles = true}
let me = {age = 5; name = "Baby ReScript"}
diff --git a/pages/docs/manual/v8.0.0/shared-data-types.mdx b/pages/docs/manual/v8.0.0/shared-data-types.mdx
index 851af21db..8422611dc 100644
--- a/pages/docs/manual/v8.0.0/shared-data-types.mdx
+++ b/pages/docs/manual/v8.0.0/shared-data-types.mdx
@@ -13,6 +13,7 @@ This means that if you're passing e.g. a ReScript string to the JavaScript side,
Unlike most compiled-to-js languages, in ReScript, **you don't need to write data converters back and forth for most of our values**!
**Shared, bidirectionally usable types**:
+
- String. Backtick strings like `` `hello $(personName)` `` (in old ML syntax: `{j|hello $(personName)|j}`) support interpolation. Normal `"hello"` strings don't.
- Float. ReScript floats are JS numbers, vice-versa.
- Array. In addition to the [JS Array API](api/js/array), we provide our own [Belt.Array](api/belt/array#set) API too.
@@ -27,6 +28,7 @@ Unlike most compiled-to-js languages, in ReScript, **you don't need to write dat
**Types that are slightly different than JS, but that you can still use from JS**:
+
- Int. **Ints are 32-bits**! Be careful, you can potentially treat them as JS numbers and vice-versa, but if the number's large, then you better treat JS numbers as floats. For example, we bind to [`Js.Date`](api/js/date) using `float`s.
- Option. The `option` type's `None` value compiles into JS `undefined`. The `Some` value, e.g. `Some(5)`, compiles to `5`. Likewise, you can treat an incoming JS `undefined` as `None`. **JS `null` isn't handled here**. If your JS value can be `null`, use [Js.Nullable](api/js/nullable) helpers.
- Exception.
diff --git a/pages/docs/manual/v8.0.0/try.mdx b/pages/docs/manual/v8.0.0/try.mdx
index 36dc995de..0c44c192b 100644
--- a/pages/docs/manual/v8.0.0/try.mdx
+++ b/pages/docs/manual/v8.0.0/try.mdx
@@ -20,6 +20,7 @@ let rec fib = n => {
};
Js.log(fib(0));
```
+
```ml
// MyFile.ml
let rec fib n =
@@ -54,6 +55,7 @@ You can also get the inferred signature directly via `bsc -i MyFile.re`
```rei
let fib: int => int;
```
+
```mli
val fib: int => int
```
diff --git a/pages/docs/manual/v8.0.0/tuple.mdx b/pages/docs/manual/v8.0.0/tuple.mdx
index 4102f4de9..bab511fd9 100644
--- a/pages/docs/manual/v8.0.0/tuple.mdx
+++ b/pages/docs/manual/v8.0.0/tuple.mdx
@@ -19,10 +19,12 @@ Tuples are a ReScript-specific data structure that don't exist in JavaScript. Th
let ageAndName = (24, "Lil' ReScript");
let my3dCoordinates = (20.0, 30.5, 100.0);
```
+
```ml
let ageAndName = (24, "Lil' ReScript")
let my3dCoordinates = (20.0, 30.5, 100.0)
```
+
```js
var ageAndName = [24, "Lil' ReScript"];
var my3dCoordinates = [20.0, 30.5, 100.0];
@@ -40,16 +42,19 @@ let ageAndName: (int, string) = (24, "Lil' ReScript");
type coord3d = (float, float, float);
let my3dCoordinates: coord3d = (20.0, 30.5, 100.0);
```
+
```ml
let ageAndName: (int * string) = (24, "Lil' ReScript")
(* a tuple type alias *)
type coord3d = (float * float * float)
let my3dCoordinates: coord3d = (20.0, 30.5, 100.0)
```
+
```js
var ageAndName = [24, "Lil' ReScript"];
var my3dCoordinates = [20.0, 30.5, 100.0];
```
+
**Note**: there's no tuple of size 1. You'd just use the value itself.
@@ -63,9 +68,11 @@ To get a specific member of a tuple, destructure it:
```re
let (_, y, _) = my3dCoordinates; // now you've retrieved y
```
+
```ml
let (_, y, _) = my3dCoordinates; (* now you've retrieved y *)
```
+
```js
var y = 30.5;
```
@@ -83,11 +90,13 @@ let coordinates1 = (10, 20, 30);
let (c1x, _, _) = coordinates1;
let coordinates2 = (c1x + 50, 20, 30);
```
+
```ml
let coordinates1 = (10, 20, 30)
let (c1x, _, _) = coordinates1
let coordinates2 = (c1x + 50, 20, 30)
```
+
```js
var coordinates1 = [10, 20, 30];
var c1x = 10;
@@ -109,12 +118,14 @@ let getCenterCoordinates = () => {
(x, y)
};
```
+
```ml
let getCenterCoordinates () =
let x = doSomeOperationsHere () in
let y = doSomeMoreOperationsHere () in
(x, y)
```
+
```js
function getCenterCoordinates(param) {
var x = doSomeOperationsHere(undefined);
diff --git a/pages/docs/manual/v8.0.0/type.mdx b/pages/docs/manual/v8.0.0/type.mdx
index c51d0a4ca..83822011f 100644
--- a/pages/docs/manual/v8.0.0/type.mdx
+++ b/pages/docs/manual/v8.0.0/type.mdx
@@ -7,6 +7,7 @@ canonical: "/docs/manual/latest/type"
# Type
Types are the highlight of ReScript! They are:
+
- **Strong**. A type can't change into another type. In JavaScript, your variable's type might change when the code runs (aka at runtime). E.g. a `number` variable might change into a `string` sometimes. This is an anti-feature; it makes the code much harder to understand when reading or debugging.
- **Static**. ReScript types are erased after compilation and don't exist at runtime. Never worry about your types dragging down performance. You don't need type info during runtime; we report all the information (especially all the type errors) during compile time. Catch the bugs earlier!
- **Sound**. This is our biggest differentiator versus many other typed languages that compile to JavaScript. Our type system is guaranteed to **never** be wrong. Most type systems make a guess at the type of a value and show you a type in your editor that's sometime incorrect. We don't do that. We believe that a type system that is sometime incorrect can end up being dangerous due to expectation mismatches.
@@ -25,14 +26,16 @@ This let-binding doesn't contain any written type:
let score = 10;
let add = (a, b) => a + b;
```
+
```ml
let score = 10
let add a b = a + b
```
+
```js
var score = 10;
function add(a, b) {
- return a + b | 0;
+ return (a + b) | 0;
}
```
@@ -49,9 +52,11 @@ But you can also optionally write down the type, aka annotate your value:
```re
let score: int = 10;
```
+
```ml
let score: int = 10
```
+
```js
var score = 10;
```
@@ -71,6 +76,7 @@ let myInt = (5: int) + (4: int);
let add = (x: int, y: int) : int => x + y;
let drawCircle = (~radius as r: int): circleType => /* code here */;
```
+
```ml
let myInt = 5
let myInt: int = 5
@@ -78,10 +84,11 @@ let myInt = (5 : int) + (4 : int)
let add (x : int) (y : int) = (x + y : int)
let drawCircle ~radius:(r : int) : circleType = (* code here *)
```
+
```js
var myInt = 9;
function add(x, y) {
- return x + y | 0;
+ return (x + y) | 0;
}
function drawCircle(r) {
/* code here */
@@ -102,10 +109,12 @@ You can refer to a type by a different name. They'll be equivalent:
type scoreType = int;
let x: scoreType = 10;
```
+
```ml
type scoreType = int
let x: scoreType = 10
```
+
```js
var x = 10;
```
@@ -128,6 +137,7 @@ type floatCoordinates = (float, float, float);
let a: intCoordinates = (10, 20, 20);
let b: floatCoordinates = (10.5, 20.5, 20.5);
```
+
```ml
(* this is a tuple of 3 items, explained next *)
type intCoordinates = (int, int, int)
@@ -136,6 +146,7 @@ type floatCoordinates = (float, float, float)
let a: intCoordinates = (10, 20, 20)
let b: floatCoordinates = (10.5, 20.5, 20.5)
```
+
```js
var a = [10, 20, 20];
var b = [10.5, 20.5, 20.5];
@@ -153,12 +164,14 @@ type coordinates('a) = ('a, 'a, 'a);
let a: coordinates(int) = (10, 20, 20);
let b: coordinates(float) = (10.5, 20.5, 20.5);
```
+
```ml
type 'a coordinates = ('a * 'a * 'a)
let a: int coordinates = (10, 20, 20)
let b: float coordinates = (10.5, 20.5, 20.5)
```
+
```js
var a = [10, 20, 20];
var b = [10.5, 20.5, 20.5];
@@ -173,9 +186,11 @@ Note that the above codes are just contrived examples for illustration purposes.
```re
let buddy = (10, 20, 20);
```
+
```ml
let buddy = (10, 20, 20)
```
+
```js
var buddy = [10, 20, 20];
```
@@ -192,10 +207,12 @@ Type arguments appear in many places. Our `array('a)` type is such a type that r
// inferred as `array(string)`
let greetings = [|"hello", "world", "how are you"|];
```
+
```ml
(* inferred as `string array` *)
let greetings = [|"hello"; "world"; "how are you"|]
```
+
```js
var greetings = ["hello", "world", "how are you"];
```
@@ -225,6 +242,7 @@ let payloadResults: myPayloadResults(string) = [|
Error("Something wrong happened!")
|];
```
+
```ml
type ('a, 'b) result =
| Ok of 'a
@@ -242,20 +260,21 @@ let payloadResults: string myPayloadResults = [|
Error("Something wrong happaned!");
|]
```
+
```js
var payloadResults = [
{
- TAG: /* Ok */0,
- _0: {data: "hi"}
+ TAG: /* Ok */ 0,
+ _0: { data: "hi" },
},
{
- TAG: /* Ok */0,
- _0: {data: "bye"}
+ TAG: /* Ok */ 0,
+ _0: { data: "bye" },
},
{
- TAG: /* Error */1,
- _0: "Something wrong happened!"
- }
+ TAG: /* Error */ 1,
+ _0: "Something wrong happened!",
+ },
];
```
@@ -273,12 +292,14 @@ type person = {
friends: array(person)
}
```
+
```ml
type person = {
name: string;
friends: person array;
}
```
+
```js
// Empty output
```
@@ -297,10 +318,12 @@ Types can also be _mutually_ recursive through `and`:
type student = {taughtBy: teacher}
and teacher = {students: array(student)};
```
+
```ml
type student = {taughtBy: teacher}
and teacher = {students: student array}
```
+
```js
// Empty output
```
@@ -316,9 +339,11 @@ ReScript's type system is robust and does not allow dangerous, unsafe stuff like
```re
external myShadyConversion: myType1 => myType2 = "%identity";
```
+
```ml
external myShadyConversion: myType1 -> myType2 = "%identity"
```
+
```js
// Empty output
```
@@ -334,11 +359,13 @@ external convertToFloat : int => float = "%identity";
let age = 10;
let gpa = 2.1 +. convertToFloat(age);
```
+
```ml
external convertToFloat : int -> float = "%identity"
let age = 10
let gpa = 2.1 +. (convertToFloat age)
```
+
```js
var age = 10;
var gpa = 2.1 + 10;
diff --git a/pages/docs/manual/v8.0.0/use-illegal-identifier-names.mdx b/pages/docs/manual/v8.0.0/use-illegal-identifier-names.mdx
index e9af30ebb..0c6200f53 100644
--- a/pages/docs/manual/v8.0.0/use-illegal-identifier-names.mdx
+++ b/pages/docs/manual/v8.0.0/use-illegal-identifier-names.mdx
@@ -14,9 +14,10 @@ This page is solely dedicated to Reason v3.6 related naming collisions and also
JavaScript has different naming conventions and has only very few limitations when it comes to naming variables, classes, functions, JS object attributes etc.
-Reason on the contrary has more restrictive naming rules which need to be considered whenever you define a type, function, value, module, record attribute or similar. Here are a few typical naming restrictions which cause trouble with JS:
+Reason on the contrary has more restrictive naming rules which need to be considered whenever you define a type, function, value, module, record attribute or similar. Here are a few typical naming restrictions which cause trouble with JS:
+
- Every name needs to start with a lowercase letter (uppercase is reserved for module names)
-- For the same reason, names can't be all caps (very common for JS constants: `const MY_CONSTANT = "my_constant"`)
+- For the same reason, names can't be all caps (very common for JS constants: `const MY_CONSTANT = "my_constant"`)
- It's not possible to use [reserved keywords](/docs/manual/latest/reserved-keywords) for names
- Labeled arguments (for defining JSX attributes) can't be named after keywords and can't start with an uppercase letter
- etc.
@@ -40,6 +41,7 @@ If you're using a React component with a reserved keyword as a prop name, then s
/* This works because `_type` is not a reserved keyword */
```
+
```ml
(* Doesn't exist in old ML syntax *)
```
@@ -79,6 +81,7 @@ let payload = {
/* ReScript is happy since we're using the valid `postTitle` field name */
let title = payload.postTitle;
```
+
```ml
type payload = {
postTitle: string [@bs.as "PostTitle"]
@@ -91,6 +94,7 @@ let payload = {
(* ReScript is happy since we're using the valid `postTitle` field name *)
let title = payload.postTitle
```
+
```js
/* The correct capitalized field name is output in the JavaScript! */
var title = payload.PostTitle;
@@ -100,7 +104,7 @@ var title = payload.PostTitle;
## Accessing reserved keywords as JavaScript object attribute names
-Just like accessing attributes that start with a capital letter, we can use `[@bs.as "the-reserved-keyword-that-javascript-wants"]`. It's customary to append an underscore (unlike the JSX case, where we *prepend* the underscore) to the reserved keyword name:
+Just like accessing attributes that start with a capital letter, we can use `[@bs.as "the-reserved-keyword-that-javascript-wants"]`. It's customary to append an underscore (unlike the JSX case, where we _prepend_ the underscore) to the reserved keyword name:
@@ -116,6 +120,7 @@ let payload = {
/* ReScript is happy since we're using the valid `type_` field name */
let payloadType = payload.type_;
```
+
```ml
type payload = {
type_: string [@bs.as "type"]
@@ -128,6 +133,7 @@ let payload = {
(* ReScript is happy since we're using the valid `type_` field name *)
let payloadType = payload.type_
```
+
```js
/* The reason compiler has correctly ouput `payload.type` even though *we* called the field `type_` */
var payloadType = payload.type;
@@ -145,7 +151,7 @@ var payloadType = payload.type;
When accessing a JavaScript object field in a structural way (e.g. `myJsObject##some`), the following rules apply:
-1. A single _leading_ underscore will be *dropped* from the output: `myJsObject##_type` => `myJsObject.type`
-1. Two (or more) _leading_ underscores will be *kept* in the output: `myJsObject##__type` => `myJsObject.__type`
+1. A single _leading_ underscore will be _dropped_ from the output: `myJsObject##_type` => `myJsObject.type`
+1. Two (or more) _leading_ underscores will be _kept_ in the output: `myJsObject##__type` => `myJsObject.__type`
1. There is _no way_ to access e.g. `myJsObject##_type` structurally - use records and `[@bs.as "_type"]` instead
1. The _final trailing_ double underscores (and anything following them) will be dropped from the output: `myJsObject##this_is_kept__this_is_omitted` => `myJsObject.this_is_kept`
diff --git a/pages/docs/manual/v8.0.0/variant.mdx b/pages/docs/manual/v8.0.0/variant.mdx
index 2905f1d94..0d359a44a 100644
--- a/pages/docs/manual/v8.0.0/variant.mdx
+++ b/pages/docs/manual/v8.0.0/variant.mdx
@@ -20,6 +20,7 @@ type myResponse =
let areYouCrushingIt = Yes;
```
+
```ml
type myResponse =
| Yes
@@ -28,8 +29,9 @@ type myResponse =
let areYouCrushingIt = Yes
```
+
```js
-var areYouCrushingIt = /* Yes */0;
+var areYouCrushingIt = /* Yes */ 0;
```
@@ -48,10 +50,12 @@ If the variant you're using is in a different file, bring it into scope like you
// Zoo.re
type animal = Dog | Cat | Bird;
```
+
```ml
(* Zoo.re *)
type animal = Dog | Cat | Bird
```
+
```js
// Empty output
```
@@ -66,15 +70,17 @@ let pet: Zoo.animal = Dog; // preferred
// or
let pet2 = Zoo.Dog;
```
+
```ml
(* Example.re *)
let pet: Zoo.animal = Dog (* preferred *)
(* or *)
let pet2 = Zoo.Dog
```
+
```js
-var pet = /* Dog */0;
-var pet2 = /* Dog */0;
+var pet = /* Dog */ 0;
+var pet2 = /* Dog */ 0;
```
@@ -91,12 +97,14 @@ type account =
| Instagram(string)
| Facebook(string, int);
```
+
```ml
type account =
| None
| Instagram of string
| Facebook of string * int
```
+
```js
// Empty output
```
@@ -111,21 +119,23 @@ Here, `Instagram` holds a `string`, and `Facebook` holds a `string` and an `int`
let myAccount = Facebook("Josh", 26);
let friendAccount = Instagram("Jenny");
```
+
```ml
let myAccount =
Facebook ("Josh", 26)
let friendAccount =
Instagram "Jenny"
```
+
```js
var myAccount = {
- TAG: /* Facebook */1,
+ TAG: /* Facebook */ 1,
_0: "Josh",
- _1: 26
+ _1: 26,
};
var friendAccount = {
- TAG: /* Instagram */0,
- _0: "Jenny"
+ TAG: /* Instagram */ 0,
+ _0: "Jenny",
};
```
@@ -144,6 +154,7 @@ type user =
| Number(int)
| Id(idType);
```
+
```ml
type idType = {name: string; password: string}
@@ -151,6 +162,7 @@ type user =
| Number of int
| Id of idType
```
+
```js
// Empty output
```
@@ -166,11 +178,13 @@ type user =
| Number(int)
| Id({name: string, password: string});
```
+
```ml
type user =
| Number of int
| Id of {name: string; password: string}
```
+
```js
// Empty output
```
@@ -193,12 +207,14 @@ type account =
type account2 =
| Instagram((string, int)); // 1 argument - happens to be a 2-tuple
```
+
```ml
type account =
| Facebook of string * int (* 2 arguments *)
type account2 =
| Instagram of (string * int) (* 1 argument - happens to be a 2-tuple *)
```
+
```js
// Empty output
```
@@ -233,6 +249,7 @@ let betterDraw = (animal) =>
betterDraw(MyFloat(1.5));
```
+
```ml
(* reserved for internal usage *)
external draw: 'a => unit = "draw" [@@bs.module "myLibrary"]
@@ -248,6 +265,7 @@ let betterDraw animal =
let () = betterDraw (MyFloat 1.5)
```
+
```js
var MyLibrary = require("myLibrary");
@@ -256,8 +274,8 @@ function betterDraw(animal) {
}
betterDraw({
- TAG: /* MyFloat */0,
- _0: 1.5
+ TAG: /* MyFloat */ 0,
+ _0: 1.5,
});
```
@@ -271,10 +289,12 @@ You could definitely do that, but there are better ways! For example, define two
[@bs.module "myLibrary"] external drawFloat: float => unit = "draw";
[@bs.module "myLibrary"] external drawString: string => unit = "draw";
```
+
```ml
external drawFloat: float -> unit = "draw" [@@bs.module "myLibrary"]
external drawString: string -> unit = "draw" [@@bs.module "myLibrary"]
```
+
```js
// Empty output
```
@@ -319,6 +339,7 @@ switch (data) {
| Bird => Js.log("Kashiiin")
}
```
+
```ml
type animal = Dog | Cat | Bird
let data = Dog
@@ -328,10 +349,11 @@ let () =
| Cat -> Js.log "Meow"
| Bird -> Js.log "Kashiiin"
```
+
```js
console.log("Wof");
-var data = /* Dog */0;
+var data = /* Dog */ 0;
```
diff --git a/pages/docs/manual/v9.0.0/api/belt/array.mdx b/pages/docs/manual/v9.0.0/api/belt/array.mdx
index 457aa9afe..f5483a892 100644
--- a/pages/docs/manual/v9.0.0/api/belt/array.mdx
+++ b/pages/docs/manual/v9.0.0/api/belt/array.mdx
@@ -8,7 +8,7 @@ Utililites for `Array` functions.
### Note about index syntax
-Code like `arr[0]` does *not* compile to JavaScript `arr[0]`. ReScript transforms the `[]` index syntax into a function: `Array.get(arr, 0)`. By default, this uses the default standard library's `Array.get` function, which may raise an exception if the index isn't found. If you `open Belt`, it will use the `Belt.Array.get` function which returns options instead of raising exceptions. [See this for more information](../belt.mdx#array-access-runtime-safety).
+Code like `arr[0]` does _not_ compile to JavaScript `arr[0]`. ReScript transforms the `[]` index syntax into a function: `Array.get(arr, 0)`. By default, this uses the default standard library's `Array.get` function, which may raise an exception if the index isn't found. If you `open Belt`, it will use the `Belt.Array.get` function which returns options instead of raising exceptions. [See this for more information](../belt.mdx#array-access-runtime-safety).
## length
diff --git a/pages/docs/manual/v9.0.0/api/belt/int.mdx b/pages/docs/manual/v9.0.0/api/belt/int.mdx
index 76fa52fbb..3e3a31c36 100644
--- a/pages/docs/manual/v9.0.0/api/belt/int.mdx
+++ b/pages/docs/manual/v9.0.0/api/belt/int.mdx
@@ -38,7 +38,6 @@ Converts a given `string` to an `int`. Returns `Some(int)` when the input is a n
Js.log(Belt.Int.fromString("1") === Some(1)) /* true */
```
-
## toString
```res sig
diff --git a/pages/docs/manual/v9.0.0/api/belt/list.mdx b/pages/docs/manual/v9.0.0/api/belt/list.mdx
index b077fa75f..d88f95805 100644
--- a/pages/docs/manual/v9.0.0/api/belt/list.mdx
+++ b/pages/docs/manual/v9.0.0/api/belt/list.mdx
@@ -549,6 +549,7 @@ Equivalent to: `zipBy(xs, ys, f)->reverse`
Belt.List.mapReverse2(list{1, 2, 3}, list{1, 2}, (a, b) => a + b) // list{4, 2}
```
+
## mapReverse2U
```res sig
diff --git a/pages/docs/manual/v9.0.0/api/belt/option.mdx b/pages/docs/manual/v9.0.0/api/belt/option.mdx
index 4e80c7b89..7cd48cca4 100644
--- a/pages/docs/manual/v9.0.0/api/belt/option.mdx
+++ b/pages/docs/manual/v9.0.0/api/belt/option.mdx
@@ -3,7 +3,7 @@
In Belt we represent the existence and nonexistence of a value by wrapping it
-with the `option` type. In order to make it a bit more convenient to work with
+with the `option` type. In order to make it a bit more convenient to work with
option-types, Belt provides utility-functions for it.
The `option` type is a part of the Reason / OCaml standard library which is defined like this:
diff --git a/pages/docs/manual/v9.0.0/api/belt/range.mdx b/pages/docs/manual/v9.0.0/api/belt/range.mdx
index 983789986..d4e50bb87 100644
--- a/pages/docs/manual/v9.0.0/api/belt/range.mdx
+++ b/pages/docs/manual/v9.0.0/api/belt/range.mdx
@@ -3,7 +3,7 @@
A small utility module to provide inclusive range operations for `[start,
-finish]`. Internally it is relying on loops instead of creating new arrays,
+finish]`. Internally it is relying on loops instead of creating new arrays,
which makes it pretty performant and memory friendly.
diff --git a/pages/docs/manual/v9.0.0/api/belt/set-dict.mdx b/pages/docs/manual/v9.0.0/api/belt/set-dict.mdx
index 19ac4be4b..b1d87ef72 100644
--- a/pages/docs/manual/v9.0.0/api/belt/set-dict.mdx
+++ b/pages/docs/manual/v9.0.0/api/belt/set-dict.mdx
@@ -677,4 +677,3 @@ let checkInvariantInternal: t<'a, 'b> => unit
```
**raise** when invariant is not held
-
diff --git a/pages/docs/manual/v9.0.0/api/belt/set-int.mdx b/pages/docs/manual/v9.0.0/api/belt/set-int.mdx
index c21e8deba..994a45772 100644
--- a/pages/docs/manual/v9.0.0/api/belt/set-int.mdx
+++ b/pages/docs/manual/v9.0.0/api/belt/set-int.mdx
@@ -534,4 +534,3 @@ let checkInvariantInternal: t => unit
```
**raise** when invariant is not held
-
diff --git a/pages/docs/manual/v9.0.0/api/belt/set-string.mdx b/pages/docs/manual/v9.0.0/api/belt/set-string.mdx
index bf21b7964..1e2815f61 100644
--- a/pages/docs/manual/v9.0.0/api/belt/set-string.mdx
+++ b/pages/docs/manual/v9.0.0/api/belt/set-string.mdx
@@ -535,4 +535,3 @@ let checkInvariantInternal: t => unit
```
**raise** when invariant is not held
-
diff --git a/pages/docs/manual/v9.0.0/api/dom.mdx b/pages/docs/manual/v9.0.0/api/dom.mdx
index eee448156..b74050f73 100644
--- a/pages/docs/manual/v9.0.0/api/dom.mdx
+++ b/pages/docs/manual/v9.0.0/api/dom.mdx
@@ -471,7 +471,7 @@ type htmlPreElement
## htmlProgressElement
```res sig
-type htmlProgressElement
+type htmlProgressElement
```
## htmlQuoteElement
@@ -489,7 +489,7 @@ type htmlScriptElement
## htmlSelectElement
```res sig
-type htmlSelectElement
+type htmlSelectElement
```
## htmlSlotElement
@@ -630,7 +630,7 @@ type xmlDocument
type event
```
-## uiEvent
+## uiEvent
```res sig
type uiEvent
diff --git a/pages/docs/manual/v9.0.0/api/js.mdx b/pages/docs/manual/v9.0.0/api/js.mdx
index d3aea4c57..c8f023802 100644
--- a/pages/docs/manual/v9.0.0/api/js.mdx
+++ b/pages/docs/manual/v9.0.0/api/js.mdx
@@ -35,6 +35,7 @@ Js.log("ReScript"->Js.String.startsWith("Re", _))
Js.log(Js.String.split("-", "2019-11-10"))
Js.log(Js.String.startsWith("Re", "ReScript"))
```
+
## Js.Xxx2 Modules
Prefer `Js.Array2` over `Js.Array`, `Js.String2` over `Js.String`, etc. The latters are old modules.
diff --git a/pages/docs/manual/v9.0.0/api/js/array-2.mdx b/pages/docs/manual/v9.0.0/api/js/array-2.mdx
index 393134ce6..ad627fab9 100644
--- a/pages/docs/manual/v9.0.0/api/js/array-2.mdx
+++ b/pages/docs/manual/v9.0.0/api/js/array-2.mdx
@@ -26,6 +26,7 @@ let result = {
[5, 2, 3, 4, 1]->filter(isEven)->map(square)->reduce(\"+", 0)
}
```
+
## t
@@ -63,7 +64,7 @@ Js.Array2.from(strArr) == ["a", "b", "c", "d"]
let fromMap: (array_like<'a>, 'a => 'b) => array<'b>
```
-Creates a new array by applying a function (the second argument) to each item in the `array_like` first argument. See [`Array.from`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from) on MDN.
+Creates a new array by applying a function (the second argument) to each item in the `array_like` first argument. See [`Array.from`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from) on MDN.
```res example
let strArr = Js.String.castToArrayLike("abcd")
@@ -99,7 +100,7 @@ Returns the number of elements in the array. See [`Array.length`](https://develo
let copyWithin: (t<'a>, ~to_: int) => t<'a>
```
-Copies from the first element in the given array to the designated `~to_` position, returning the resulting array. *This function modifies the original array.* See [`Array.copyWithin`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/copyWithin) on MDN.
+Copies from the first element in the given array to the designated `~to_` position, returning the resulting array. _This function modifies the original array._ See [`Array.copyWithin`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/copyWithin) on MDN.
```res example
let arr = [100, 101, 102, 103, 104]
@@ -113,7 +114,7 @@ arr == [100, 101, 100, 101, 102]
let copyWithinFrom: (t<'a>, ~to_: int, ~from: int) => t<'a>
```
-Copies starting at element `~from` in the given array to the designated `~to_` position, returning the resulting array. *This function modifies the original array.* See [`Array.copyWithin`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/copyWithin) on MDN.
+Copies starting at element `~from` in the given array to the designated `~to_` position, returning the resulting array. _This function modifies the original array._ See [`Array.copyWithin`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/copyWithin) on MDN.
```res example
let arr = [100, 101, 102, 103, 104]
@@ -127,7 +128,7 @@ arr == [102, 103, 104, 103, 104]
let copyWithinFromRange: (t<'a>, ~to_: int, ~start: int, ~end_: int) => t<'a>
```
-Copies starting at element `~start` in the given array up to but not including `~end_` to the designated `~to_` position, returning the resulting array. *This function modifies the original array.* See [`Array.copyWithin`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/copyWithin) on MDN.
+Copies starting at element `~start` in the given array up to but not including `~end_` to the designated `~to_` position, returning the resulting array. _This function modifies the original array._ See [`Array.copyWithin`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/copyWithin) on MDN.
```res example
let arr = [100, 101, 102, 103, 104, 105]
@@ -140,7 +141,8 @@ arr == [100, 102, 103, 104, 104, 105]
```res sig
let fillInPlace: (t<'a>, 'a) => t<'a>
```
-Sets all elements of the given array (the first arumgent) to the designated value (the secon argument), returning the resulting array. *This function modifies the original array.* See [`Array.fill`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/fill) on MDN.
+
+Sets all elements of the given array (the first arumgent) to the designated value (the secon argument), returning the resulting array. _This function modifies the original array._ See [`Array.fill`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/fill) on MDN.
```res example
let arr = [100, 101, 102, 103, 104]
@@ -153,7 +155,8 @@ arr == [99, 99, 99, 99, 99]
```res sig
let fillFromInPlace: (t<'a>, 'a, ~from: int) => t<'a>
```
-Sets all elements of the given array (the first arumgent) from position `~from` to the end to the designated value (the second argument), returning the resulting array. *This function modifies the original array.* See [`Array.fill`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/fill) on MDN.
+
+Sets all elements of the given array (the first arumgent) from position `~from` to the end to the designated value (the second argument), returning the resulting array. _This function modifies the original array._ See [`Array.fill`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/fill) on MDN.
```res example
let arr = [100, 101, 102, 103, 104]
@@ -166,7 +169,8 @@ arr == [100, 101, 99, 99, 99]
```res sig
let fillRangeInPlace: (t<'a>, 'a, ~start: int, ~end_: int) => t<'a>
```
-Sets the elements of the given array (the first arumgent) from position `~start` up to but not including position `~end_` to the designated value (the second argument), returning the resulting array. *This function modifies the original array.* See [`Array.fill`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/fill) on MDN.
+
+Sets the elements of the given array (the first arumgent) from position `~start` up to but not including position `~end_` to the designated value (the second argument), returning the resulting array. _This function modifies the original array._ See [`Array.fill`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/fill) on MDN.
```res example
let arr = [100, 101, 102, 103, 104]
@@ -179,7 +183,8 @@ arr == [100, 99, 99, 99, 104]
```res sig
let pop: t<'a> => option<'a>
```
-If the array is not empty, removes the last element and returns it as `Some(value)`; returns `None` if the array is empty. *This function modifies the original array.* See [`Array.pop`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/pop) on MDN.
+
+If the array is not empty, removes the last element and returns it as `Some(value)`; returns `None` if the array is empty. _This function modifies the original array._ See [`Array.pop`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/pop) on MDN.
```res example
let arr = [100, 101, 102, 103, 104]
@@ -195,7 +200,8 @@ Js.Array2.pop(empty) == None
```res sig
let push: (t<'a>, 'a) => int
```
-Appends the given value to the array, returning the number of elements in the updated array. *This function modifies the original array.* See [`Array.push`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push) on MDN.
+
+Appends the given value to the array, returning the number of elements in the updated array. _This function modifies the original array._ See [`Array.push`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push) on MDN.
```res example
let arr = ["ant", "bee", "cat"]
@@ -208,7 +214,8 @@ arr == ["ant", "bee", "cat", "dog"]
```res sig
let pushMany: (t<'a>, array<'a>) => int
```
-Appends the values from one array (the second argument) to another (the first argument), returning the number of elements in the updated array. *This function modifies the original array.* See [`Array.push`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push) on MDN.
+
+Appends the values from one array (the second argument) to another (the first argument), returning the number of elements in the updated array. _This function modifies the original array._ See [`Array.push`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push) on MDN.
```res example
let arr = ["ant", "bee", "cat"]
@@ -221,7 +228,8 @@ arr == ["ant", "bee", "cat", "dog", "elk"]
```res sig
let reverseInPlace: t<'a> => t<'a>
```
-Returns an array with the elements of the input array in reverse order. *This function modifies the original array.* See [`Array.reverse`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse) on MDN.
+
+Returns an array with the elements of the input array in reverse order. _This function modifies the original array._ See [`Array.reverse`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse) on MDN.
```res example
let arr = ["ant", "bee", "cat"]
@@ -234,7 +242,8 @@ arr == ["cat", "bee", "ant"]
```res sig
let shift: t<'a> => option<'a>
```
-If the array is not empty, removes the first element and returns it as `Some(value)`; returns `None` if the array is empty. *This function modifies the original array.* See [`Array.shift`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/shift) on MDN.
+
+If the array is not empty, removes the first element and returns it as `Some(value)`; returns `None` if the array is empty. _This function modifies the original array._ See [`Array.shift`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/shift) on MDN.
```res example
let arr = [100, 101, 102, 103, 104]
@@ -250,7 +259,8 @@ Js.Array2.shift(empty) == None
```res sig
let sortInPlace: t<'a> => t<'a>
```
-Sorts the given array in place and returns the sorted array. JavaScript sorts the array by converting the arguments to UTF-16 strings and sorting them. See the second example with sorting numbers, which does not do a numeric sort. *This function modifies the original array.* See [`Array.sort`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort) on MDN.
+
+Sorts the given array in place and returns the sorted array. JavaScript sorts the array by converting the arguments to UTF-16 strings and sorting them. See the second example with sorting numbers, which does not do a numeric sort. _This function modifies the original array._ See [`Array.sort`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort) on MDN.
```res example
let words = ["bee", "dog", "ant", "cat"]
@@ -267,13 +277,14 @@ numbers == [1, 10, 2, 20, 3, 30]
```res sig
let sortInPlaceWith: (t<'a>, ('a, 'a) => int) => t<'a>
```
-Sorts the given array in place and returns the sorted array. *This function modifies the original array.*
+
+Sorts the given array in place and returns the sorted array. _This function modifies the original array._
The first argument to `sortInPlaceWith()` is a function that compares two items from the array and returns:
-* an integer less than zero if the first item is less than the second item
-* zero if the items are equal
-* an integer greater than zero if the first item is greater than the second item
+- an integer less than zero if the first item is less than the second item
+- zero if the items are equal
+- an integer greater than zero if the first item is greater than the second item
See [`Array.sort`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort) on MDN.
@@ -295,7 +306,8 @@ Js.Array2.sortInPlaceWith(numbers, reverseNumeric) == [30, 20, 10, 3, 2, 1]
```res sig
let spliceInPlace: (t<'a>, ~pos: int, ~remove: int, ~add: array<'a>) => t<'a>
```
-Starting at position `~pos`, remove `~remove` elements and then add the elements from the `~add` array. Returns an array consisting of the removed items. *This function modifies the original array.* See [`Array.splice`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice) on MDN.
+
+Starting at position `~pos`, remove `~remove` elements and then add the elements from the `~add` array. Returns an array consisting of the removed items. _This function modifies the original array._ See [`Array.splice`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice) on MDN.
```res example
let arr = ["a", "b", "c", "d", "e", "f"]
@@ -316,7 +328,8 @@ arr3 == ["a", "b", "c", "d", "e", "f", "x", "y", "z"]
```res sig
let removeFromInPlace: (t<'a>, ~pos: int) => t<'a>
```
-Removes elements from the given array starting at position `~pos` to the end of the array, returning the removed elements. *This function modifies the original array.* See [`Array.splice`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice) on MDN.
+
+Removes elements from the given array starting at position `~pos` to the end of the array, returning the removed elements. _This function modifies the original array._ See [`Array.splice`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice) on MDN.
```res example
let arr = ["a", "b", "c", "d", "e", "f"]
@@ -329,7 +342,8 @@ arr == ["a", "b", "c", "d"]
```res sig
let removeCountInPlace: (t<'a>, ~pos: int, ~count: int) => t<'a>
```
-Removes `~count` elements from the given array starting at position `~pos`, returning the removed elements. *This function modifies the original array.* See [`Array.splice`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice) on MDN.
+
+Removes `~count` elements from the given array starting at position `~pos`, returning the removed elements. _This function modifies the original array._ See [`Array.splice`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice) on MDN.
```res example
let arr = ["a", "b", "c", "d", "e", "f"]
@@ -342,7 +356,8 @@ arr == ["a", "b", "f"]
```res sig
let unshift: (t<'a>, 'a) => int
```
-Adds the given element to the array, returning the new number of elements in the array. *This function modifies the original array.* See [`Array.unshift`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/unshift) on MDN.
+
+Adds the given element to the array, returning the new number of elements in the array. _This function modifies the original array._ See [`Array.unshift`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/unshift) on MDN.
```res example
let arr = ["b", "c", "d"]
@@ -355,7 +370,8 @@ arr == ["a", "b", "c", "d"]
```res sig
let unshiftMany: (t<'a>, array<'a>) => int
```
-Adds the elements in the second array argument at the beginning of the first array argument, returning the new number of elements in the array. *This function modifies the original array.* See [`Array.unshift`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/unshift) on MDN.
+
+Adds the elements in the second array argument at the beginning of the first array argument, returning the new number of elements in the array. _This function modifies the original array._ See [`Array.unshift`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/unshift) on MDN.
```res example
let arr = ["d", "e"]
@@ -368,6 +384,7 @@ arr == ["a", "b", "c", "d", "e"]
```res sig
let append: (t<'a>, 'a) => t<'a>
```
+
Deprecated. `append()` is not type-safe. Use `concat()` instead.
## concat
@@ -375,6 +392,7 @@ Deprecated. `append()` is not type-safe. Use `concat()` instead.
```res sig
let concat: (t<'a>, t<'a>) => t<'a>
```
+
Concatenates the second array argument to the first array argument, returning a new array. The original arrays are not modified. See [`Array.concat`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat) on MDN.
```res example
@@ -386,6 +404,7 @@ Js.Array2.concat(["a", "b"], ["c", "d", "e"]) == ["a", "b", "c", "d", "e"]
```res sig
let concatMany: (t<'a>, array>) => t<'a>
```
+
The second argument to `concatMany()` is an array of arrays; these are added at the end of the first argument, returning a new array. See [`Array.concat`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat) on MDN.
```res example
@@ -406,6 +425,7 @@ Js.Array2.concatMany(["a", "b", "c"], [["d", "e"], ["f", "g", "h"]]) == [
```res sig
let includes: (t<'a>, 'a) => bool
```
+
Returns true if the given value is in the array, `false` otherwise. See [`Array.includes`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes) on MDN.
```res example
@@ -418,6 +438,7 @@ Js.Array2.includes(["a", "b", "c"], "x") == false
```res sig
let indexOf: (t<'a>, 'a) => int
```
+
Returns the index of the first element in the array that has the given value. If the value is not in the array, returns -1. See [`Array.indexOf`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf) on MDN.
```res example
@@ -430,6 +451,7 @@ Js.Array2.indexOf([100, 101, 102, 103], 999) == -1
```res sig
let indexOfFrom: (t<'a>, 'a, ~from: int) => int
```
+
Returns the index of the first element in the array with the given value. The search starts at position `~from`. See [`Array.indexOf`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf) on MDN.
```res example
@@ -443,6 +465,7 @@ Js.Array2.indexOfFrom(["a", "b", "a", "c", "a"], "b", ~from=2) == -1
```res sig
let joinWith: (t<'a>, string) => string
```
+
This function converts each element of the array to a string (via JavaScript) and concatenates them, separated by the string given in the first argument, into a single string. See [`Array.join`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join) on MDN.
```res example
@@ -457,6 +480,7 @@ Js.Array2.joinWith([2.5, 3.6, 3e-2], ";") == "2.5;3.6;0.03"
```res sig
let lastIndexOf: (t<'a>, 'a) => int
```
+
Returns the index of the last element in the array that has the given value. If the value is not in the array, returns -1. See [`Array.lastIndexOf`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/lastIndexOf) on MDN.
```res example
@@ -469,6 +493,7 @@ Js.Array2.lastIndexOf(["a", "b", "a", "c"], "x") == -1
```res sig
let lastIndexOfFrom: (t<'a>, 'a, ~from: int) => int
```
+
Returns the index of the last element in the array that has the given value, searching from position `~from` down to the start of the array. If the value is not in the array, returns -1. See [`Array.lastIndexOf`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/lastIndexOf) on MDN.
```res example
@@ -481,6 +506,7 @@ Js.Array2.lastIndexOfFrom(["a", "b", "a", "c", "a", "d"], "c", ~from=2) == -1
```res sig
let slice: (t<'a>, ~start: int, ~end_: int) => t<'a>
```
+
Returns a shallow copy of the given array from the `~start` index up to but not including the `~end_` position. Negative numbers indicate an offset from the end of the array. See [`Array.slice`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice) on MDN.
```res example
@@ -495,12 +521,15 @@ Js.Array2.slice(arr, ~start=9, ~end_=10) == []
```res sig
let copy: t<'a> => t<'a>
```
+
Returns a copy of the entire array. Same as `Js.Array2.Slice(arr, ~start=0, ~end_=Js.Array2.length(arr))`. See [`Array.slice`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice) on MDN.
+
## sliceFrom
```res sig
let sliceFrom: (t<'a>, int) => t<'a>
```
+
Returns a shallow copy of the given array from the given index to the end. See [`Array.slice`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice) on MDN.
```res example
@@ -512,6 +541,7 @@ Js.Array2.sliceFrom([100, 101, 102, 103, 104], 2) == [102, 103, 104]
```res sig
let toString: t<'a> => string
```
+
Converts the array to a string. Each element is converted to a string using JavaScript. Unlike the JavaScript `Array.toString()`, all elements in a ReasonML array must have the same type. See [`Array.toString`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/toString) on MDN.
```res example
@@ -524,6 +554,7 @@ Js.Array2.toString(["a", "b", "c"]) == "a,b,c"
```res sig
let toLocaleString: t<'a> => string
```
+
Converts the array to a string using the conventions of the current locale. Each element is converted to a string using JavaScript. Unlike the JavaScript `Array.toLocaleString()`, all elements in a ReasonML array must have the same type. See [`Array.toLocaleString`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/toLocaleString) on MDN.
```res example
@@ -537,6 +568,7 @@ Js.Array2.toLocaleString([Js.Date.make()])
```res sig
let every: (t<'a>, 'a => bool) => bool
```
+
The first argument to `every()` is an array. The second argument is a predicate function that returns a boolean. The `every()` function returns `true` if the predicate function is true for all items in the given array. If given an empty array, returns `true`. See [`Array.every`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every) on MDN.
```res example
@@ -566,6 +598,7 @@ Js.Array2.everyi([6, 3, -5, 8], evenIndexPositive) == false
```res sig
let filter: (t<'a>, 'a => bool) => t<'a>
```
+
Applies the given predicate function (the second argument) to each element in the array; the result is an array of those elements for which the predicate function returned `true`. See [`Array.filter`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) on MDN.
```res example
@@ -578,7 +611,8 @@ Js.Array2.filter(["abc", "", "", "def", "ghi"], nonEmpty) == ["abc", "def", "ghi
```res sig
let filteri: (t<'a>, ('a, int) => bool) => t<'a>
```
-Each element of the given array are passed to the predicate function. The return value is an array of all those elements for which the predicate function returned `true`. See [`Array.filter`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) on MDN.
+
+Each element of the given array are passed to the predicate function. The return value is an array of all those elements for which the predicate function returned `true`. See [`Array.filter`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) on MDN.
```res example
// keep only positive elements at odd indices
@@ -592,6 +626,7 @@ Js.Array2.filteri([6, 3, 5, 8, 7, -4, 1], positiveOddElement) == [3, 8]
```res sig
let find: (t<'a>, 'a => bool) => option<'a>
```
+
Returns `Some(value)` for the first element in the array that satisifies the given predicate function, or `None` if no element satisifies the predicate. See [`Array.find`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find) on MDN.
```res example
@@ -605,6 +640,7 @@ Js.Array2.find([33, 22, 55, 77, 44], x => x < 0) == None
```res sig
let findi: (t<'a>, ('a, int) => bool) => option<'a>
```
+
Returns `Some(value)` for the first element in the array that satisifies the given predicate function, or `None` if no element satisifies the predicate. The predicate function takes an array element and an index as its parameters. See [`Array.find`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find) on MDN.
```res example
@@ -620,6 +656,7 @@ Js.Array2.findi([66, -33, 55, -88, 22], positiveOddElement) == None
```res sig
let findIndex: (t<'a>, 'a => bool) => int
```
+
Returns the index of the first element in the array that satisifies the given predicate function, or -1 if no element satisifies the predicate. See [`Array.find`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find) on MDN.
```res example
@@ -632,6 +669,7 @@ Js.Array2.findIndex([33, 22, 55, 77, 44], x => x < 0) == -1
```res sig
let findIndexi: (t<'a>, ('a, int) => bool) => int
```
+
Returns `Some(value)` for the first element in the array that satisifies the given predicate function, or `None` if no element satisifies the predicate. The predicate function takes an array element and an index as its parameters. See [`Array.find`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find) on MDN.
```res example
@@ -647,6 +685,7 @@ Js.Array2.findIndexi([66, -33, 55, -88, 22], positiveOddElement) == -1
```res sig
let forEach: (t<'a>, 'a => unit) => unit
```
+
The `forEach()` function applies the function given as the second argument to each element in the array. The function you provide returns `unit`, and the `forEach()` function also returns `unit`. You use `forEach()` when you need to process each element in the array but not return any new array or value; for example, to print the items in an array. See [`Array.forEach`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach) on MDN.
```res example
@@ -659,6 +698,7 @@ Js.Array2.forEach(["a", "b", "c"], x => Js.log(x)) == ()
```res sig
let forEachi: (t<'a>, ('a, int) => unit) => unit
```
+
The `forEachi()` function applies the function given as the second argument to each element in the array. The function you provide takes an item in the array and its index number, and returns `unit`. The `forEachi()` function also returns `unit`. You use `forEachi()` when you need to process each element in the array but not return any new array or value; for example, to print the items in an array. See [`Array.forEach`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach) on MDN.
```res example
@@ -671,6 +711,7 @@ Js.Array2.forEachi(["a", "b", "c"], (item, index) => Js.log2(index + 1, item)) =
```res sig
let map: (t<'a>, 'a => 'b) => t<'b>
```
+
Applies the function (the second argument) to each item in the array, returning a new array. The result array does not have to have elements of the same type as the input array. See [`Array.map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) on MDN.
```res example
@@ -683,6 +724,7 @@ Js.Array2.map(["animal", "vegetable", "mineral"], Js.String.length) == [6, 9, 7]
```res sig
let mapi: (t<'a>, ('a, int) => 'b) => t<'b>
```
+
Applies the function (the second argument) to each item in the array, returning a new array. The function acceps two arguments: an item from the array and its index number. The result array does not have to have elements of the same type as the input array. See [`Array.map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) on MDN.
```res example
@@ -696,7 +738,8 @@ Js.Array2.mapi([10, 11, 12], product) == [0, 11, 24]
```res sig
let reduce: (t<'a>, ('b, 'a) => 'b, 'b) => 'b
```
-The `reduce()` function takes three parameters: an array, a *reducer function*, and a beginning accumulator value. The reducer function has two parameters: an accumulated value and an element of the array.
+
+The `reduce()` function takes three parameters: an array, a _reducer function_, and a beginning accumulator value. The reducer function has two parameters: an accumulated value and an element of the array.
`reduce()` first calls the reducer function with the beginning value and the first element in the array. The result becomes the new accumulator value, which is passed in to the reducer function along with the second element in the array. `reduce()` proceeds through the array, passing in the result of each stage as the accumulator to the reducer function.
@@ -720,7 +763,8 @@ Js.Array2.reduce([2.0, 4.0], (acc, item) => item /. acc, 1.0) == 2.0 // 4.0 / (2
```res sig
let reducei: (t<'a>, ('b, 'a, int) => 'b, 'b) => 'b
```
-The `reducei()` function takes three parameters: an array, a *reducer function*, and a beginning accumulator value. The reducer function has three parameters: an accumulated value, an element of the array, and the index of that element.
+
+The `reducei()` function takes three parameters: an array, a _reducer function_, and a beginning accumulator value. The reducer function has three parameters: an accumulated value, an element of the array, and the index of that element.
`reducei()` first calls the reducer function with the beginning value, the first element in the array, and zero (its index). The result becomes the new accumulator value, which is passed to the reducer function along with the second element in the array and one (its index). `reducei()` proceeds from left to right through the array, passing in the result of each stage as the accumulator to the reducer function.
@@ -743,11 +787,12 @@ Js.Array2.reducei([2, 5, 1, 4, 3], sumOfEvens, 0) == 6
```res sig
let reduceRight: (t<'a>, ('b, 'a) => 'b, 'b) => 'b
```
-The `reduceRight()` function takes three parameters: an array, a *reducer function*, and a beginning accumulator value. The reducer function has two parameters: an accumulated value and an element of the array.
+
+The `reduceRight()` function takes three parameters: an array, a _reducer function_, and a beginning accumulator value. The reducer function has two parameters: an accumulated value and an element of the array.
`reduceRight()` first calls the reducer function with the beginning value and the last element in the array. The result becomes the new accumulator value, which is passed in to the reducer function along with the next-to-last element in the array. `reduceRight()` proceeds from right to left through the array, passing in the result of each stage as the accumulator to the reducer function.
-When all array elements are processed, the final value of the accumulator becomes the return value of `reduceRight()`. See [`Array.reduceRight`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduceRight) on MDN.
+When all array elements are processed, the final value of the accumulator becomes the return value of `reduceRight()`. See [`Array.reduceRight`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduceRight) on MDN.
**NOTE:** In many cases, `reduce()` and `reduceRight()` give the same result. However, see the last example here and compare it to the example from `reduce()`, where order makes a difference.
@@ -763,7 +808,8 @@ Js.Array2.reduceRight([2.0, 4.0], (acc, item) => item /. acc, 1.0) == 0.5 // 2.0
```res sig
let reduceRighti: (t<'a>, ('b, 'a, int) => 'b, 'b) => 'b
```
-The `reduceRighti()` function takes three parameters: an array, a *reducer function*, and a beginning accumulator value. The reducer function has three parameters: an accumulated value, an element of the array, and the index of that element. `reduceRighti()` first calls the reducer function with the beginning value, the last element in the array, and its index (length of array minus one). The result becomes the new accumulator value, which is passed in to the reducer function along with the second element in the array and one (its index). `reduceRighti()` proceeds from right to left through the array, passing in the result of each stage as the accumulator to the reducer function.
+
+The `reduceRighti()` function takes three parameters: an array, a _reducer function_, and a beginning accumulator value. The reducer function has three parameters: an accumulated value, an element of the array, and the index of that element. `reduceRighti()` first calls the reducer function with the beginning value, the last element in the array, and its index (length of array minus one). The result becomes the new accumulator value, which is passed in to the reducer function along with the second element in the array and one (its index). `reduceRighti()` proceeds from right to left through the array, passing in the result of each stage as the accumulator to the reducer function.
When all array elements are processed, the final value of the accumulator becomes the return value of `reduceRighti()`. See [`Array.reduceRight`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduceRight) on MDN.
@@ -786,6 +832,7 @@ Js.Array2.reduceRighti([2, 5, 1, 4, 3], sumOfEvens, 0) == 6
```res sig
let some: (t<'a>, 'a => bool) => bool
```
+
Returns `true` if the predicate function given as the second argument to `some()` returns `true` for any element in the array; `false` otherwise.
```res example
@@ -800,6 +847,7 @@ Js.Array2.some([3, 7, 5, 1, 9], isEven) == false
```res sig
let somei: (t<'a>, ('a, int) => bool) => bool
```
+
Returns `true` if the predicate function given as the second argument to `somei()` returns `true` for any element in the array; `false` otherwise. The predicate function has two arguments: an item from the array and the index value
```res example
@@ -819,6 +867,7 @@ Js.Array2.somei(["a", "bc", "def", "gh"], sameLength) == false
```res sig
let unsafe_get: (array<'a>, int) => 'a
```
+
Returns the value at the given position in the array if the position is in bounds; returns the JavaScript value `undefined` otherwise.
```res example
@@ -832,7 +881,8 @@ Js.Array2.unsafe_get(arr, 4) // returns undefined
```res sig
let unsafe_set: (array<'a>, int, 'a) => unit
```
-Sets the value at the given position in the array if the position is in bounds. If the index is out of bounds, well, “here there be dragons.“ *This function modifies the original array.*
+
+Sets the value at the given position in the array if the position is in bounds. If the index is out of bounds, well, “here there be dragons.“ _This function modifies the original array._
```res example
let arr = [100, 101, 102, 103]
diff --git a/pages/docs/manual/v9.0.0/api/js/array.mdx b/pages/docs/manual/v9.0.0/api/js/array.mdx
index 1ed2abb75..4c55ae32d 100644
--- a/pages/docs/manual/v9.0.0/api/js/array.mdx
+++ b/pages/docs/manual/v9.0.0/api/js/array.mdx
@@ -64,7 +64,7 @@ Js.Array.from(strArr) == ["a", "b", "c", "d"]
let fromMap: (array_like<'a>, 'a => 'b) => array<'b>
```
-Creates a new array by applying a function (the second argument) to each item in the `array_like` first argument. See [`Array.from`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from) on MDN.
+Creates a new array by applying a function (the second argument) to each item in the `array_like` first argument. See [`Array.from`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from) on MDN.
```res example
let strArr = Js.String.castToArrayLike("abcd")
@@ -100,7 +100,7 @@ Returns the number of elements in the array. See [`Array.length`](https://develo
let copyWithin: (~to_: int, t<'a>) => t<'a>
```
-Copies from the first element in the given array to the designated `~to_` position, returning the resulting array. *This function modifies the original array.* See [`Array.copyWithin`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/copyWithin) on MDN.
+Copies from the first element in the given array to the designated `~to_` position, returning the resulting array. _This function modifies the original array._ See [`Array.copyWithin`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/copyWithin) on MDN.
```res example
let arr = [100, 101, 102, 103, 104]
@@ -114,7 +114,7 @@ arr == [100, 101, 100, 101, 102]
let copyWithinFrom: (~to_: int, ~from: int, t<'a>) => t<'a>
```
-Copies starting at element `~from` in the given array to the designated `~to_` position, returning the resulting array. *This function modifies the original array.* See [`Array.copyWithin`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/copyWithin) on MDN.
+Copies starting at element `~from` in the given array to the designated `~to_` position, returning the resulting array. _This function modifies the original array._ See [`Array.copyWithin`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/copyWithin) on MDN.
```res example
let arr = [100, 101, 102, 103, 104]
@@ -128,7 +128,7 @@ arr == [102, 103, 104, 103, 104]
let copyWithinFromRange: (~to_: int, ~start: int, ~end_: int, t<'a>) => t<'a>
```
-Copies starting at element `~start` in the given array up to but not including `~end_` to the designated `~to_` position, returning the resulting array. *This function modifies the original array.* See [`Array.copyWithin`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/copyWithin) on MDN.
+Copies starting at element `~start` in the given array up to but not including `~end_` to the designated `~to_` position, returning the resulting array. _This function modifies the original array._ See [`Array.copyWithin`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/copyWithin) on MDN.
```res example
let arr = [100, 101, 102, 103, 104, 105]
@@ -141,7 +141,8 @@ arr == [100, 102, 103, 104, 104, 105]
```res sig
let fillInPlace: ('a, t<'a>) => t<'a>
```
-Sets all elements of the given array (the second arumgent) to the designated value (the first argument), returning the resulting array. *This function modifies the original array.* See [`Array.fill`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/fill) on MDN.
+
+Sets all elements of the given array (the second arumgent) to the designated value (the first argument), returning the resulting array. _This function modifies the original array._ See [`Array.fill`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/fill) on MDN.
```res example
let arr = [100, 101, 102, 103, 104]
@@ -154,7 +155,8 @@ arr == [99, 99, 99, 99, 99]
```res sig
let fillFromInPlace: ('a, ~from: int, t<'a>) => t<'a>
```
-Sets all elements of the given array (the last arumgent) from position `~from` to the end to the designated value (the first argument), returning the resulting array. *This function modifies the original array.* See [`Array.fill`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/fill) on MDN.
+
+Sets all elements of the given array (the last arumgent) from position `~from` to the end to the designated value (the first argument), returning the resulting array. _This function modifies the original array._ See [`Array.fill`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/fill) on MDN.
```res example
let arr = [100, 101, 102, 103, 104]
@@ -168,7 +170,7 @@ arr == [100, 101, 99, 99, 99]
let fillRangeInPlace: ('a, ~start: int, ~end_: int, t<'a>) => t<'a>
```
-Sets the elements of the given array (the last arumgent) from position `~start` up to but not including position `~end_` to the designated value (the first argument), returning the resulting array. *This function modifies the original array.* See [`Array.fill`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/fill) on MDN.
+Sets the elements of the given array (the last arumgent) from position `~start` up to but not including position `~end_` to the designated value (the first argument), returning the resulting array. _This function modifies the original array._ See [`Array.fill`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/fill) on MDN.
```res example
let arr = [100, 101, 102, 103, 104]
@@ -182,7 +184,7 @@ arr == [100, 99, 99, 99, 104]
let pop: t<'a> => option<'a>
```
-If the array is not empty, removes the last element and returns it as `Some(value)`; returns `None` if the array is empty. *This function modifies the original array.* See [`Array.pop`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/pop) on MDN.
+If the array is not empty, removes the last element and returns it as `Some(value)`; returns `None` if the array is empty. _This function modifies the original array._ See [`Array.pop`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/pop) on MDN.
```res example
let arr = [100, 101, 102, 103, 104]
@@ -199,7 +201,7 @@ Js.Array.pop(empty) == None
let push: ('a, t<'a>) => int
```
-Appends the given value to the array, returning the number of elements in the updated array. *This function modifies the original array.* See [`Array.push`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push) on MDN.
+Appends the given value to the array, returning the number of elements in the updated array. _This function modifies the original array._ See [`Array.push`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push) on MDN.
```res example
let arr = ["ant", "bee", "cat"]
@@ -213,7 +215,7 @@ arr == ["ant", "bee", "cat", "dog"]
let pushMany: (array<'a>, t<'a>) => int
```
-Appends the values from one array (the first argument) to another (the second argument), returning the number of elements in the updated array. *This function modifies the original array.* See [`Array.push`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push) on MDN.
+Appends the values from one array (the first argument) to another (the second argument), returning the number of elements in the updated array. _This function modifies the original array._ See [`Array.push`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push) on MDN.
```res example
let arr = ["ant", "bee", "cat"]
@@ -227,7 +229,7 @@ arr == ["ant", "bee", "cat", "dog", "elk"]
let reverseInPlace: t<'a> => t<'a>
```
-Returns an array with the elements of the input array in reverse order. *This function modifies the original array.* See [`Array.reverse`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse) on MDN.
+Returns an array with the elements of the input array in reverse order. _This function modifies the original array._ See [`Array.reverse`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse) on MDN.
```res example
let arr = ["ant", "bee", "cat"]
@@ -240,7 +242,8 @@ arr == ["cat", "bee", "ant"]
```res sig
let shift: t<'a> => option<'a>
```
-If the array is not empty, removes the first element and returns it as `Some(value)`; returns `None` if the array is empty. *This function modifies the original array.* See [`Array.shift`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/shift) on MDN.
+
+If the array is not empty, removes the first element and returns it as `Some(value)`; returns `None` if the array is empty. _This function modifies the original array._ See [`Array.shift`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/shift) on MDN.
```res example
let arr = [100, 101, 102, 103, 104]
@@ -250,13 +253,14 @@ arr == [101, 102, 103, 104]
let empty: array = []
Js.Array.shift(empty) == None
```
+
## sortInPlace
```res sig
let sortInPlace: t<'a> => t<'a>
```
-Sorts the given array in place and returns the sorted array. JavaScript sorts the array by converting the arguments to UTF-16 strings and sorting them. See the second example with sorting numbers, which does not do a numeric sort. *This function modifies the original array.* See [`Array.sort`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort) on MDN.
+Sorts the given array in place and returns the sorted array. JavaScript sorts the array by converting the arguments to UTF-16 strings and sorting them. See the second example with sorting numbers, which does not do a numeric sort. _This function modifies the original array._ See [`Array.sort`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort) on MDN.
```res example
let words = ["bee", "dog", "ant", "cat"]
@@ -274,13 +278,13 @@ numbers == [1, 10, 2, 20, 3, 30]
let sortInPlaceWith: (('a, 'a) => int, t<'a>) => t<'a>
```
-Sorts the given array in place and returns the sorted array. *This function modifies the original array.*
+Sorts the given array in place and returns the sorted array. _This function modifies the original array._
The first argument to `sortInPlaceWith()` is a function that compares two items from the array and returns:
-* an integer less than zero if the first item is less than the second item
-* zero if the items are equal
-* an integer greater than zero if the first item is greater than the second item
+- an integer less than zero if the first item is less than the second item
+- zero if the items are equal
+- an integer greater than zero if the first item is greater than the second item
See [`Array.sort`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort) on MDN.
@@ -303,7 +307,7 @@ Js.Array.sortInPlaceWith(reverseNumeric, numbers) == [30, 20, 10, 3, 2, 1]
let spliceInPlace: (~pos: int, ~remove: int, ~add: array<'a>, t<'a>) => t<'a>
```
-Starting at position `~pos`, remove `~remove` elements and then add the elements from the `~add` array. Returns an array consisting of the removed items. *This function modifies the original array.* See [`Array.splice`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice) on MDN.
+Starting at position `~pos`, remove `~remove` elements and then add the elements from the `~add` array. Returns an array consisting of the removed items. _This function modifies the original array._ See [`Array.splice`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice) on MDN.
```res example
let arr = ["a", "b", "c", "d", "e", "f"]
@@ -325,7 +329,7 @@ arr3 == ["a", "b", "c", "d", "e", "f", "x", "y", "z"]
let removeFromInPlace: (~pos: int, t<'a>) => t<'a>
```
-Removes elements from the given array starting at position `~pos` to the end of the array, returning the removed elements. *This function modifies the original array.* See [`Array.splice`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice) on MDN.
+Removes elements from the given array starting at position `~pos` to the end of the array, returning the removed elements. _This function modifies the original array._ See [`Array.splice`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice) on MDN.
```res example
let arr = ["a", "b", "c", "d", "e", "f"]
@@ -339,7 +343,7 @@ arr == ["a", "b", "c", "d"]
let removeCountInPlace: (~pos: int, ~count: int, t<'a>) => t<'a>
```
-Removes `~count` elements from the given array starting at position `~pos`, returning the removed elements. *This function modifies the original array.* See [`Array.splice`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice) on MDN.
+Removes `~count` elements from the given array starting at position `~pos`, returning the removed elements. _This function modifies the original array._ See [`Array.splice`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice) on MDN.
```res example
let arr = ["a", "b", "c", "d", "e", "f"]
@@ -353,7 +357,7 @@ arr == ["a", "b", "f"]
let unshift: ('a, t<'a>) => int
```
-Adds the given element to the array, returning the new number of elements in the array. *This function modifies the original array.* See [`Array.unshift`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/unshift) on MDN.
+Adds the given element to the array, returning the new number of elements in the array. _This function modifies the original array._ See [`Array.unshift`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/unshift) on MDN.
```res example
let arr = ["b", "c", "d"]
@@ -367,7 +371,7 @@ arr == ["a", "b", "c", "d"]
let unshiftMany: (array<'a>, t<'a>) => int
```
-Adds the elements in the first array argument at the beginning of the second array argument, returning the new number of elements in the array. *This function modifies the original array.* See [`Array.unshift`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/unshift) on MDN.
+Adds the elements in the first array argument at the beginning of the second array argument, returning the new number of elements in the array. _This function modifies the original array._ See [`Array.unshift`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/unshift) on MDN.
```res example
let arr = ["d", "e"]
@@ -434,6 +438,7 @@ Js.Array.includes("x", ["a", "b", "c"]) == false
```res sig
let indexOf: ('a, t<'a>) => int
```
+
Returns the index of the first element in the array that has the given value. If the value is not in the array, returns -1. See [`Array.indexOf`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf) on MDN.
```res example
@@ -461,6 +466,7 @@ Js.Array.indexOfFrom("b", ~from=2, ["a", "b", "a", "c", "a"]) == -1
```res sig
let join: t<'a> => string
```
+
Deprecated. Use `joinWith` instead.
## joinWith
@@ -468,6 +474,7 @@ Deprecated. Use `joinWith` instead.
```res sig
let joinWith: (string, t<'a>) => string
```
+
This function converts each element of the array to a string (via JavaScript) and concatenates them, separated by the string given in the first argument, into a single string. See [`Array.join`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join) on MDN.
```res example
@@ -632,14 +639,13 @@ let nonEmpty = s => s != ""
Js.Array.filter(nonEmpty, ["abc", "", "", "def", "ghi"]) == ["abc", "def", "ghi"]
```
-
## filteri
```res sig
let filteri: (('a, int) => bool, t<'a>) => t<'a>
```
-Each element of the given array are passed to the predicate function. The return value is an array of all those elements for which the predicate function returned `true`. See [`Array.filter`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) on MDN.
+Each element of the given array are passed to the predicate function. The return value is an array of all those elements for which the predicate function returned `true`. See [`Array.filter`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) on MDN.
```res example
// keep only positive elements at odd indices
@@ -690,6 +696,7 @@ Returns the index of the first element in the array that satisifies the given pr
Js.Array.findIndex(x => x < 0, [33, 22, -55, 77, -44]) == 2
Js.Array.findIndex(x => x < 0, [33, 22, 55, 77, 44]) == -1
```
+
## findIndexi
```res sig
@@ -765,7 +772,7 @@ Js.Array.mapi(product, [10, 11, 12]) == [0, 11, 24]
let reduce: (('b, 'a) => 'b, 'b, t<'a>) => 'b
```
-The `reduce()` function takes three parameters: a *reducer function*, a beginning accumulator value, and an array. The reducer function has two parameters: an accumulated value and an element of the array.
+The `reduce()` function takes three parameters: a _reducer function_, a beginning accumulator value, and an array. The reducer function has two parameters: an accumulated value and an element of the array.
`reduce()` first calls the reducer function with the beginning value and the first element in the array. The result becomes the new accumulator value, which is passed in to the reducer function along with the second element in the array. `reduce()` proceeds through the array, passing in the result of each stage as the accumulator to the reducer function.
@@ -790,7 +797,7 @@ Js.Array.reduce((acc, item) => item /. acc, 1.0, [2.0, 4.0]) == 2.0 // 4.0 / (2.
let reducei: (('b, 'a, int) => 'b, 'b, t<'a>) => 'b
```
-The `reducei()` function takes three parameters: a *reducer function*, a beginning accumulator value, and an array. The reducer function has three parameters: an accumulated value, an element of the array, and the index of that element.
+The `reducei()` function takes three parameters: a _reducer function_, a beginning accumulator value, and an array. The reducer function has three parameters: an accumulated value, an element of the array, and the index of that element.
`reducei()` first calls the reducer function with the beginning value, the first element in the array, and zero (its index). The result becomes the new accumulator value, which is passed to the reducer function along with the second element in the array and one (its index). `reducei()` proceeds from left to right through the array, passing in the result of each stage as the accumulator to the reducer function.
@@ -814,11 +821,11 @@ Js.Array.reducei(sumOfEvens, 0, [2, 5, 1, 4, 3]) == 6
let reduceRight: (('b, 'a) => 'b, 'b, t<'a>) => 'b
```
-The `reduceRight()` function takes three parameters: a *reducer function*, a beginning accumulator value, and an array. The reducer function has two parameters: an accumulated value and an element of the array.
+The `reduceRight()` function takes three parameters: a _reducer function_, a beginning accumulator value, and an array. The reducer function has two parameters: an accumulated value and an element of the array.
`reduceRight()` first calls the reducer function with the beginning value and the last element in the array. The result becomes the new accumulator value, which is passed in to the reducer function along with the next-to-last element in the array. `reduceRight()` proceeds from right to left through the array, passing in the result of each stage as the accumulator to the reducer function.
-When all array elements are processed, the final value of the accumulator becomes the return value of `reduceRight()`. See [`Array.reduceRight`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduceRight) on MDN.
+When all array elements are processed, the final value of the accumulator becomes the return value of `reduceRight()`. See [`Array.reduceRight`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduceRight) on MDN.
**NOTE:** In many cases, `reduce()` and `reduceRight()` give the same result. However, see the last example here and compare it to the example from `reduce()`, where order makes a difference.
@@ -835,7 +842,7 @@ Js.Array.reduceRight((acc, item) => item /. acc, 1.0, [2.0, 4.0]) == 0.5 // 2.0
let reduceRighti: (('b, 'a, int) => 'b, 'b, t<'a>) => 'b
```
-The `reduceRighti()` function takes three parameters: a *reducer function*, a beginning accumulator value, and an array. The reducer function has three parameters: an accumulated value, an element of the array, and the index of that element. `reduceRighti()` first calls the reducer function with the beginning value, the last element in the array, and its index (length of array minus one). The result becomes the new accumulator value, which is passed in to the reducer function along with the second element in the array and one (its index). `reduceRighti()` proceeds from right to left through the array, passing in the result of each stage as the accumulator to the reducer function.
+The `reduceRighti()` function takes three parameters: a _reducer function_, a beginning accumulator value, and an array. The reducer function has three parameters: an accumulated value, an element of the array, and the index of that element. `reduceRighti()` first calls the reducer function with the beginning value, the last element in the array, and its index (length of array minus one). The result becomes the new accumulator value, which is passed in to the reducer function along with the second element in the array and one (its index). `reduceRighti()` proceeds from right to left through the array, passing in the result of each stage as the accumulator to the reducer function.
When all array elements are processed, the final value of the accumulator becomes the return value of `reduceRighti()`. See [`Array.reduceRight`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduceRight) on MDN.
@@ -893,6 +900,7 @@ Js.Array.somei(sameLength, ["a", "bc", "def", "gh"]) == false
```res sig
let unsafe_get: (array<'a>, int) => 'a
```
+
Returns the value at the given position in the array if the position is in bounds; returns
the JavaScript value `undefined` otherwise.
@@ -908,7 +916,7 @@ Js.Array.unsafe_get(arr, 4) // returns undefined
let unsafe_set: (array<'a>, int, 'a) => unit
```
-Sets the value at the given position in the array if the position is in bounds. If the index is out of bounds, well, “here there be dragons.“ *This function modifies the original array.*
+Sets the value at the given position in the array if the position is in bounds. If the index is out of bounds, well, “here there be dragons.“ _This function modifies the original array._
```res example
let arr = [100, 101, 102, 103]
diff --git a/pages/docs/manual/v9.0.0/api/js/console.mdx b/pages/docs/manual/v9.0.0/api/js/console.mdx
index f02bd576b..c7d83a8ed 100644
--- a/pages/docs/manual/v9.0.0/api/js/console.mdx
+++ b/pages/docs/manual/v9.0.0/api/js/console.mdx
@@ -6,7 +6,6 @@ Provide console (logging) utilities.
-
## log
```res sig
diff --git a/pages/docs/manual/v9.0.0/api/js/date.mdx b/pages/docs/manual/v9.0.0/api/js/date.mdx
index 9212782d7..a381d68e5 100644
--- a/pages/docs/manual/v9.0.0/api/js/date.mdx
+++ b/pages/docs/manual/v9.0.0/api/js/date.mdx
@@ -3,7 +3,8 @@
Provide bindings to JS date. (See [`Date`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) on MDN.) JavaScript stores dates as the number of milliseconds since
-the UNIX *epoch*, midnight 1 January 1970, UTC.
+the UNIX _epoch_, midnight 1 January 1970, UTC.
+
In these examples, we will be using this date:
@@ -17,7 +18,6 @@ The code used to access this date is running in the Europe/Austria time zone wit
In all of these functions, month values are in the range 0-11, where January is month zero.
-
## t
```res prelude
@@ -29,6 +29,7 @@ type t
```res sig
let valueOf: t => float
```
+
Returns the primitive value of this date, equivalent to `getTime()`. (See [`Date.valueOf`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/valueOf) on MDN.)
```res example
@@ -40,6 +41,7 @@ Js.Date.valueOf(exampleDate) == 123456654321.0
```res sig
let make: unit => t
```
+
Returns a date representing the current time. See [`Date()` Constructor](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/Date) on MDN.
```res example
@@ -77,6 +79,7 @@ Js.Date.fromString("Thor, 32 Lok -19 60:70:80 XYZ") // returns NaN
```res sig
let makeWithYM: (~year: float, ~month: float, unit) => t
```
+
Returns a date representing midnight of the first day of the given month and year in the current time zone. Fractional parts of arguments are ignored. See [`Date()` Constructor](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/Date) on MDN.
```res example
@@ -88,6 +91,7 @@ let november1 = Js.Date.makeWithYM(~year=2020.0, ~month=10.0, ())
```res sig
let makeWithYMD: (~year: float, ~month: float, ~date: float, unit) => t
```
+
Returns a date representing midnight of the given date of the given month and year in the current time zone. Fractional parts of arguments are ignored. See [`Date()` Constructor](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/Date) on MDN.
## makeWithYMDH
@@ -95,6 +99,7 @@ Returns a date representing midnight of the given date of the given month and ye
```res sig
let makeWithYMDH: (~year: float, ~month: float, ~date: float, ~hours: float, unit) => t
```
+
Returns a date representing the given date of the given month and year, at zero minutes and zero seconds past the given `hours`, in the current time zone. Fractional parts of arguments are ignored. See [`Date()` Constructor](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/Date) on MDN. Fractional parts of the arguments are ignored.
## makeWithYMDHM
@@ -109,7 +114,8 @@ let makeWithYMDHM: (
unit,
) => t
```
-Returns a date representing the given date of the given month and year, at zero seconds past the given time in hours and minutes in the current time zone. Fractional parts of arguments are ignored. See [`Date()` Constructor](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/Date) on MDN.
+
+Returns a date representing the given date of the given month and year, at zero seconds past the given time in hours and minutes in the current time zone. Fractional parts of arguments are ignored. See [`Date()` Constructor](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/Date) on MDN.
## makeWithYMDHMS
@@ -124,6 +130,7 @@ let makeWithYMDHMS: (
unit,
) => t
```
+
Returns a date representing the given date of the given month and year, at the given time in hours, minutes, and seconds in the current time zone. Fractional parts of arguments are ignored. See [`Date()` Constructor](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/Date) on MDN.
```res example
@@ -143,6 +150,7 @@ Js.Date.makeWithYMDHMS(
```res sig
let utcWithYM: (~year: float, ~month: float, unit) => float
```
+
Returns a float representing the number of milliseconds past the epoch for midnight of the first day of the given month and year in UTC. Fractional parts of arguments are ignored. See [`Date.UTC`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/UTC) on MDN.
```res example
@@ -154,6 +162,7 @@ let november1 = Js.Date.utcWithYM(~year=2020.0, ~month=10.0, ())
```res sig
let utcWithYMD: (~year: float, ~month: float, ~date: float, unit) => float
```
+
Returns a float representing the number of milliseconds past the epoch for midnight of the given date of the given month and year in UTC. Fractional parts of arguments are ignored. See [`Date.UTC`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/UTC) on MDN.
## utcWithYMDH
@@ -161,6 +170,7 @@ Returns a float representing the number of milliseconds past the epoch for midni
```res sig
let utcWithYMDH: (~year: float, ~month: float, ~date: float, ~hours: float, unit) => float
```
+
Returns a float representing the number of milliseconds past the epoch for midnight of the given date of the given month and year, at zero minutes and seconds past the given hours in UTC. Fractional parts of arguments are ignored. See [`Date.UTC`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/UTC) on MDN.
## utcWithYMDHM
@@ -175,6 +185,7 @@ let utcWithYMDHM: (
unit,
) => float
```
+
Returns a float representing the number of milliseconds past the epoch for midnight of the given date of the given month and year, at zero seconds past the given number of minutes past the given hours in UTC. Fractional parts of arguments are ignored. See [`Date.UTC`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/UTC) on MDN.
## utcWithYMDHMS
@@ -190,6 +201,7 @@ let utcWithYMDHMS: (
unit,
) => float
```
+
Returns a float representing the number of milliseconds past the epoch for midnight of the given date of the given month and year, at the given time in hours, minutes and seconds in UTC. Fractional parts of arguments are ignored. See [`Date.UTC`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/UTC) on MDN.
## now
@@ -197,6 +209,7 @@ Returns a float representing the number of milliseconds past the epoch for midni
```res sig
let now: unit => float
```
+
Returns the current time as number of milliseconds since Unix epoch.
## parse
@@ -204,6 +217,7 @@ Returns the current time as number of milliseconds since Unix epoch.
```res sig
let parse: string => t
```
+
Deprecated. Use [`fromString()`](#fromstring).
## parseAsFloat
@@ -211,6 +225,7 @@ Deprecated. Use [`fromString()`](#fromstring).
```res sig
let parseAsFloat: string => float
```
+
Returns a float with the number of milliseconds past the epoch represented by the given string. The string can be in “IETF-compliant RFC 2822 timestamps, and also strings in a version of ISO8601.” Returns `NaN` if given an invalid date string. According to the [`Date.parse`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse) documentation on MDN, its use is discouraged. Returns `NaN` if passed invalid date string.
## getDate
@@ -218,6 +233,7 @@ Returns a float with the number of milliseconds past the epoch represented by th
```res sig
let getDate: t => float
```
+
Returns the day of the month for its argument. The argument is evaluated in the current time zone. See [`Date.getDate`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getDate) on MDN.
```res example
@@ -229,7 +245,8 @@ Js.Date.getDate(exampleDate) == 29.0
```res sig
let getDay: t => float
```
-Returns the day of the week (0.0-6.0) for its argument, where 0.0 represents Sunday. The argument is evaluated in the current time zone. See [`Date.getDay`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getDay) on MDN.
+
+Returns the day of the week (0.0-6.0) for its argument, where 0.0 represents Sunday. The argument is evaluated in the current time zone. See [`Date.getDay`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getDay) on MDN.
```res example
Js.Date.getDay(exampleDate) == 4.0
@@ -240,6 +257,7 @@ Js.Date.getDay(exampleDate) == 4.0
```res sig
let getFullYear: t => float
```
+
Returns the full year (as opposed to the range 0-99) for its argument. The argument is evaluated in the current time zone. See [`Date.getFullYear`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getFullYear) on MDN.
```res example
@@ -251,6 +269,7 @@ Js.Date.getFullYear(exampleDate) == 1973.0
```res sig
let getHours: t => float
```
+
Returns the hours for its argument, evaluated in the current time zone. See [`Date.getHours`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getHours) on MDN.
```res example
@@ -262,6 +281,7 @@ Js.Date.getHours(exampleDate) == 22.0 // Vienna is in GMT+01:00
```res sig
let getMilliseconds: t => float
```
+
Returns the number of milliseconds for its argument, evaluated in the current time zone. See [`Date.getMilliseconds`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getMilliseconds) on MDN.
```res example
@@ -273,6 +293,7 @@ Js.Date.getMilliseconds(exampleDate) == 321.0
```res sig
let getMinutes: t => float
```
+
Returns the number of minutes for its argument, evaluated in the current time zone. See [`Date.getMinutes`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getMinutes) on MDN.
```res example
@@ -284,7 +305,8 @@ Js.Date.getMinutes(exampleDate) == 30.0
```res sig
let getMonth: t => float
```
-Returns the month (0.0-11.0) for its argument, evaluated in the current time zone. January is month zero. See [`Date.getMonth`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getMonth) on MDN.
+
+Returns the month (0.0-11.0) for its argument, evaluated in the current time zone. January is month zero. See [`Date.getMonth`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getMonth) on MDN.
```res example
Js.Date.getMonth(exampleDate) == 10.0
@@ -295,6 +317,7 @@ Js.Date.getMonth(exampleDate) == 10.0
```res sig
let getSeconds: t => float
```
+
Returns the seconds for its argument, evaluated in the current time zone. See [`Date.getSeconds`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getSeconds) on MDN.
```res example
@@ -306,7 +329,8 @@ Js.Date.getSeconds(exampleDate) == 54.0
```res sig
let getTime: t => float
```
-Returns the number of milliseconds since Unix epoch, evaluated in UTC. See [`Date.getTime`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getTime) on MDN.
+
+Returns the number of milliseconds since Unix epoch, evaluated in UTC. See [`Date.getTime`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getTime) on MDN.
```res example
Js.Date.getTime(exampleDate) == 123456654321.0
@@ -329,6 +353,7 @@ Js.Date.getTimezoneOffset(exampleDate) == -60.0
```res sig
let getUTCDate: t => float
```
+
Returns the day of the month of the argument, evaluated in UTC. See [`Date.getUTCDate`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getUTCDate) on MDN.
```res example
@@ -340,6 +365,7 @@ Js.Date.getUTCDate(exampleDate) == 29.0
```res sig
let getUTCDay: t => float
```
+
Returns the day of the week of the argument, evaluated in UTC. The range of the return value is 0.0-6.0, where Sunday is zero. See [`Date.getUTCDay`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getUTCDay) on MDN.
```res example
@@ -351,7 +377,8 @@ Js.Date.getUTCDay(exampleDate) == 4.0
```res sig
let getUTCFullYear: t => float
```
-Returns the full year (as opposed to the range 0-99) for its argument. The argument is evaluated in UTC. See [`Date.getUTCFullYear`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getUTCFullYear) on MDN.
+
+Returns the full year (as opposed to the range 0-99) for its argument. The argument is evaluated in UTC. See [`Date.getUTCFullYear`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getUTCFullYear) on MDN.
```res example
Js.Date.getUTCFullYear(exampleDate) == 1973.0
@@ -362,6 +389,7 @@ Js.Date.getUTCFullYear(exampleDate) == 1973.0
```res sig
let getUTCHours: t => float
```
+
Returns the hours for its argument, evaluated in the current time zone. See [`Date.getUTCHours`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getUTCHours) on MDN.
```res example
@@ -373,6 +401,7 @@ Js.Date.getUTCHours(exampleDate) == 21.0
```res sig
let getUTCMilliseconds: t => float
```
+
Returns the number of milliseconds for its argument, evaluated in UTC. See [`Date.getUTCMilliseconds`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getUTCMilliseconds) on MDN.
```res example
@@ -384,6 +413,7 @@ Js.Date.getUTCMilliseconds(exampleDate) == 321.0
```res sig
let getUTCMinutes: t => float
```
+
Returns the number of minutes for its argument, evaluated in UTC. See [`Date.getUTCMinutes`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getUTCMinutes) on MDN.
```res example
@@ -395,6 +425,7 @@ Js.Date.getUTCMinutes(exampleDate) == 30.0
```res sig
let getUTCMonth: t => float
```
+
Returns the month (0.0-11.0) for its argument, evaluated in UTC. January is month zero. See [`Date.getUTCMonth`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getUTCMonth) on MDN.
```res example
@@ -406,6 +437,7 @@ Js.Date.getUTCMonth(exampleDate) == 10.0
```res sig
let getUTCSeconds: t => float
```
+
Returns the seconds for its argument, evaluated in UTC. See [`Date.getUTCSeconds`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getUTCSeconds) on MDN.
```res example
@@ -417,6 +449,7 @@ Js.Date.getUTCSeconds(exampleDate) == 54.0
```res sig
let getYear: t => float
```
+
Deprecated. Use `getFullYear()` instead.
## setDate
@@ -424,7 +457,8 @@ Deprecated. Use `getFullYear()` instead.
```res sig
let setDate: (t, float) => float
```
-Sets the given `Date`’s day of month to the value in the second argument according to the current time zone. Returns the number of milliseconds since the epoch of the updated `Date`. *This function modifies the original `Date`.* See [`Date.setDate`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setDate) on MDN.
+
+Sets the given `Date`’s day of month to the value in the second argument according to the current time zone. Returns the number of milliseconds since the epoch of the updated `Date`. _This function modifies the original `Date`._ See [`Date.setDate`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setDate) on MDN.
```res example
let date1 = Js.Date.fromFloat(123456654321.0) // 29 November 1973 21:30:54.321 GMT
@@ -438,7 +472,8 @@ twoWeeksBefore == Js.Date.getTime(date1)
```res sig
let setFullYear: (t, float) => float
```
-Sets the given `Date`’s year to the value in the second argument according to the current time zone. Returns the number of milliseconds since the epoch of the updated `Date`. *This function modifies the original `Date`.* See [`Date.setFullYear`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setFullYear) on MDN.
+
+Sets the given `Date`’s year to the value in the second argument according to the current time zone. Returns the number of milliseconds since the epoch of the updated `Date`. _This function modifies the original `Date`._ See [`Date.setFullYear`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setFullYear) on MDN.
```res example
let date1 = Js.Date.fromFloat(123456654321.0) // 29 November 1973 21:30:54.321 GMT
@@ -453,7 +488,7 @@ nextYear == Js.Date.getTime(date1)
let setFullYearM: (t, ~year: float, ~month: float, unit) => float
```
-Sets the given `Date`’s year and month to the values in the labeled arguments according to the current time zone. Returns the number of milliseconds since the epoch of the updated `Date`. *This function modifies the original `Date`.* See [`Date.setFullYear`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setFullYear) on MDN.
+Sets the given `Date`’s year and month to the values in the labeled arguments according to the current time zone. Returns the number of milliseconds since the epoch of the updated `Date`. _This function modifies the original `Date`._ See [`Date.setFullYear`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setFullYear) on MDN.
```res example
let date1 = Js.Date.fromFloat(123456654321.0) // 29 November 1973 21:30:54.321 GMT
@@ -467,7 +502,8 @@ future == Js.Date.getTime(date1)
```res sig
let setFullYearMD: (t, ~year: float, ~month: float, ~date: float, unit) => float
```
-Sets the given `Date`’s year, month, and day of month to the values in the labeled arguments according to the current time zone. Returns the number of milliseconds since the epoch of the updated `Date`. *This function modifies the original `Date`.* See [`Date.setFullYear`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setFullYear) on MDN.
+
+Sets the given `Date`’s year, month, and day of month to the values in the labeled arguments according to the current time zone. Returns the number of milliseconds since the epoch of the updated `Date`. _This function modifies the original `Date`._ See [`Date.setFullYear`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setFullYear) on MDN.
```res example
let date1 = Js.Date.fromFloat(123456654321.0) // 29 November 1973 21:30:54.321 GMT
@@ -481,7 +517,8 @@ future == Js.Date.getTime(date1)
```res sig
let setHours: (t, float) => float
```
-Sets the given `Date`’s hours to the value in the second argument according to the current time zone. Returns the number of milliseconds since the epoch of the updated `Date`. *This function modifies the original `Date`.* See [`Date.setHours`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setHours) on MDN.
+
+Sets the given `Date`’s hours to the value in the second argument according to the current time zone. Returns the number of milliseconds since the epoch of the updated `Date`. _This function modifies the original `Date`._ See [`Date.setHours`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setHours) on MDN.
```res example
let date1 = Js.Date.fromFloat(123456654321.0) // 29 November 1973 21:30:54.321 GMT
@@ -495,7 +532,8 @@ nextHour == Js.Date.getTime(date1)
```res sig
let setHoursM: (t, ~hours: float, ~minutes: float, unit) => float
```
-Sets the given `Date`’s hours and minutes to the values in the labeled arguments according to the current time zone. Returns the number of milliseconds since the epoch of the updated `Date`. *This function modifies the original `Date`.* See [`Date.setHours`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setHours) on MDN.
+
+Sets the given `Date`’s hours and minutes to the values in the labeled arguments according to the current time zone. Returns the number of milliseconds since the epoch of the updated `Date`. _This function modifies the original `Date`._ See [`Date.setHours`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setHours) on MDN.
```res example
let date1 = Js.Date.fromFloat(123456654321.0) // 29 November 1973 21:30:54.321 GMT
@@ -509,7 +547,8 @@ futureTime == Js.Date.getTime(date1)
```res sig
let setHoursMS: (t, ~hours: float, ~minutes: float, ~seconds: float, unit) => float
```
-Sets the given `Date`’s hours, minutes, and seconds to the values in the labeled arguments according to the current time zone. Returns the number of milliseconds since the epoch of the updated `Date`. *This function modifies the original `Date`.* See [`Date.setHours`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setHours) on MDN.
+
+Sets the given `Date`’s hours, minutes, and seconds to the values in the labeled arguments according to the current time zone. Returns the number of milliseconds since the epoch of the updated `Date`. _This function modifies the original `Date`._ See [`Date.setHours`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setHours) on MDN.
```res example
let date1 = Js.Date.fromFloat(123456654321.0) // 29 November 1973 21:30:54.321 GMT
@@ -530,7 +569,8 @@ let setHoursMSMs: (
unit,
) => float
```
-Sets the given `Date`’s hours, minutes, seconds, and milliseconds to the values in the labeled arguments according to the current time zone. Returns the number of milliseconds since the epoch of the updated `Date`. *This function modifies the original `Date`.* See [`Date.setHours`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setHours) on MDN.
+
+Sets the given `Date`’s hours, minutes, seconds, and milliseconds to the values in the labeled arguments according to the current time zone. Returns the number of milliseconds since the epoch of the updated `Date`. _This function modifies the original `Date`._ See [`Date.setHours`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setHours) on MDN.
```res example
let date1 = Js.Date.fromFloat(123456654321.0) // 29 November 1973 21:30:54.321 GMT
@@ -551,7 +591,8 @@ futureTime == Js.Date.getTime(date1)
```res sig
let setMilliseconds: (t, float) => float
```
-Sets the given `Date`’s milliseconds to the value in the second argument according to the current time zone. Returns the number of milliseconds since the epoch of the updated `Date`. *This function modifies the original `Date`.* See [`Date.setMilliseconds`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setMilliseconds) on MDN.
+
+Sets the given `Date`’s milliseconds to the value in the second argument according to the current time zone. Returns the number of milliseconds since the epoch of the updated `Date`. _This function modifies the original `Date`._ See [`Date.setMilliseconds`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setMilliseconds) on MDN.
```res example
let date1 = Js.Date.fromFloat(123456654321.0) // 29 November 1973 21:30:54.321 GMT
@@ -565,7 +606,8 @@ futureTime == Js.Date.getTime(date1)
```res sig
let setMinutes: (t, float) => float
```
-Sets the given `Date`’s minutes to the value in the second argument according to the current time zone. Returns the number of milliseconds since the epoch of the updated `Date`. *This function modifies the original `Date`.* See [`Date.setMinutes`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setMinutes) on MDN.
+
+Sets the given `Date`’s minutes to the value in the second argument according to the current time zone. Returns the number of milliseconds since the epoch of the updated `Date`. _This function modifies the original `Date`._ See [`Date.setMinutes`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setMinutes) on MDN.
```res example
let date1 = Js.Date.fromFloat(123456654321.0) // 29 November 1973 21:30:54.321 GMT
@@ -579,7 +621,8 @@ futureTime == Js.Date.getTime(date1)
```res sig
let setMinutesS: (t, ~minutes: float, ~seconds: float, unit) => float
```
-Sets the given `Date`’s minutes and seconds to the values in the labeled arguments according to the current time zone. Returns the number of milliseconds since the epoch of the updated `Date`. *This function modifies the original `Date`.* See [`Date.setMinutes`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setMinutes) on MDN.
+
+Sets the given `Date`’s minutes and seconds to the values in the labeled arguments according to the current time zone. Returns the number of milliseconds since the epoch of the updated `Date`. _This function modifies the original `Date`._ See [`Date.setMinutes`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setMinutes) on MDN.
```res example
let date1 = Js.Date.fromFloat(123456654321.0) // 29 November 1973 21:30:54.321 GMT
@@ -593,7 +636,8 @@ futureTime == Js.Date.getTime(date1)
```res sig
let setMinutesSMs: (t, ~minutes: float, ~seconds: float, ~milliseconds: float, unit) => float
```
-Sets the given `Date`’s minutes, seconds, and milliseconds to the values in the labeled arguments according to the current time zone. Returns the number of milliseconds since the epoch of the updated `Date`. *This function modifies the original `Date`.* See [`Date.setMinutes`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setMinutes) on MDN.
+
+Sets the given `Date`’s minutes, seconds, and milliseconds to the values in the labeled arguments according to the current time zone. Returns the number of milliseconds since the epoch of the updated `Date`. _This function modifies the original `Date`._ See [`Date.setMinutes`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setMinutes) on MDN.
```res example
let date1 = Js.Date.fromFloat(123456654321.0) // 29 November 1973 21:30:54.321 GMT
@@ -613,7 +657,8 @@ futureTime == Js.Date.getTime(date1)
```res sig
let setMonth: (t, float) => float
```
-Sets the given `Date`’s month to the value in the second argument according to the current time zone. Returns the number of milliseconds since the epoch of the updated `Date`. *This function modifies the original `Date`.* See [`Date.setMonth`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setMonth) on MDN.
+
+Sets the given `Date`’s month to the value in the second argument according to the current time zone. Returns the number of milliseconds since the epoch of the updated `Date`. _This function modifies the original `Date`._ See [`Date.setMonth`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setMonth) on MDN.
```res example
let date1 = Js.Date.fromFloat(123456654321.0) // 29 November 1973 21:30:54.321 GMT
@@ -627,7 +672,8 @@ futureTime == Js.Date.getTime(date1)
```res sig
let setMonthD: (t, ~month: float, ~date: float, unit) => float
```
-Sets the given `Date`’s month and day of month to the values in the labeled arguments according to the current time zone. Returns the number of milliseconds since the epoch of the updated `Date`. *This function modifies the original `Date`.* See [`Date.setMonth`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setMonth) on MDN.
+
+Sets the given `Date`’s month and day of month to the values in the labeled arguments according to the current time zone. Returns the number of milliseconds since the epoch of the updated `Date`. _This function modifies the original `Date`._ See [`Date.setMonth`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setMonth) on MDN.
```res example
let date1 = Js.Date.fromFloat(123456654321.0) // 29 November 1973 21:30:54.321 GMT
@@ -641,7 +687,8 @@ futureTime == Js.Date.getTime(date1)
```res sig
let setSeconds: (t, float) => float
```
-Sets the given `Date`’s seconds to the value in the second argument according to the current time zone. Returns the number of milliseconds since the epoch of the updated `Date`. *This function modifies the original `Date`.* See [`Date.setSeconds`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setSeconds) on MDN.
+
+Sets the given `Date`’s seconds to the value in the second argument according to the current time zone. Returns the number of milliseconds since the epoch of the updated `Date`. _This function modifies the original `Date`._ See [`Date.setSeconds`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setSeconds) on MDN.
```res example
let date1 = Js.Date.fromFloat(123456654321.0) // 29 November 1973 21:30:54.321 GMT
@@ -655,7 +702,8 @@ futureTime == Js.Date.getTime(date1)
```res sig
let setSecondsMs: (t, ~seconds: float, ~milliseconds: float, unit) => float
```
-Sets the given `Date`’s seconds and milliseconds to the values in the labeled arguments according to the current time zone. Returns the number of milliseconds since the epoch of the updated `Date`. *This function modifies the original `Date`.* See [`Date.setSeconds`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setSeconds) on MDN.
+
+Sets the given `Date`’s seconds and milliseconds to the values in the labeled arguments according to the current time zone. Returns the number of milliseconds since the epoch of the updated `Date`. _This function modifies the original `Date`._ See [`Date.setSeconds`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setSeconds) on MDN.
```res example
let date1 = Js.Date.fromFloat(123456654321.0) // 29 November 1973 21:30:54.321 GMT
@@ -669,7 +717,8 @@ futureTime == Js.Date.getTime(date1)
```res sig
let setTime: (t, float) => float
```
-Sets the given `Date`’s value in terms of milliseconds since the epoch. Returns the number of milliseconds since the epoch of the updated `Date`. *This function modifies the original `Date`.* See [`Date.setTime`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setTime) on MDN.
+
+Sets the given `Date`’s value in terms of milliseconds since the epoch. Returns the number of milliseconds since the epoch of the updated `Date`. _This function modifies the original `Date`._ See [`Date.setTime`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setTime) on MDN.
```res example
let date1 = Js.Date.fromFloat(123456654321.0) // 29 November 1973 21:30:54.321 GMT
@@ -684,7 +733,8 @@ futureTime == Js.Date.getTime(date1)
```res sig
let setUTCDate: (t, float) => float
```
-Sets the given `Date`’s day of month to the value in the second argument according to UTC. Returns the number of milliseconds since the epoch of the updated `Date`. *This function modifies the original `Date`.* See [`Date.setUTCDate`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setUTCDate) on MDN.
+
+Sets the given `Date`’s day of month to the value in the second argument according to UTC. Returns the number of milliseconds since the epoch of the updated `Date`. _This function modifies the original `Date`._ See [`Date.setUTCDate`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setUTCDate) on MDN.
```res example
let date1 = Js.Date.fromFloat(123456654321.0) // 29 November 1973 21:30:54.321 GMT
@@ -698,7 +748,8 @@ twoWeeksBefore == Js.Date.getTime(date1)
```res sig
let setUTCFullYear: (t, float) => float
```
-Sets the given `Date`’s year to the value in the second argument according to UTC. Returns the number of milliseconds since the epoch of the updated `Date`. *This function modifies the original `Date`.* See [`Date.setUTCFullYear`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setUTCFullYear) on MDN.
+
+Sets the given `Date`’s year to the value in the second argument according to UTC. Returns the number of milliseconds since the epoch of the updated `Date`. _This function modifies the original `Date`._ See [`Date.setUTCFullYear`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setUTCFullYear) on MDN.
```res example
let date1 = Js.Date.fromFloat(123456654321.0) // 29 November 1973 21:30:54.321 GMT
@@ -712,7 +763,8 @@ nextYear == Js.Date.getTime(date1)
```res sig
let setUTCFullYearM: (t, ~year: float, ~month: float, unit) => float
```
-Sets the given `Date`’s year and month to the values in the labeled arguments according to UTC. Returns the number of milliseconds since the epoch of the updated `Date`. *This function modifies the original `Date`.* See [`Date.setUTCFullYear`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setUTCFullYear) on MDN.
+
+Sets the given `Date`’s year and month to the values in the labeled arguments according to UTC. Returns the number of milliseconds since the epoch of the updated `Date`. _This function modifies the original `Date`._ See [`Date.setUTCFullYear`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setUTCFullYear) on MDN.
```res example
let date1 = Js.Date.fromFloat(123456654321.0) // 29 November 1973 21:30:54.321 GMT
@@ -726,7 +778,8 @@ future == Js.Date.getTime(date1)
```res sig
let setUTCFullYearMD: (t, ~year: float, ~month: float, ~date: float, unit) => float
```
-Sets the given `Date`’s year, month, and day of month to the values in the labeled arguments according to UTC. Returns the number of milliseconds since the epoch of the updated `Date`. *This function modifies the original `Date`.* See [`Date.setUTCFullYear`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setUTCFullYear) on MDN.
+
+Sets the given `Date`’s year, month, and day of month to the values in the labeled arguments according to UTC. Returns the number of milliseconds since the epoch of the updated `Date`. _This function modifies the original `Date`._ See [`Date.setUTCFullYear`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setUTCFullYear) on MDN.
```res example
let date1 = Js.Date.fromFloat(123456654321.0) // 29 November 1973 21:30:54.321 GMT
@@ -740,7 +793,8 @@ future == Js.Date.getTime(date1)
```res sig
let setUTCHours: (t, float) => float
```
-Sets the given `Date`’s hours to the value in the second argument according to UTC. Returns the number of milliseconds since the epoch of the updated `Date`. *This function modifies the original `Date`.* See [`Date.setUTCHours`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setUTCHours) on MDN.
+
+Sets the given `Date`’s hours to the value in the second argument according to UTC. Returns the number of milliseconds since the epoch of the updated `Date`. _This function modifies the original `Date`._ See [`Date.setUTCHours`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setUTCHours) on MDN.
```res example
let date1 = Js.Date.fromFloat(123456654321.0) // 29 November 1973 21:30:54.321 GMT
@@ -754,7 +808,8 @@ nextHour == Js.Date.getTime(date1)
```res sig
let setUTCHoursM: (t, ~hours: float, ~minutes: float, unit) => float
```
-Sets the given `Date`’s hours and minutes to the values in the labeled arguments according to UTC. Returns the number of milliseconds since the epoch of the updated `Date`. *This function modifies the original `Date`.* See [`Date.setUTCHours`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setUTCHours) on MDN.
+
+Sets the given `Date`’s hours and minutes to the values in the labeled arguments according to UTC. Returns the number of milliseconds since the epoch of the updated `Date`. _This function modifies the original `Date`._ See [`Date.setUTCHours`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setUTCHours) on MDN.
```res example
let date1 = Js.Date.fromFloat(123456654321.0) // 29 November 1973 21:30:54.321 GMT
@@ -768,7 +823,8 @@ futureTime == Js.Date.getTime(date1)
```res sig
let setUTCHoursMS: (t, ~hours: float, ~minutes: float, ~seconds: float, unit) => float
```
-Sets the given `Date`’s hours, minutes, and seconds to the values in the labeled arguments according to UTC. Returns the number of milliseconds since the epoch of the updated `Date`. *This function modifies the original `Date`.* See [`Date.setUTCHours`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setUTCHours) on MDN.
+
+Sets the given `Date`’s hours, minutes, and seconds to the values in the labeled arguments according to UTC. Returns the number of milliseconds since the epoch of the updated `Date`. _This function modifies the original `Date`._ See [`Date.setUTCHours`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setUTCHours) on MDN.
```res example
let date1 = Js.Date.fromFloat(123456654321.0) // 29 November 1973 21:30:54.321 GMT
@@ -789,7 +845,8 @@ let setUTCHoursMSMs: (
unit,
) => float
```
-Sets the given `Date`’s hours, minutes, seconds, and milliseconds to the values in the labeled arguments according to UTC. Returns the number of milliseconds since the epoch of the updated `Date`. *This function modifies the original `Date`.* See [`Date.setUTCHours`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setUTCHours) on MDN.
+
+Sets the given `Date`’s hours, minutes, seconds, and milliseconds to the values in the labeled arguments according to UTC. Returns the number of milliseconds since the epoch of the updated `Date`. _This function modifies the original `Date`._ See [`Date.setUTCHours`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setUTCHours) on MDN.
```res example
let date1 = Js.Date.fromFloat(123456654321.0) // 29 November 1973 21:30:54.321 GMT
@@ -810,7 +867,8 @@ futureTime == Js.Date.getTime(date1)
```res sig
let setUTCMilliseconds: (t, float) => float
```
-Sets the given `Date`’s milliseconds to the value in the second argument according to UTC. Returns the number of milliseconds since the epoch of the updated `Date`. *This function modifies the original `Date`.* See [`Date.setUTCMilliseconds`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setUTCMilliseconds) on MDN.
+
+Sets the given `Date`’s milliseconds to the value in the second argument according to UTC. Returns the number of milliseconds since the epoch of the updated `Date`. _This function modifies the original `Date`._ See [`Date.setUTCMilliseconds`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setUTCMilliseconds) on MDN.
```res example
let date1 = Js.Date.fromFloat(123456654321.0) // 29 November 1973 21:30:54.321 GMT
@@ -824,7 +882,8 @@ futureTime == Js.Date.getTime(date1)
```res sig
let setUTCMinutes: (t, float) => float
```
-Sets the given `Date`’s minutes to the value in the second argument according to the current time zone. Returns the number of milliseconds since the epoch of the updated `Date`. *This function modifies the original `Date`.* See [`Date.setUTCMinutes`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setUTCMinutes) on MDN.
+
+Sets the given `Date`’s minutes to the value in the second argument according to the current time zone. Returns the number of milliseconds since the epoch of the updated `Date`. _This function modifies the original `Date`._ See [`Date.setUTCMinutes`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setUTCMinutes) on MDN.
```res example
let date1 = Js.Date.fromFloat(123456654321.0) // 29 November 1973 21:30:54.321 GMT
@@ -838,7 +897,8 @@ futureTime == Js.Date.getTime(date1)
```res sig
let setUTCMinutesS: (t, ~minutes: float, ~seconds: float, unit) => float
```
-Sets the given `Date`’s minutes and seconds to the values in the labeled arguments according to UTC. Returns the number of milliseconds since the epoch of the updated `Date`. *This function modifies the original `Date`.* See [`Date.setUTCMinutes`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setUTCMinutes) on MDN.
+
+Sets the given `Date`’s minutes and seconds to the values in the labeled arguments according to UTC. Returns the number of milliseconds since the epoch of the updated `Date`. _This function modifies the original `Date`._ See [`Date.setUTCMinutes`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setUTCMinutes) on MDN.
```res example
let date1 = Js.Date.fromFloat(123456654321.0) // 29 November 1973 21:30:54.321 GMT
@@ -852,7 +912,8 @@ futureTime == Js.Date.getTime(date1)
```res sig
let setUTCMinutesSMs: (t, ~minutes: float, ~seconds: float, ~milliseconds: float, unit) => float
```
-Sets the given `Date`’s minutes, seconds, and milliseconds to the values in the labeled arguments according to UTC. Returns the number of milliseconds since the epoch of the updated `Date`. *This function modifies the original `Date`.* See [`Date.setUTCMinutes`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setUTCMinutes) on MDN.
+
+Sets the given `Date`’s minutes, seconds, and milliseconds to the values in the labeled arguments according to UTC. Returns the number of milliseconds since the epoch of the updated `Date`. _This function modifies the original `Date`._ See [`Date.setUTCMinutes`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setUTCMinutes) on MDN.
```res example
let date1 = Js.Date.fromFloat(123456654321.0) // 29 November 1973 21:30:54.321 GMT
@@ -872,7 +933,8 @@ futureTime == Js.Date.getTime(date1)
```res sig
let setUTCMonth: (t, float) => float
```
-Sets the given `Date`’s month to the value in the second argument according to UTC. Returns the number of milliseconds since the epoch of the updated `Date`. *This function modifies the original `Date`.* See [`Date.setUTCMonth`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setUTCMonth) on MDN.
+
+Sets the given `Date`’s month to the value in the second argument according to UTC. Returns the number of milliseconds since the epoch of the updated `Date`. _This function modifies the original `Date`._ See [`Date.setUTCMonth`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setUTCMonth) on MDN.
```res example
let date1 = Js.Date.fromFloat(123456654321.0) // 29 November 1973 21:30:54.321 GMT
@@ -886,7 +948,8 @@ futureTime == Js.Date.getTime(date1)
```res sig
let setUTCMonthD: (t, ~month: float, ~date: float, unit) => float
```
-Sets the given `Date`’s month and day of month to the values in the labeled arguments according to UTC. Returns the number of milliseconds since the epoch of the updated `Date`. *This function modifies the original `Date`.* See [`Date.setUTCMonth`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setUTCMonth) on MDN.
+
+Sets the given `Date`’s month and day of month to the values in the labeled arguments according to UTC. Returns the number of milliseconds since the epoch of the updated `Date`. _This function modifies the original `Date`._ See [`Date.setUTCMonth`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setUTCMonth) on MDN.
```res example
let date1 = Js.Date.fromFloat(123456654321.0) // 29 November 1973 21:30:54.321 GMT
@@ -900,7 +963,8 @@ futureTime == Js.Date.getTime(date1)
```res sig
let setUTCSeconds: (t, float) => float
```
-Sets the given `Date`’s seconds to the value in the second argument according to UTC. Returns the number of milliseconds since the epoch of the updated `Date`. *This function modifies the original `Date`.* See [`Date.setUTCSeconds`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setUTCSeconds) on MDN.
+
+Sets the given `Date`’s seconds to the value in the second argument according to UTC. Returns the number of milliseconds since the epoch of the updated `Date`. _This function modifies the original `Date`._ See [`Date.setUTCSeconds`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setUTCSeconds) on MDN.
```res example
let date1 = Js.Date.fromFloat(123456654321.0) // 29 November 1973 21:30:54.321 GMT
@@ -914,7 +978,8 @@ futureTime == Js.Date.getTime(date1)
```res sig
let setUTCSecondsMs: (t, ~seconds: float, ~milliseconds: float, unit) => float
```
-Sets the given `Date`’s seconds and milliseconds to the values in the labeled arguments according to UTC. Returns the number of milliseconds since the epoch of the updated `Date`. *This function modifies the original `Date`.* See [`Date.setUTCSeconds`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setUTCSeconds) on MDN.
+
+Sets the given `Date`’s seconds and milliseconds to the values in the labeled arguments according to UTC. Returns the number of milliseconds since the epoch of the updated `Date`. _This function modifies the original `Date`._ See [`Date.setUTCSeconds`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setUTCSeconds) on MDN.
```res example
let date1 = Js.Date.fromFloat(123456654321.0) // 29 November 1973 21:30:54.321 GMT
@@ -928,6 +993,7 @@ futureTime == Js.Date.getTime(date1)
```res sig
let setUTCTime: (t, float) => float
```
+
Same as [`setTime()`](#settime).
## setYear
@@ -935,6 +1001,7 @@ Same as [`setTime()`](#settime).
```res sig
let setYear: (t, float) => float
```
+
Deprecated. Use [`setFullYear()`](#setfullyear) instead.
## toDateString
@@ -942,6 +1009,7 @@ Deprecated. Use [`setFullYear()`](#setfullyear) instead.
```res sig
let toDateString: t => string
```
+
Returns the date (day of week, year, month, and day of month) portion of a `Date` in English. See [`Date.toDateString`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toDateString) on MDN.
```res example
@@ -953,6 +1021,7 @@ Js.Date.toDateString(exampleDate) == "Thu Nov 29 1973"
```res sig
let toGMTString: t => string
```
+
Deprecated. Use [`toUTCString()`](#toutcstring) instead.
## toISOString
@@ -960,6 +1029,7 @@ Deprecated. Use [`toUTCString()`](#toutcstring) instead.
```res sig
let toISOString: t => string
```
+
Returns a simplified version of the ISO 8601 format for the date. See [`Date.toISOString`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString) on MDN.
```res example
@@ -971,6 +1041,7 @@ Js.Date.toISOString(exampleDate) == "1973-11-29T21:30:54.321Z"
```res sig
let toJSON: t => string
```
+
Deprecated. This method is unsafe. It will be changed to return `option` in a future release. Please use `toJSONUnsafe()` instead.
## toJSONUnsafe
@@ -978,6 +1049,7 @@ Deprecated. This method is unsafe. It will be changed to return `option` in a fu
```res sig
let toJSONUnsafe: t => string
```
+
Returns a string representation of the given date. See [`Date.toJSON`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toJSON) on MDN.
```res example
@@ -997,12 +1069,12 @@ Js.Date.toLocaleDateString(exampleDate) == "11/29/1973" // for en_US.utf8
Js.Date.toLocaleDateString(exampleDate) == "29.11.73" // for de_DE.utf8
```
-
## toLocaleString
```res sig
let toLocaleString: t => string
```
+
Returns the time and date for the given `Date` in the current locale format. See [`Date.toLocaleString`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString) on MDN.
```res example
@@ -1015,6 +1087,7 @@ Js.Date.toLocaleString(exampleDate) == "29.11.1973, 22:30:54" // for de_DE.utf8
```res sig
let toLocaleTimeString: t => string
```
+
Returns the time of day for the given `Date` in the current locale format. See [`Date.toLocaleTimeString`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleTimeString) on MDN.
```res example
@@ -1027,6 +1100,7 @@ Js.Date.toLocaleString(exampleDate) == "22:30:54" // for de_DE.utf8
```res sig
let toString: t => string
```
+
Returns a string representing the date and time of day for the given `Date` in the current locale and time zone. See [`Date.toString`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toString) on MDN.
```res example
@@ -1041,7 +1115,7 @@ Js.Date.toString(
let toTimeString: t => string
```
-Returns a string representing the time of day for the given `Date` in the current locale and time zone. See [`Date.toTimeString`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toTimeString) on MDN.
+Returns a string representing the time of day for the given `Date` in the current locale and time zone. See [`Date.toTimeString`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toTimeString) on MDN.
```res example
Js.Date.toTimeString(exampleDate) == "22:30:54 GMT+0100 (Central European Standard Time)"
diff --git a/pages/docs/manual/v9.0.0/api/js/dict.mdx b/pages/docs/manual/v9.0.0/api/js/dict.mdx
index 881527a9e..0758932ae 100644
--- a/pages/docs/manual/v9.0.0/api/js/dict.mdx
+++ b/pages/docs/manual/v9.0.0/api/js/dict.mdx
@@ -27,7 +27,7 @@ This Dictionary type is mostly used with the Js_json.t type.
type key = string
```
-The type for dictionary keys. This means that dictionaries *must* use `string`s as their keys.
+The type for dictionary keys. This means that dictionaries _must_ use `string`s as their keys.
## get
@@ -47,6 +47,7 @@ Js.Dict.get(ages, "Paul") == None
```res sig
let unsafeGet: (t<'a>, key) => 'a
```
+
`Js.Dict.unsafeGet(key)` returns the value if the key exists, otherwise an `undefined` value is returned. Use this only when you are sure the key exists (i.e. when having used the `keys()` function to check that the key is valid).
```res example
@@ -60,7 +61,7 @@ Js.Dict.unsafeGet(ages, "Paul") // returns undefined
let set: (t<'a>, key, 'a) => unit
```
-`Js.Dict.set(dict, key, value)` sets the key/value in the dictionary `dict`. If the key does not exist, and entry will be created for it. *This function modifies the original dictionary.*
+`Js.Dict.set(dict, key, value)` sets the key/value in the dictionary `dict`. If the key does not exist, and entry will be created for it. _This function modifies the original dictionary._
```res example
Js.Dict.set(ages, "Maria", 31)
diff --git a/pages/docs/manual/v9.0.0/api/js/float.mdx b/pages/docs/manual/v9.0.0/api/js/float.mdx
index 1da019985..13f375ad5 100644
--- a/pages/docs/manual/v9.0.0/api/js/float.mdx
+++ b/pages/docs/manual/v9.0.0/api/js/float.mdx
@@ -6,11 +6,12 @@ Provide utilities for JS float.
-## _NaN
+## \_NaN
```res sig
let _NaN: float
```
+
The special value "Not a Number".
## isNaN
@@ -19,7 +20,7 @@ The special value "Not a Number".
let isNaN: float => bool
```
-Tests if the given value is _NaN.
+Tests if the given value is \_NaN.
Note that both `_NaN == _NaN` and `_NaN === _NaN` will return false. `isNaN` is therefore necessary to test for `_NaN`.
Returns true if the given value is `_NaN`, false otherwise.
diff --git a/pages/docs/manual/v9.0.0/api/js/json.mdx b/pages/docs/manual/v9.0.0/api/js/json.mdx
index ca48da776..99c970894 100644
--- a/pages/docs/manual/v9.0.0/api/js/json.mdx
+++ b/pages/docs/manual/v9.0.0/api/js/json.mdx
@@ -41,7 +41,6 @@ type tagged_t =
| JSONArray(array)
```
-
## classify
```res sig
@@ -136,7 +135,7 @@ let boolean: bool => t
`boolean(b)` makes a JSON boolean of the `bool` `b`.
-## object_
+## object\_
```res sig
let object_: Js_dict.t => t
@@ -182,7 +181,7 @@ let booleanArray: array => t
let objectArray: array> => t
```
-`objectArray(a) makes a JSON array of the `JsDict.t` array `a`.
+`objectArray(a) makes a JSON array of the `JsDict.t`array`a`.
## parseExn
diff --git a/pages/docs/manual/v9.0.0/api/js/math.mdx b/pages/docs/manual/v9.0.0/api/js/math.mdx
index 90592d361..69cd10d4d 100644
--- a/pages/docs/manual/v9.0.0/api/js/math.mdx
+++ b/pages/docs/manual/v9.0.0/api/js/math.mdx
@@ -6,7 +6,7 @@ Provide utilities for JS Math. Note: The constants `_E`, `_LN10`, `_LN2`, `_LOG1
-## _E
+## \_E
```res sig
let _E: float
@@ -14,7 +14,7 @@ let _E: float
Euler's number; ≈ 2.718281828459045. See [`Math.E`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/E) on MDN.
-## _LN2
+## \_LN2
```res sig
let _LN2: float
@@ -22,7 +22,7 @@ let _LN2: float
Natural logarithm of 2; ≈ 0.6931471805599453. See [`Math.LN2`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/LN2) on MDN.
-## _LN10
+## \_LN10
```res sig
let _LN10: float
@@ -30,7 +30,7 @@ let _LN10: float
Natural logarithm of 10; ≈ 2.302585092994046. See [`Math.LN10`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/LN10) on MDN.
-## _LOG2E
+## \_LOG2E
```res sig
let _LOG2E: float
@@ -38,7 +38,7 @@ let _LOG2E: float
Base 2 logarithm of E; ≈ 1.4426950408889634. See [`Math.LOG2E`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/LOG2E) on MDN.
-## _LOG10E
+## \_LOG10E
```res sig
let _LOG10E: float
@@ -46,7 +46,7 @@ let _LOG10E: float
Base 10 logarithm of E; ≈ 0.4342944819032518. See [`Math.LOG10E`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/LOG10E) on MDN.
-## _PI
+## \_PI
```res sig
let _PI: float
@@ -54,7 +54,7 @@ let _PI: float
Pi - ratio of the circumference to the diameter of a circle; ≈ 3.141592653589793. See [`Math.PI`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/PI) on MDN.
-## _SQRT1_2
+## \_SQRT1_2
```res sig
let _SQRT1_2: float
@@ -62,7 +62,7 @@ let _SQRT1_2: float
Square root of 1/2; ≈ 0.7071067811865476. See [`Math.SQRT1_2`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/SQRT1_2) on MDN.
-## _SQRT2
+## \_SQRT2
```res sig
let _SQRT2: float
@@ -140,7 +140,7 @@ Hyperbolic arctangent (in radians) of argument; returns `NaN` if the argument is
let atan2: (~y: float, ~x: float, unit) => float
```
-Returns the angle (in radians) of the quotient `y /. x`. It is also the angle between the *x*-axis and point (*x*, *y*). See [`Math.atan2`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/atan2) on MDN.
+Returns the angle (in radians) of the quotient `y /. x`. It is also the angle between the _x_-axis and point (_x_, _y_). See [`Math.atan2`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/atan2) on MDN.
```res example
Js.Math.atan2(~y=0.0, ~x=10.0, ()) == 0.0
@@ -178,6 +178,7 @@ Js.Math.unsafe_ceil_int(1.0e15) // result is outside range of int datatype
```res sig
let unsafe_ceil: float => int
```
+
Deprecated; please use [`unsafe_ceil_int`](#unsafe_ceil_int) instead.
## ceil_int
@@ -255,7 +256,7 @@ Hyperbolic cosine of argument, which must be specified in radians. See [`Math.co
let exp: float => float
```
-Natural exponentional; returns *e* (the base of natural logarithms) to the power of the given argument. See [`Math.exp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/exp) on MDN.
+Natural exponentional; returns _e_ (the base of natural logarithms) to the power of the given argument. See [`Math.exp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/exp) on MDN.
## expm1
@@ -263,7 +264,7 @@ Natural exponentional; returns *e* (the base of natural logarithms) to the power
let expm1: float => float
```
-Returns *e* (the base of natural logarithms) to the power of the given argument minus 1. See [`Math.expm1`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/expm1) on MDN.
+Returns _e_ (the base of natural logarithms) to the power of the given argument minus 1. See [`Math.expm1`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/expm1) on MDN.
## unsafe_floor_int
@@ -326,6 +327,7 @@ Js.Math.floor_float(3.0) == 3.0
Js.Math.floor_float(-3.1) == -4.0
Js.Math.floor_float(2_150_000_000.3) == 2_150_000_000.0
```
+
## fround
```res sig
@@ -373,7 +375,7 @@ let imul: (int, int) => int
let log: float => float
```
-Returns the natural logarithm of its argument; this is the number *x* such that *e**x* equals the argument. Returns `NaN` for negative arguments. See [`Math.log`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/log) on MDN.
+Returns the natural logarithm of its argument; this is the number _x_ such that _e__x_ equals the argument. Returns `NaN` for negative arguments. See [`Math.log`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/log) on MDN.
```res example
Js.Math.log(Js.Math._E) == 1.0
@@ -421,14 +423,13 @@ Js.Math.log2(0.125) == -3.0
Js.Math.log2(Js.Math._SQRT2) == 0.5000000000000001 // due to precision
```
-
## max_int
```res sig
let max_int: (int, int) => int
```
-Returns the maximum of its two integer arguments. See [`Math.max`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/max) on MDN.
+Returns the maximum of its two integer arguments. See [`Math.max`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/max) on MDN.
## maxMany_int
@@ -436,7 +437,7 @@ Returns the maximum of its two integer arguments. See [`Math.max`](https://deve
let maxMany_int: array => int
```
-Returns the maximum of the integers in the given array. See [`Math.max`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/max) on MDN.
+Returns the maximum of the integers in the given array. See [`Math.max`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/max) on MDN.
## max_float
@@ -462,7 +463,6 @@ let min_int: (int, int) => int
Returns the minimum of its two integer arguments. See [`Math.min`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/min) on MDN.
-
## minMany_int
```res sig
@@ -487,7 +487,6 @@ let minMany_float: array => float
Returns the minimum of the floating point values in the given array. See [`Math.min`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/min) on MDN.
-
## pow_int
```res sig
@@ -500,7 +499,6 @@ Raises the given base to the given exponent. (Arguments and result are integers.
Js.Math.pow_int(~base=3, ~exp=4) == 81
```
-
## pow_float
```res sig
@@ -539,7 +537,7 @@ A call to `random_int(minVal, maxVal)` returns a random number in the half-close
let unsafe_round: float => int
```
-Rounds its argument to nearest integer. For numbers with a fractional portion of exactly 0.5, the argument is rounded to the next integer in the direction of positive infinity. This function may return values not representable by `int`, whose range is -2147483648 to 2147483647. This is because, in JavaScript, there are only 64-bit floating point numbers, which can represent integers in the range ±(253 -1) exactly. See [`Math.round`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round) on MDN.
+Rounds its argument to nearest integer. For numbers with a fractional portion of exactly 0.5, the argument is rounded to the next integer in the direction of positive infinity. This function may return values not representable by `int`, whose range is -2147483648 to 2147483647. This is because, in JavaScript, there are only 64-bit floating point numbers, which can represent integers in the range ±(253 -1) exactly. See [`Math.round`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round) on MDN.
```res example
Js.Math.unsafe_round(3.7) == 4
@@ -555,7 +553,6 @@ let round: float => float
Rounds to nearest integral value (expressed as a float). See [`Math.round`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round) on MDN.
-
## sign_int
```res sig
@@ -569,6 +566,7 @@ Returns the sign of its integer argument: -1 if negative, 0 if zero, 1 if positi
```res sig
let sign_float: float => float
```
+
Returns the sign of its float argument: -1.0 if negative, 0.0 if zero, 1.0 if positive. See [`Math.sign`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign) on MDN.
## sin
diff --git a/pages/docs/manual/v9.0.0/api/js/option.mdx b/pages/docs/manual/v9.0.0/api/js/option.mdx
index ed23e8a64..61e3700c8 100644
--- a/pages/docs/manual/v9.0.0/api/js/option.mdx
+++ b/pages/docs/manual/v9.0.0/api/js/option.mdx
@@ -17,6 +17,7 @@ type t<'a> = option<'a>
```res sig
let some: 'a => option<'a>
```
+
Wraps the given value in `Some()`
```res example
@@ -72,10 +73,10 @@ The first argument to `equal` is an uncurried function `eq()` that takes two arg
If the second and third arguments are of the form:
-* `Some(v1)` and `Some(v2)`: returns `eq(v1, v2)`
-* `Some(v1)` and `None`: returns `false`
-* `None` and `Some(v2)`: returns `false`
-* `None` and `None`: returns `true`
+- `Some(v1)` and `Some(v2)`: returns `eq(v1, v2)`
+- `Some(v1)` and `None`: returns `false`
+- `None` and `Some(v2)`: returns `false`
+- `None` and `None`: returns `true`
```res example
let clockEqual = (. a, b) => mod(a, 12) == mod(b, 12)
diff --git a/pages/docs/manual/v9.0.0/api/js/promise.mdx b/pages/docs/manual/v9.0.0/api/js/promise.mdx
index 52d06c41d..df1331769 100644
--- a/pages/docs/manual/v9.0.0/api/js/promise.mdx
+++ b/pages/docs/manual/v9.0.0/api/js/promise.mdx
@@ -78,7 +78,7 @@ let all6: ((t<'a0>, t<'a1>, t<'a2>, t<'a3>, t<'a4>, t<'a5>)) => t<('a0, 'a1, 'a2
let race: array> => t<'a>
```
-## then_
+## then\_
```res sig
let then_: ('a => t<'b>, t<'a>) => t<'b>
diff --git a/pages/docs/manual/v9.0.0/api/js/string-2.mdx b/pages/docs/manual/v9.0.0/api/js/string-2.mdx
index 7d88129c4..c38ec4b85 100644
--- a/pages/docs/manual/v9.0.0/api/js/string-2.mdx
+++ b/pages/docs/manual/v9.0.0/api/js/string-2.mdx
@@ -252,6 +252,7 @@ Js.String2.indexOf("bookseller", "xyz") == -1
```res sig
let indexOfFrom: (t, t, int) => int
```
+
`indexOfFrom(str, searchValue, start)` returns the position at which `searchValue` was found within `str` starting at character position `start`, or -1 if `searchValue` is not found in that portion of `str`.
The return value is relative to the beginning of the string, no matter where the search started from. See [`String.indexOf`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf) on MDN.
@@ -299,6 +300,7 @@ let localeCompare: (t, t) => float
```
`localeCompare(reference, comparison)` returns
+
- a negative value if reference comes before comparison in sort order
- zero if reference and comparison have the same sort order
- a positive value if reference comes after comparison in sort order
@@ -319,9 +321,10 @@ let match_: (t, Js_re.t) => option>
```
`match(str, regexp)` matches a `string` against the given `regexp`. If there is no match, it returns `None`. For regular expressions without the g modifier, if there is a match, the return value is `Some(array)` where the array contains:
+
- The entire matched string
- Any capture groups if the regexp had parentheses
-For regular expressions with the g modifier, a matched expression returns `Some(array)` with all the matched substrings and no capture groups. See [`String.match`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match) on MDN.
+ For regular expressions with the g modifier, a matched expression returns `Some(array)` with all the matched substrings and no capture groups. See [`String.match`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match) on MDN.
```res example
Js.String2.match_("The better bats", %re("/b[aeiou]t/")) == Some(["bet"])
@@ -348,6 +351,7 @@ let normalizeByForm: (t, t) => t
```
ES2015: `normalize(str, form)` returns the normalized Unicode string using the specified form of normalization, which may be one of:
+
- "NFC" — Normalization Form Canonical Composition.
- "NFD" — Normalization Form Canonical Decomposition.
- "NFKC" — Normalization Form Compatibility Composition.
@@ -482,6 +486,7 @@ let slice: (t, ~from: int, ~to_: int) => t
```
`slice(str, from:n1, to_:n2)` returns the substring of `str` starting at character `n1` up to but not including `n2`.
+
- If either `n1` or `n2` is negative, then it is evaluated as `length(str - n1)` or `length(str - n2)`.
- If `n2` is greater than the length of `str`, then it is treated as `length(str)`.
- If `n1` is greater than `n2`, slice returns the empty string.
@@ -502,6 +507,7 @@ let sliceToEnd: (t, ~from: int) => t
```
`sliceToEnd(str, from:n)` returns the substring of `str` starting at character `n` to the end of the string.
+
- If `n` is negative, then it is evaluated as `length(str - n)`.
- If `n` is greater than the length of `str`, then sliceToEnd returns the empty string.
@@ -628,6 +634,7 @@ let substr: (t, ~from: int) => t
```
`substr(str, ~from:n)` returns the substring of `str` from position `n` to the end of the string.
+
- If `n` is less than zero, the starting position is the length of `str - n`.
- If `n` is greater than or equal to the length of `str`, returns the empty string.
@@ -646,6 +653,7 @@ let substrAtMost: (t, ~from: int, ~length: int) => t
```
`substrAtMost(str, ~from: pos, ~length: n)` returns the substring of `str` of length `n` starting at position `pos`.
+
- If `pos` is less than zero, the starting position is the length of `str - pos`.
- If `pos` is greater than or equal to the length of `str`, returns the empty string.
- If `n` is less than or equal to zero, returns the empty string.
@@ -665,6 +673,7 @@ let substring: (t, ~from: int, ~to_: int) => t
```
`substring(str, ~from: start, ~to_: finish)` returns characters `start` up to but not including finish from `str`.
+
- If `start` is less than zero, it is treated as zero.
- If `finish` is zero or negative, the empty string is returned.
- If `start` is greater than `finish`, the `start` and `finish` points are swapped.
@@ -684,6 +693,7 @@ let substringToEnd: (t, ~from: int) => t
```
`substringToEnd(str, ~from: start)` returns the substring of `str` from position `start` to the end.
+
- If `start` is less than or equal to zero, the entire string is returned.
- If `start` is greater than or equal to the length of `str`, the empty string is returned.
diff --git a/pages/docs/manual/v9.0.0/api/js/string.mdx b/pages/docs/manual/v9.0.0/api/js/string.mdx
index 7e4eb846d..597ff07b8 100644
--- a/pages/docs/manual/v9.0.0/api/js/string.mdx
+++ b/pages/docs/manual/v9.0.0/api/js/string.mdx
@@ -252,6 +252,7 @@ Js.String.indexOf("xyz", "bookseller") == -1
```res sig
let indexOfFrom: (t, t, int) => int
```
+
`indexOfFrom(searchValue, start, str)` returns the position at which `searchValue` was found within `str` starting at character position `start`, or -1 if `searchValue` is not found in that portion of `str`.
The return value is relative to the beginning of the string, no matter where the search started from. See [`String.indexOf`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf) on MDN.
@@ -299,6 +300,7 @@ let localeCompare: (t, t) => float
```
`localeCompare(comparison, reference)` returns
+
- a negative value if reference comes before comparison in sort order
- zero if reference and comparison have the same sort order
- a positive value if reference comes after comparison in sort order
@@ -319,9 +321,10 @@ let match_: (Js_re.t, t) => option>
```
`match(regexp, str)` matches a `string` against the given `regexp`. If there is no match, it returns `None`. For regular expressions without the g modifier, if there is a match, the return value is `Some(array)` where the array contains:
+
- The entire matched string
- Any capture groups if the regexp had parentheses
-For regular expressions with the g modifier, a matched expression returns `Some(array)` with all the matched substrings and no capture groups. See [`String.match`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match) on MDN.
+ For regular expressions with the g modifier, a matched expression returns `Some(array)` with all the matched substrings and no capture groups. See [`String.match`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match) on MDN.
```res example
Js.String.match_(%re("/b[aeiou]t/"), "The better bats") == Some(["bet"])
@@ -348,6 +351,7 @@ let normalizeByForm: (t, t) => t
```
ES2015: `normalize(form, str)` returns the normalized Unicode string using the specified form of normalization, which may be one of:
+
- "NFC" — Normalization Form Canonical Composition.
- "NFD" — Normalization Form Canonical Decomposition.
- "NFKC" — Normalization Form Compatibility Composition.
@@ -482,6 +486,7 @@ let slice: (~from: int, ~to_: int, t) => t
```
`slice(from:n1, to_:n2, str)` returns the substring of `str` starting at character `n1` up to but not including `n2`.
+
- If either `n1` or `n2` is negative, then it is evaluated as `length(str - n1)` or `length(str - n2)`.
- If `n2` is greater than the length of `str`, then it is treated as `length(str)`.
- If `n1` is greater than `n2`, slice returns the empty string.
@@ -502,6 +507,7 @@ let sliceToEnd: (~from: int, t) => t
```
`sliceToEnd(str, from:n)` returns the substring of `str` starting at character `n` to the end of the string.
+
- If `n` is negative, then it is evaluated as `length(str - n)`.
- If `n` is greater than the length of `str`, then sliceToEnd returns the empty string.
@@ -638,6 +644,7 @@ let substr: (~from: int, t) => t
```
`substr(~from:n, str)` returns the substring of `str` from position `n` to the end of the string.
+
- If `n` is less than zero, the starting position is the length of `str - n`.
- If `n` is greater than or equal to the length of `str`, returns the empty string.
@@ -656,6 +663,7 @@ let substrAtMost: (~from: int, ~length: int, t) => t
```
`substrAtMost(~from: pos, ~length: n, str)` returns the substring of `str` of length `n` starting at position `pos`.
+
- If `pos` is less than zero, the starting position is the length of `str - pos`.
- If `pos` is greater than or equal to the length of `str`, returns the empty string.
- If `n` is less than or equal to zero, returns the empty string.
@@ -675,6 +683,7 @@ let substring: (~from: int, ~to_: int, t) => t
```
`substring(~from: start, ~to_: finish, str)` returns characters `start` up to but not including finish from `str`.
+
- If `start` is less than zero, it is treated as zero.
- If `finish` is zero or negative, the empty string is returned.
- If `start` is greater than `finish`, the `start` and `finish` points are swapped.
@@ -694,6 +703,7 @@ let substringToEnd: (~from: int, t) => t
```
`substringToEnd(~from: start, str)` returns the substring of `str` from position `start` to the end.
+
- If `start` is less than or equal to zero, the entire string is returned.
- If `start` is greater than or equal to the length of `str`, the empty string is returned.
diff --git a/pages/docs/manual/v9.0.0/api/js/typed-array-2.mdx b/pages/docs/manual/v9.0.0/api/js/typed-array-2.mdx
index 617e9324d..ab447dbdc 100644
--- a/pages/docs/manual/v9.0.0/api/js/typed-array-2.mdx
+++ b/pages/docs/manual/v9.0.0/api/js/typed-array-2.mdx
@@ -19,13 +19,23 @@ type array_like<'a>
```
## module ArrayBuffer
+
## module Int8Array
+
## module Uint8Array
+
## module Uint8ClampedArray
+
## module Int16Array
+
## module Uint16Array
+
## module Int32Array
+
## module Uint32Array
+
## module Float32Array
+
## module Float64Array
+
## module DataView
diff --git a/pages/docs/manual/v9.0.0/api/js/typed-array-2_array-buffer.mdx b/pages/docs/manual/v9.0.0/api/js/typed-array-2_array-buffer.mdx
index 5bef6f7e8..a0af5cafa 100644
--- a/pages/docs/manual/v9.0.0/api/js/typed-array-2_array-buffer.mdx
+++ b/pages/docs/manual/v9.0.0/api/js/typed-array-2_array-buffer.mdx
@@ -20,7 +20,6 @@ let make: int => t
Takes length. initializes elements to 0.
-
## byteLength
```res sig
diff --git a/pages/docs/manual/v9.0.0/api/js/typed-array-2_float-32-array.mdx b/pages/docs/manual/v9.0.0/api/js/typed-array-2_float-32-array.mdx
index 2bfec4069..e8ded9652 100644
--- a/pages/docs/manual/v9.0.0/api/js/typed-array-2_float-32-array.mdx
+++ b/pages/docs/manual/v9.0.0/api/js/typed-array-2_float-32-array.mdx
@@ -314,7 +314,7 @@ let some: ((. elt) => bool, t) => bool
let somei: ((. elt, int) => bool, t) => bool
```
-## _BYTES_PER_ELEMENT
+## \_BYTES_PER_ELEMENT
```res sig
let _BYTES_PER_ELEMENT: int
diff --git a/pages/docs/manual/v9.0.0/api/js/typed-array-2_float-64-array.mdx b/pages/docs/manual/v9.0.0/api/js/typed-array-2_float-64-array.mdx
index 5cf59253b..9e56a8585 100644
--- a/pages/docs/manual/v9.0.0/api/js/typed-array-2_float-64-array.mdx
+++ b/pages/docs/manual/v9.0.0/api/js/typed-array-2_float-64-array.mdx
@@ -314,7 +314,7 @@ let some: ((. elt) => bool, t) => bool
let somei: ((. elt, int) => bool, t) => bool
```
-## _BYTES_PER_ELEMENT
+## \_BYTES_PER_ELEMENT
```res sig
let _BYTES_PER_ELEMENT: int
diff --git a/pages/docs/manual/v9.0.0/api/js/typed-array-2_int-16-array.mdx b/pages/docs/manual/v9.0.0/api/js/typed-array-2_int-16-array.mdx
index 6452ee5ef..754bbaa80 100644
--- a/pages/docs/manual/v9.0.0/api/js/typed-array-2_int-16-array.mdx
+++ b/pages/docs/manual/v9.0.0/api/js/typed-array-2_int-16-array.mdx
@@ -314,7 +314,7 @@ let some: ((. elt) => bool, t) => bool
let somei: ((. elt, int) => bool, t) => bool
```
-## _BYTES_PER_ELEMENT
+## \_BYTES_PER_ELEMENT
```res sig
let _BYTES_PER_ELEMENT: int
diff --git a/pages/docs/manual/v9.0.0/api/js/typed-array-2_int-32-array.mdx b/pages/docs/manual/v9.0.0/api/js/typed-array-2_int-32-array.mdx
index da230b64b..efeb8dddd 100644
--- a/pages/docs/manual/v9.0.0/api/js/typed-array-2_int-32-array.mdx
+++ b/pages/docs/manual/v9.0.0/api/js/typed-array-2_int-32-array.mdx
@@ -314,7 +314,7 @@ let some: ((. elt) => bool, t) => bool
let somei: ((. elt, int) => bool, t) => bool
```
-## _BYTES_PER_ELEMENT
+## \_BYTES_PER_ELEMENT
```res sig
let _BYTES_PER_ELEMENT: int
diff --git a/pages/docs/manual/v9.0.0/api/js/typed-array-2_int-8-array.mdx b/pages/docs/manual/v9.0.0/api/js/typed-array-2_int-8-array.mdx
index d0676dce3..c75df550c 100644
--- a/pages/docs/manual/v9.0.0/api/js/typed-array-2_int-8-array.mdx
+++ b/pages/docs/manual/v9.0.0/api/js/typed-array-2_int-8-array.mdx
@@ -314,7 +314,7 @@ let some: ((. elt) => bool, t) => bool
let somei: ((. elt, int) => bool, t) => bool
```
-## _BYTES_PER_ELEMENT
+## \_BYTES_PER_ELEMENT
```res sig
let _BYTES_PER_ELEMENT: int
diff --git a/pages/docs/manual/v9.0.0/api/js/typed-array-2_uint-16-array.mdx b/pages/docs/manual/v9.0.0/api/js/typed-array-2_uint-16-array.mdx
index 67ad8e6db..38a507f30 100644
--- a/pages/docs/manual/v9.0.0/api/js/typed-array-2_uint-16-array.mdx
+++ b/pages/docs/manual/v9.0.0/api/js/typed-array-2_uint-16-array.mdx
@@ -314,7 +314,7 @@ let some: ((. elt) => bool, t) => bool
let somei: ((. elt, int) => bool, t) => bool
```
-## _BYTES_PER_ELEMENT
+## \_BYTES_PER_ELEMENT
```res sig
let _BYTES_PER_ELEMENT: int
diff --git a/pages/docs/manual/v9.0.0/api/js/typed-array-2_uint-32-array.mdx b/pages/docs/manual/v9.0.0/api/js/typed-array-2_uint-32-array.mdx
index e27f5075f..d65d4174d 100644
--- a/pages/docs/manual/v9.0.0/api/js/typed-array-2_uint-32-array.mdx
+++ b/pages/docs/manual/v9.0.0/api/js/typed-array-2_uint-32-array.mdx
@@ -314,7 +314,7 @@ let some: ((. elt) => bool, t) => bool
let somei: ((. elt, int) => bool, t) => bool
```
-## _BYTES_PER_ELEMENT
+## \_BYTES_PER_ELEMENT
```res sig
let _BYTES_PER_ELEMENT: int
diff --git a/pages/docs/manual/v9.0.0/api/js/typed-array-2_uint-8-array.mdx b/pages/docs/manual/v9.0.0/api/js/typed-array-2_uint-8-array.mdx
index 3af6a295d..4bb64163b 100644
--- a/pages/docs/manual/v9.0.0/api/js/typed-array-2_uint-8-array.mdx
+++ b/pages/docs/manual/v9.0.0/api/js/typed-array-2_uint-8-array.mdx
@@ -314,7 +314,7 @@ let some: ((. elt) => bool, t) => bool
let somei: ((. elt, int) => bool, t) => bool
```
-## _BYTES_PER_ELEMENT
+## \_BYTES_PER_ELEMENT
```res sig
let _BYTES_PER_ELEMENT: int
diff --git a/pages/docs/manual/v9.0.0/api/js/typed-array-2_uint-8-clamped-array.mdx b/pages/docs/manual/v9.0.0/api/js/typed-array-2_uint-8-clamped-array.mdx
index 4a015d3ba..effd38955 100644
--- a/pages/docs/manual/v9.0.0/api/js/typed-array-2_uint-8-clamped-array.mdx
+++ b/pages/docs/manual/v9.0.0/api/js/typed-array-2_uint-8-clamped-array.mdx
@@ -314,7 +314,7 @@ let some: ((. elt) => bool, t) => bool
let somei: ((. elt, int) => bool, t) => bool
```
-## _BYTES_PER_ELEMENT
+## \_BYTES_PER_ELEMENT
```res sig
let _BYTES_PER_ELEMENT: int
diff --git a/pages/docs/manual/v9.0.0/api/js/typed-array.mdx b/pages/docs/manual/v9.0.0/api/js/typed-array.mdx
index b62f9e668..cbafefce5 100644
--- a/pages/docs/manual/v9.0.0/api/js/typed-array.mdx
+++ b/pages/docs/manual/v9.0.0/api/js/typed-array.mdx
@@ -27,14 +27,25 @@ module type Type = {
```
## module ArrayBuffer
+
## module type S
+
## module Int8Array
+
## module Uint8Array
+
## module Uint8ClampedArray
+
## module Int16Array
+
## module Uint16Array
+
## module Int32Array
+
## module Uint32Array
+
## module Float32Array
+
## module Float64Array
+
## module DataView
diff --git a/pages/docs/manual/v9.0.0/api/js/typed-array_float-32-array.mdx b/pages/docs/manual/v9.0.0/api/js/typed-array_float-32-array.mdx
index c10ae364d..06b3a5866 100644
--- a/pages/docs/manual/v9.0.0/api/js/typed-array_float-32-array.mdx
+++ b/pages/docs/manual/v9.0.0/api/js/typed-array_float-32-array.mdx
@@ -314,7 +314,7 @@ let some: ((. elt) => bool, t) => bool
let somei: ((. elt, int) => bool, t) => bool
```
-## _BYTES_PER_ELEMENT
+## \_BYTES_PER_ELEMENT
```res sig
let _BYTES_PER_ELEMENT: int
diff --git a/pages/docs/manual/v9.0.0/api/js/typed-array_float-64-array.mdx b/pages/docs/manual/v9.0.0/api/js/typed-array_float-64-array.mdx
index d7222de99..3df7aaa1a 100644
--- a/pages/docs/manual/v9.0.0/api/js/typed-array_float-64-array.mdx
+++ b/pages/docs/manual/v9.0.0/api/js/typed-array_float-64-array.mdx
@@ -314,7 +314,7 @@ let some: ((. elt) => bool, t) => bool
let somei: ((. elt, int) => bool, t) => bool
```
-## _BYTES_PER_ELEMENT
+## \_BYTES_PER_ELEMENT
```res sig
let _BYTES_PER_ELEMENT: int
diff --git a/pages/docs/manual/v9.0.0/api/js/typed-array_int-16-array.mdx b/pages/docs/manual/v9.0.0/api/js/typed-array_int-16-array.mdx
index f49f8162a..ba9bb68b2 100644
--- a/pages/docs/manual/v9.0.0/api/js/typed-array_int-16-array.mdx
+++ b/pages/docs/manual/v9.0.0/api/js/typed-array_int-16-array.mdx
@@ -314,7 +314,7 @@ let some: ((. elt) => bool, t) => bool
let somei: ((. elt, int) => bool, t) => bool
```
-## _BYTES_PER_ELEMENT
+## \_BYTES_PER_ELEMENT
```res sig
let _BYTES_PER_ELEMENT: int
diff --git a/pages/docs/manual/v9.0.0/api/js/typed-array_int-32-array.mdx b/pages/docs/manual/v9.0.0/api/js/typed-array_int-32-array.mdx
index 7147de119..181940b34 100644
--- a/pages/docs/manual/v9.0.0/api/js/typed-array_int-32-array.mdx
+++ b/pages/docs/manual/v9.0.0/api/js/typed-array_int-32-array.mdx
@@ -314,7 +314,7 @@ let some: ((. elt) => bool, t) => bool
let somei: ((. elt, int) => bool, t) => bool
```
-## _BYTES_PER_ELEMENT
+## \_BYTES_PER_ELEMENT
```res sig
let _BYTES_PER_ELEMENT: int
diff --git a/pages/docs/manual/v9.0.0/api/js/typed-array_int-8-array.mdx b/pages/docs/manual/v9.0.0/api/js/typed-array_int-8-array.mdx
index 5336025ae..fce0667de 100644
--- a/pages/docs/manual/v9.0.0/api/js/typed-array_int-8-array.mdx
+++ b/pages/docs/manual/v9.0.0/api/js/typed-array_int-8-array.mdx
@@ -314,7 +314,7 @@ let some: ((. elt) => bool, t) => bool
let somei: ((. elt, int) => bool, t) => bool
```
-## _BYTES_PER_ELEMENT
+## \_BYTES_PER_ELEMENT
```res sig
let _BYTES_PER_ELEMENT: int
diff --git a/pages/docs/manual/v9.0.0/api/js/typed-array_uint-16-array.mdx b/pages/docs/manual/v9.0.0/api/js/typed-array_uint-16-array.mdx
index 6ac15af3c..4628398b5 100644
--- a/pages/docs/manual/v9.0.0/api/js/typed-array_uint-16-array.mdx
+++ b/pages/docs/manual/v9.0.0/api/js/typed-array_uint-16-array.mdx
@@ -314,7 +314,7 @@ let some: ((. elt) => bool, t) => bool
let somei: ((. elt, int) => bool, t) => bool
```
-## _BYTES_PER_ELEMENT
+## \_BYTES_PER_ELEMENT
```res sig
let _BYTES_PER_ELEMENT: int
diff --git a/pages/docs/manual/v9.0.0/api/js/typed-array_uint-32-array.mdx b/pages/docs/manual/v9.0.0/api/js/typed-array_uint-32-array.mdx
index fbd25e7fa..667ed5134 100644
--- a/pages/docs/manual/v9.0.0/api/js/typed-array_uint-32-array.mdx
+++ b/pages/docs/manual/v9.0.0/api/js/typed-array_uint-32-array.mdx
@@ -314,7 +314,7 @@ let some: ((. elt) => bool, t) => bool
let somei: ((. elt, int) => bool, t) => bool
```
-## _BYTES_PER_ELEMENT
+## \_BYTES_PER_ELEMENT
```res sig
let _BYTES_PER_ELEMENT: int
diff --git a/pages/docs/manual/v9.0.0/api/js/typed-array_uint-8-array.mdx b/pages/docs/manual/v9.0.0/api/js/typed-array_uint-8-array.mdx
index 75bf7449a..1cc7887ab 100644
--- a/pages/docs/manual/v9.0.0/api/js/typed-array_uint-8-array.mdx
+++ b/pages/docs/manual/v9.0.0/api/js/typed-array_uint-8-array.mdx
@@ -314,7 +314,7 @@ let some: ((. elt) => bool, t) => bool
let somei: ((. elt, int) => bool, t) => bool
```
-## _BYTES_PER_ELEMENT
+## \_BYTES_PER_ELEMENT
```res sig
let _BYTES_PER_ELEMENT: int
diff --git a/pages/docs/manual/v9.0.0/api/js/typed-array_uint-8-clamped-array.mdx b/pages/docs/manual/v9.0.0/api/js/typed-array_uint-8-clamped-array.mdx
index 57f4a5288..e5372dfbe 100644
--- a/pages/docs/manual/v9.0.0/api/js/typed-array_uint-8-clamped-array.mdx
+++ b/pages/docs/manual/v9.0.0/api/js/typed-array_uint-8-clamped-array.mdx
@@ -314,7 +314,7 @@ let some: ((. elt) => bool, t) => bool
let somei: ((. elt, int) => bool, t) => bool
```
-## _BYTES_PER_ELEMENT
+## \_BYTES_PER_ELEMENT
```res sig
let _BYTES_PER_ELEMENT: int
diff --git a/pages/docs/manual/v9.0.0/array-and-list.mdx b/pages/docs/manual/v9.0.0/array-and-list.mdx
index 143b60479..e76e501f1 100644
--- a/pages/docs/manual/v9.0.0/array-and-list.mdx
+++ b/pages/docs/manual/v9.0.0/array-and-list.mdx
@@ -15,6 +15,7 @@ Arrays are our main ordered data structure. They work the same way as JavaScript
```res example
let myArray = ["hello", "world", "how are you"]
```
+
```js
var myArray = ["hello", "world", "how are you"];
```
@@ -40,6 +41,7 @@ myArray[0] = "hey" // now ["hey", "world", "how are you"]
let pushedValue = Js.Array2.push(myArray, "bye")
```
+
```js
var myArray = ["hello", "world", "how are you"];
@@ -66,6 +68,7 @@ ReScript provides a singly linked list too. Lists are:
```res example
let myList = list{1, 2, 3}
```
+
```js
var myList = {
hd: 1,
@@ -73,9 +76,9 @@ var myList = {
hd: 2,
tl: {
hd: 3,
- tl: 0
- }
- }
+ tl: 0,
+ },
+ },
};
```
@@ -101,6 +104,7 @@ Use the spread syntax:
let myList = list{1, 2, 3}
let anotherList = list{0, ...myList}
```
+
```js
var myList = {
hd: 1,
@@ -108,14 +112,14 @@ var myList = {
hd: 2,
tl: {
hd: 3,
- tl: 0
- }
- }
+ tl: 0,
+ },
+ },
};
var anotherList = {
hd: 0,
- tl: myList
+ tl: myList,
};
```
@@ -140,6 +144,7 @@ let message =
| list{a, ...rest} => "The head of the list is the string " ++ Js.Int.toString(a)
}
```
+
```js
var message = myList
? "The head of the list is the string " + (1).toString()
diff --git a/pages/docs/manual/v9.0.0/attribute.mdx b/pages/docs/manual/v9.0.0/attribute.mdx
index 07024c568..b125a3f8f 100644
--- a/pages/docs/manual/v9.0.0/attribute.mdx
+++ b/pages/docs/manual/v9.0.0/attribute.mdx
@@ -16,6 +16,7 @@ let mode = "dev"
let mode2 = mode
```
+
```js
var mode2 = "dev";
```
@@ -52,9 +53,11 @@ type student = {
let customDouble = foo => foo * 2
@deprecated("Use SomeOther.customTriple instead")
-let customTriple = foo => foo * 3
+let customTriple = foo => foo * 3
```
+
```js
+
```
@@ -75,8 +78,9 @@ There's a second category of attributes, called "extension points" (a remnant te
```res
%raw("var a = 1")
```
+
```js
-var a = 1
+var a = 1;
```
diff --git a/pages/docs/manual/v9.0.0/bind-to-global-js-values.mdx b/pages/docs/manual/v9.0.0/bind-to-global-js-values.mdx
index 65038f1bf..373e8cf12 100644
--- a/pages/docs/manual/v9.0.0/bind-to-global-js-values.mdx
+++ b/pages/docs/manual/v9.0.0/bind-to-global-js-values.mdx
@@ -16,6 +16,7 @@ Some JS values, like `setTimeout`, live in the global scope. You can bind to the
@val external setTimeout: (unit => unit, int) => float = "setTimeout"
@val external clearTimeout: float => unit = "clearTimeout"
```
+
```js
// Empty output
```
@@ -46,6 +47,7 @@ type timerId
let id = setTimeout(() => Js.log("hello"), 100)
clearTimeout(id)
```
+
```js
var id = setTimeout(function (param) {
console.log("hello");
@@ -70,6 +72,7 @@ If you want to bind to a value inside a global module, e.g. `Math.random`, attac
@scope("Math") @val external random: unit => float = "random"
let someNumber = random()
```
+
```js
var someNumber = Math.random();
```
@@ -84,6 +87,7 @@ you can bind to an arbitrarily deep object by passing a tuple to `scope`:
@val @scope(("window", "location", "ancestorOrigins"))
external length: int = "length"
```
+
```js
// Empty output
```
@@ -106,6 +110,7 @@ switch %external(__DEV__) {
| None => Js.log("production mode")
}
```
+
```js
var match = typeof __DEV__ === "undefined" ? undefined : __DEV__;
@@ -130,8 +135,9 @@ switch %external(__filename) {
| None => Js.log("non-node environment")
};
```
+
```js
-var match = typeof (__filename) === "undefined" ? undefined : (__filename);
+var match = typeof __filename === "undefined" ? undefined : __filename;
if (match !== undefined) {
console.log(match);
diff --git a/pages/docs/manual/v9.0.0/bind-to-js-function.mdx b/pages/docs/manual/v9.0.0/bind-to-js-function.mdx
index 303781bdf..c8e5cfd9b 100644
--- a/pages/docs/manual/v9.0.0/bind-to-js-function.mdx
+++ b/pages/docs/manual/v9.0.0/bind-to-js-function.mdx
@@ -15,6 +15,7 @@ Binding a JS function is like binding any other value:
@module("path") external dirname: string => string = "dirname"
let root = dirname("/User/github") // returns "User"
```
+
```js
var Path = require("path");
var root = Path.dirname("/User/github");
@@ -32,10 +33,10 @@ ReScript has [labeled arguments](function.md#labeled-arguments) (that can also b
// MyGame.js
function draw(x, y, border) {
- // suppose `border` is optional and defaults to false
+ // suppose `border` is optional and defaults to false
}
-draw(10, 20)
-draw(20, 20, true)
+draw(10, 20);
+draw(20, 20, true);
```
It'd be nice if on ReScript's side, we can bind & call `draw` while labeling things a bit:
@@ -49,6 +50,7 @@ external draw: (~x: int, ~y: int, ~border: bool=?, unit) => unit = "draw"
draw(~x=10, ~y=20, ~border=true, ())
draw(~x=10, ~y=20, ())
```
+
```js
var MyGame = require("MyGame");
@@ -73,6 +75,7 @@ external draw: (~x: int, ~y: int, ~border: bool=?, unit) => unit = "draw"
draw(~x=10, ~y=20, ())
draw(~y=20, ~x=10, ())
```
+
```js
var MyGame = require("MyGame");
@@ -95,6 +98,7 @@ type document // abstract type for a document object
let el = getElementById(doc, "myId")
```
+
```js
var el = document.getElementById("myId");
```
@@ -119,6 +123,7 @@ external join: array => string = "join"
let v = join(["a", "b"])
```
+
```js
var Path = require("path");
var v = Path.join("a", "b");
@@ -143,6 +148,7 @@ If you can exhaustively enumerate the many forms an overloaded JS function can t
@module("MyGame") external drawDog: (~giveName: string) => unit = "draw"
@module("MyGame") external draw: (string, ~useRandomAnimal: bool) => unit = "draw"
```
+
```js
// Empty output
```
@@ -183,6 +189,7 @@ external padLeft: (
padLeft("Hello World", #Int(4))
padLeft("Hello World", #Str("Message from ReScript: "))
```
+
```js
padLeft("Hello World", 4);
padLeft("Hello World", "Message from ReScript: ");
@@ -210,6 +217,7 @@ external readFileSync: (
readFileSync(~name="xx.txt", #useAscii)
```
+
```js
var Fs = require("fs");
Fs.readFileSync("xx.txt", "ascii");
@@ -237,6 +245,7 @@ external testIntType: (
=> int = "testIntType"
testIntType(#inBinary)
```
+
```js
testIntType(21);
```
@@ -269,11 +278,12 @@ let register = rl =>
->on(#close(event => ()))
->on(#line(line => Js.log(line)));
```
+
```js
function register(rl) {
return rl
- .on("close", function($$event) {})
- .on("line", function(line) {
+ .on("close", function ($$event) {})
+ .on("line", function (line) {
console.log(line);
});
}
@@ -300,6 +310,7 @@ processOnExit(exitCode =>
Js.log("error code: " ++ Js.Int.toString(exitCode))
);
```
+
```js
process.on("exit", function (exitCode) {
console.log("error code: " + exitCode.toString());
@@ -308,7 +319,7 @@ process.on("exit", function (exitCode) {
-The `@as("exit")` and the placeholder `_` argument together indicates that you want the first argument to compile to the string `"exit"`. You can also use any JSON literal with `as`: `` @as(json`true`) ``, `` @as(json`{"name": "John"}`) ``, etc.
+The `@as("exit")` and the placeholder `_` argument together indicates that you want the first argument to compile to the string `"exit"`. You can also use any JSON literal with `as`: ``@as(json`true`)``, ``@as(json`{"name": "John"}`)``, etc.
## Curry & Uncurry
@@ -352,6 +363,7 @@ type timerId
let id = setTimeout((.) => Js.log("hello"), 1000)
```
+
```js
var id = setTimeout(function () {
console.log("hello");
@@ -378,6 +390,7 @@ Then try `@uncurry`:
@send external map: (array<'a>, @uncurry ('a => 'b)) => array<'b> = "map"
map([1, 2, 3], x => x + 1)
```
+
```js
// Empty output
```
@@ -391,9 +404,9 @@ In general, `uncurry` is recommended; the compiler will do lots of optimizations
Many JS libraries have callbacks which rely on this (the source), for example:
```js
-x.onload = function(v) {
- console.log(this.response + v)
-}
+x.onload = function (v) {
+ console.log(this.response + v);
+};
```
Here, `this` would point to `x` (actually, it depends on how `onload` is called, but we digress). It's not correct to declare `x.onload` of type `(. unit) -> unit`. Instead, we introduced a special attribute, `this`, which allows us to type `x` as so:
@@ -407,6 +420,7 @@ type x
@get external resp: x => int = "response"
setOnload(x, @this ((o, v) => Js.log(resp(o) + v)))
```
+
```js
x.onload = function (v) {
var o = this;
@@ -439,6 +453,7 @@ let test = dom => {
}
}
```
+
```js
function test(dom) {
var elem = dom.getElementById("haha");
@@ -449,7 +464,6 @@ function test(dom) {
return 2;
}
}
-
```
diff --git a/pages/docs/manual/v9.0.0/bind-to-js-object.mdx b/pages/docs/manual/v9.0.0/bind-to-js-object.mdx
index 5b46f0c5c..4acba9bba 100644
--- a/pages/docs/manual/v9.0.0/bind-to-js-object.mdx
+++ b/pages/docs/manual/v9.0.0/bind-to-js-object.mdx
@@ -36,6 +36,7 @@ type person = {
let johnName = john.name
```
+
```js
var MySchool = require("MySchool");
@@ -63,6 +64,7 @@ type person = {
let johnName = john["name"]
```
+
```js
var MySchool = require("MySchool");
@@ -82,7 +84,9 @@ type textarea
@set external setName: (textarea, string) => unit = "name"
@get external getName: textarea => string = "name"
```
+
```js
+
```
@@ -101,6 +105,7 @@ let i32arr = create(3)
i32arr->set(0, 42)
Js.log(i32arr->get(0))
```
+
```js
var i32arr = new Int32Array(3);
i32arr[0] = 42;
@@ -130,6 +135,7 @@ type t
let date = createDate()
```
+
```js
var date = new Date();
```
@@ -145,6 +151,7 @@ type t
@new @module external book: unit => t = "Book"
let myBook = book()
```
+
```js
var Book = require("Book");
var myBook = new Book();
diff --git a/pages/docs/manual/v9.0.0/build-configuration-schema.mdx b/pages/docs/manual/v9.0.0/build-configuration-schema.mdx
index 9dfe69b06..918ee6b9f 100644
--- a/pages/docs/manual/v9.0.0/build-configuration-schema.mdx
+++ b/pages/docs/manual/v9.0.0/build-configuration-schema.mdx
@@ -15,7 +15,7 @@ export const Docson = dynamic(
{
ssr: false,
loading: () => Loading...
,
- }
+ },
);
export default function BuildConfigurationSchemaPage() {
diff --git a/pages/docs/manual/v9.0.0/build-external-stdlib.mdx b/pages/docs/manual/v9.0.0/build-external-stdlib.mdx
index 835080157..62bdc8a29 100644
--- a/pages/docs/manual/v9.0.0/build-external-stdlib.mdx
+++ b/pages/docs/manual/v9.0.0/build-external-stdlib.mdx
@@ -10,6 +10,7 @@ canonical: "/docs/manual/latest/build-external-stdlib"
**Since 9.0**
Your ReScript project depends on the `bs-platform` (soon `rescript`) package as a [`devDependency`](https://docs.npmjs.com/specifying-dependencies-and-devdependencies-in-a-package-json-file), which includes our compiler, build system and runtime like `Belt`. However, you had to move it to `dependency` in `package.json` if you publish your code:
+
- To Docker or other low-storage deployment devices.
- For pure JS/TS consumers who probably won't install `bs-platform` in their own project.
@@ -33,7 +34,7 @@ Then add this to `bsconfig.json`:
```json
{
// ...
- "external-stdlib" : "@rescript/std"
+ "external-stdlib": "@rescript/std"
}
```
diff --git a/pages/docs/manual/v9.0.0/build-overview.mdx b/pages/docs/manual/v9.0.0/build-overview.mdx
index 77f0d674a..5f0d681aa 100644
--- a/pages/docs/manual/v9.0.0/build-overview.mdx
+++ b/pages/docs/manual/v9.0.0/build-overview.mdx
@@ -11,7 +11,7 @@ ReScript comes with a build system, bsb, that's meant to be fast, lean and used
The build description file is called `bsconfig.json`. Every ReScript project needs one.
-## Build Project
+## Build Project
Each build will create build artifacts from your project's source files.
@@ -29,7 +29,6 @@ Add `-w` to keep the built-in watcher running. Any new file change will be picke
**To build only your project's files (without dependencies)**, run:
-
```sh
bsb
```
diff --git a/pages/docs/manual/v9.0.0/build-performance.mdx b/pages/docs/manual/v9.0.0/build-performance.mdx
index 3a5db7063..d144140a9 100644
--- a/pages/docs/manual/v9.0.0/build-performance.mdx
+++ b/pages/docs/manual/v9.0.0/build-performance.mdx
@@ -21,7 +21,11 @@ Run the above command at your ReScript project's root; it'll spit out a JSON fil
import Image from "src/components/Image";
-
+
## Under the Hood
diff --git a/pages/docs/manual/v9.0.0/build-pinned-dependencies.mdx b/pages/docs/manual/v9.0.0/build-pinned-dependencies.mdx
index 941f0e083..1c149c99a 100644
--- a/pages/docs/manual/v9.0.0/build-pinned-dependencies.mdx
+++ b/pages/docs/manual/v9.0.0/build-pinned-dependencies.mdx
@@ -13,7 +13,6 @@ Usually we'd recommend to use ReScript in a single-codebase style by using one `
There are scenarios where you still want to connect and build multiple independent ReScript packages for one main project though (`yarn workspaces`-like "monorepos"). This is where `pinned-dependencies` come into play.
-
## Package Types
Before we go into detail, let's first explain all the different package types recognized by the build system:
@@ -29,6 +28,7 @@ Whenever a package is being built (`bsb -make-world`), the build system will bui
The build system respects the following rules for each package type:
**Toplevel**
+
- Warnings reported
- Warn-error respected
- Builds dev dependencies
@@ -37,6 +37,7 @@ The build system respects the following rules for each package type:
- Package-specs like ES6/CommonJS overrides all its dependencies
**Pinned dependencies**
+
- Warnings reported
- Warn-error respected
- Ignores pinned dependencies
@@ -44,6 +45,7 @@ The build system respects the following rules for each package type:
- Runs custom rules
**Normal dependencies**
+
- Warnings, warn-error ignored
- Ignores dev directories
- Ignores pinned dependencies
@@ -78,16 +80,11 @@ Our `package.json` file within our codebase root would look like this:
"name": "myproject",
"private": true,
"workspaces": {
- "packages": [
- "app",
- "common",
- "myplugin"
- ]
+ "packages": ["app", "common", "myplugin"]
}
}
```
-
Our `app` folder would be our toplevel package, consuming our `common` and `myplugin` packages as `pinned-dependencies`. The configuration for `app/bsconfig.json` looks like this:
```json
@@ -95,15 +92,12 @@ Our `app` folder would be our toplevel package, consuming our `common` and `mypl
"name": "app",
"version": "1.0.0",
"sources": {
- "dir" : "src",
- "subdirs" : true
+ "dir": "src",
+ "subdirs": true
},
/* ... */
- "bs-dependencies": [
- "common",
- "myplugin"
- ],
- "pinned-dependencies": ["common", "myplugin"],
+ "bs-dependencies": ["common", "myplugin"],
+ "pinned-dependencies": ["common", "myplugin"]
/* ... */
}
```
@@ -111,4 +105,3 @@ Our `app` folder would be our toplevel package, consuming our `common` and `mypl
Now, whenever we are running `npx bsb -make-world` within our `app` package, the compiler would always rebuild any changes within its pinned dependencies as well.
**Important:** ReScript will not rebuild any `pinned-dependencies` in watch mode! This is due to the complexity of file watching, so you'd need to set up your own file-watcher process that runs `bsb -make-world` on specific file changes. E.g. you could use [`watchman-make`](https://facebook.github.io/watchman/docs/watchman-make.html) to automatically run the build task when a file in `common` or `myplugin` has been changed.
-
diff --git a/pages/docs/manual/v9.0.0/control-flow.mdx b/pages/docs/manual/v9.0.0/control-flow.mdx
index a7d391534..0abb918c7 100644
--- a/pages/docs/manual/v9.0.0/control-flow.mdx
+++ b/pages/docs/manual/v9.0.0/control-flow.mdx
@@ -23,6 +23,7 @@ let message = if isMorning {
"Hello!"
}
```
+
```js
var message = isMorning ? "Good morning!" : "Hello!";
```
@@ -38,6 +39,7 @@ if showMenu {
displayMenu()
}
```
+
```js
if (showMenu) {
displayMenu();
@@ -57,9 +59,10 @@ if showMenu {
()
}
```
+
```js
if (showMenu) {
- displayMenu()
+ displayMenu();
}
```
@@ -82,6 +85,7 @@ We also have ternary sugar, but **we encourage you to prefer if-else when possib
```res
let message = isMorning ? "Good morning!" : "Hello!"
```
+
```js
var message = isMorning ? "Good morning!" : "Hello!";
```
@@ -101,8 +105,9 @@ for i in startValueInclusive to endValueInclusive {
Js.log(i)
}
```
+
```js
-for(var i = startValueInclusive; i <= endValueInclusive; ++i){
+for (var i = startValueInclusive; i <= endValueInclusive; ++i) {
console.log(i);
}
```
@@ -117,8 +122,9 @@ for x in 1 to 3 {
Js.log(x)
}
```
+
```js
-for(var x = 1; x <= 3; ++x){
+for (var x = 1; x <= 3; ++x) {
console.log(x);
}
```
@@ -134,8 +140,9 @@ for i in startValueInclusive downto endValueInclusive {
Js.log(i)
}
```
+
```js
-for(var i = startValueInclusive; i >= endValueInclusive; --i){
+for (var i = startValueInclusive; i >= endValueInclusive; --i) {
console.log(i);
}
```
@@ -150,8 +157,9 @@ for x in 3 downto 1 {
Js.log(x)
}
```
+
```js
-for(var x = 3; x >= 1; --x){
+for (var x = 3; x >= 1; --x) {
console.log(x);
}
```
@@ -169,6 +177,7 @@ while testCondition {
// body here
}
```
+
```js
while (testCondition) {
// body here
@@ -194,18 +203,19 @@ while !break.contents {
}
}
```
+
```js
var $$break = {
- contents: false
+ contents: false,
};
-while(!$$break.contents) {
+while (!$$break.contents) {
if (Math.random() > 0.3) {
$$break.contents = true;
} else {
console.log("Still running");
}
-};
+}
```
diff --git a/pages/docs/manual/v9.0.0/converting-from-js.mdx b/pages/docs/manual/v9.0.0/converting-from-js.mdx
index 4d72fd941..e4c01b6ef 100644
--- a/pages/docs/manual/v9.0.0/converting-from-js.mdx
+++ b/pages/docs/manual/v9.0.0/converting-from-js.mdx
@@ -7,6 +7,7 @@ canonical: "/docs/manual/latest/converting-from-js"
# Converting from JS
ReScript offers a unique project conversion methodology which:
+
- Ensures minimal disruption to your teammates (very important!).
- Remove the typical friction of verifying conversion's correctness and performance guarantees.
- Doesn't force you to search for pre-made binding libraries made by others. **ReScript doesn't need the equivalent of TypeScript's `DefinitelyTyped`**.
@@ -22,7 +23,7 @@ Run `npm install --save-dev bs-platform` on your project, then imitate our [New
Let's work on converting a file called `src/main.js`.
```js
-const school = require('school');
+const school = require("school");
const defaultId = 10;
@@ -54,11 +55,12 @@ function queryResult(usePayload, payload) {
}
`)
```
+
```js
// Generated by ReScript, PLEASE EDIT WITH CARE
-'use strict';
+"use strict";
-const school = require('school');
+const school = require("school");
const defaultId = 10;
@@ -109,6 +111,7 @@ function queryResult(usePayload, payload) {
}
`)
```
+
```js
// Generated by ReScript, PLEASE EDIT WITH CARE
'use strict';
@@ -150,7 +153,9 @@ let queryResult = (usePayload, payload) => {
}
}
```
+
```js
+
```
@@ -180,7 +185,9 @@ let queryResult = (usePayload, payload) => {
}
}
```
+
```js
+
```
@@ -202,9 +209,10 @@ let queryResult = (usePayload, payload) => {
}
}
```
+
```js
// Generated by ReScript, PLEASE EDIT WITH CARE
-'use strict';
+"use strict";
var School = require("school");
@@ -257,9 +265,10 @@ let queryResult = (usePayload, payload) => {
}
}
```
+
```js
// Generated by ReScript, PLEASE EDIT WITH CARE
-'use strict';
+"use strict";
var School = require("school");
@@ -281,6 +290,7 @@ exports.queryResult = queryResult;
We've:
+
- introduced an opaque types for `school` and `student` to prevent misusages their values
- typed the payload as a record with only the `student` field
- typed `getStudentById` as the sole method of `student`
diff --git a/pages/docs/manual/v9.0.0/editor-plugins.mdx b/pages/docs/manual/v9.0.0/editor-plugins.mdx
index 90e82cc47..e564b81e7 100644
--- a/pages/docs/manual/v9.0.0/editor-plugins.mdx
+++ b/pages/docs/manual/v9.0.0/editor-plugins.mdx
@@ -9,7 +9,8 @@ canonical: "/docs/manual/latest/editor-plugins"
- [VSCode](https://marketplace.visualstudio.com/items?itemName=chenglou92.rescript-vscode)
- [Sublime Text](https://github.com/reasonml-editor/sublime-reason)
- [Vim/Neovim](https://github.com/rescript-lang/vim-rescript)
--
+-
+
## Community Supported
We don't officially support these; use them at your own risk!
diff --git a/pages/docs/manual/v9.0.0/embed-raw-javascript.mdx b/pages/docs/manual/v9.0.0/embed-raw-javascript.mdx
index 4d99e9b5a..f89d61f2f 100644
--- a/pages/docs/manual/v9.0.0/embed-raw-javascript.mdx
+++ b/pages/docs/manual/v9.0.0/embed-raw-javascript.mdx
@@ -21,11 +21,12 @@ function greet(m) {
}
`)
```
+
```js
// look ma, regular JavaScript!
var message = "hello";
function greet(m) {
- console.log(m)
+ console.log(m);
}
```
@@ -49,10 +50,11 @@ let add = %raw(`
Js.log(add(1, 2))
```
+
```js
-var add = function(a, b) {
+var add = function (a, b) {
console.log("hello from raw JavaScript!");
- return a + b
+ return a + b;
};
console.log(add(1, 2));
@@ -61,6 +63,7 @@ console.log(add(1, 2));
The above code:
+
- declared a ReScript variable `add`,
- with the raw JavaScript value of a function declaration,
- then called that function in ReScript.
@@ -79,10 +82,11 @@ let f = (x, y) => {
x + y
}
```
+
```js
function f(x, y) {
debugger;
- return x + y | 0;
+ return (x + y) | 0;
}
```
diff --git a/pages/docs/manual/v9.0.0/exception.mdx b/pages/docs/manual/v9.0.0/exception.mdx
index e27305991..b25d3740d 100644
--- a/pages/docs/manual/v9.0.0/exception.mdx
+++ b/pages/docs/manual/v9.0.0/exception.mdx
@@ -28,6 +28,7 @@ let result =
| Not_found => 0 // Default value if getItem throws
}
```
+
```js
function getItem(items) {
if (callSomeFunctionThatThrows()) {
@@ -35,7 +36,7 @@ function getItem(items) {
}
throw {
RE_EXN_ID: "Not_found",
- Error: new Error()
+ Error: new Error(),
};
}
@@ -67,18 +68,18 @@ switch List.find(i => i === theItem, myItems) {
| exception Not_found => Js.log("No such item found!")
}
```
+
```js
var exit = 0;
var item;
try {
- item = List.find(function(i) {
+ item = List.find(function (i) {
return i === theItem;
}, myItems);
exit = 1;
-}
-catch (raw_exn){
+} catch (raw_exn) {
var exn = Caml_js_exceptions.internalToOCamlException(raw_exn);
if (exn.RE_EXN_ID === "Not_found") {
console.log("No such item found!");
@@ -103,6 +104,7 @@ exception InputClosed(string)
// later on
raise(InputClosed("The stream has closed!"))
```
+
```js
var Caml_exceptions = require("./stdlib/caml_exceptions.js");
@@ -111,7 +113,7 @@ var InputClosed = Caml_exceptions.create("MyFile.InputClosed");
throw {
RE_EXN_ID: InputClosed,
_1: "The stream has closed!",
- Error: new Error()
+ Error: new Error(),
};
```
@@ -134,6 +136,7 @@ try {
}
}
```
+
```js
var Js_exn = require("./stdlib/js_exn.js");
var Caml_js_exceptions = require("./stdlib/caml_js_exceptions.js");
@@ -168,6 +171,7 @@ let myTest = () => {
Js.Exn.raiseError("Hello!")
}
```
+
```js
var Js_exn = require("./stdlib/js_exn.js");
@@ -183,9 +187,9 @@ Then you can catch it from the JS side:
```js
// after importing `myTest`...
try {
- myTest()
+ myTest();
} catch (e) {
- console.log(e.message) // "Hello!"
+ console.log(e.message); // "Hello!"
}
```
@@ -202,6 +206,7 @@ let myTest = () => {
raise(BadArgument({myMessage: "Oops!"}))
}
```
+
```js
var Caml_exceptions = require("./stdlib/caml_exceptions.js");
@@ -211,7 +216,7 @@ function myTest() {
throw {
RE_EXN_ID: BadArgument,
myMessage: "Oops!",
- Error: new Error()
+ Error: new Error(),
};
}
```
@@ -223,10 +228,10 @@ Then, in your JS:
```js
// after importing `myTest`...
try {
- myTest()
+ myTest();
} catch (e) {
- console.log(e.myMessage) // "Oops!"
- console.log(e.Error.stack) // the stack trace
+ console.log(e.myMessage); // "Oops!"
+ console.log(e.Error.stack); // the stack trace
}
```
@@ -251,6 +256,7 @@ try {
| Js.Exn.Error(obj) => ... // catch the JS exception
}
```
+
```js
var Js_exn = require("./stdlib/js_exn.js");
var Caml_js_exceptions = require("./stdlib/caml_js_exceptions.js");
diff --git a/pages/docs/manual/v9.0.0/external.mdx b/pages/docs/manual/v9.0.0/external.mdx
index 95cddbe3d..2a63fac3c 100644
--- a/pages/docs/manual/v9.0.0/external.mdx
+++ b/pages/docs/manual/v9.0.0/external.mdx
@@ -9,6 +9,7 @@ canonical: "/docs/manual/latest/external"
`external` is the primary ReScript feature for bringing in and using JavaScript values.
`external` is like a let binding, but:
+
- The right side of `=` isn't a value; it's the name of the JS value you're referring to.
- The type for the binding is mandatory, since we need to know what the type of that JS value is.
- Can only exist at the top level of a file or module.
@@ -18,6 +19,7 @@ canonical: "/docs/manual/latest/external"
```res example
@val external setTimeout: (unit => unit, int) => float = "setTimeout"
```
+
```js
// Empty output
```
@@ -56,8 +58,9 @@ let loc = document["location"]
// set a property
document["location"]["href"] = "rescript-lang.org"
```
+
```js
-document.addEventListener("mouseup", function(_event) {
+document.addEventListener("mouseup", function (_event) {
console.log("clicked!");
});
diff --git a/pages/docs/manual/v9.0.0/faq.mdx b/pages/docs/manual/v9.0.0/faq.mdx
index 18cb46b88..7913c5de7 100644
--- a/pages/docs/manual/v9.0.0/faq.mdx
+++ b/pages/docs/manual/v9.0.0/faq.mdx
@@ -10,23 +10,20 @@ canonical: "/docs/manual/latest/faq"
We aim to provide the best typed language experience for the JavaScript platform.
-
**What’s the relationship with BuckleScript?**
BuckleScript is ReScript's old branding, with a sharper focus on proper JS support and familiarity which we previously couldn't achieve to the degree we wanted, due to us needing to cater to various different crowds.
**What’s ReScript's relationship with OCaml?**
-We reuse and adjust the excellent type system and lots of other high quality components from OCaml for JS experience.
-Additionally, ReScript provides its own syntax, build system, IDE, backend, JS interop, extra language features, etc.
+We reuse and adjust the excellent type system and lots of other high quality components from OCaml for JS experience.
+Additionally, ReScript provides its own syntax, build system, IDE, backend, JS interop, extra language features, etc.
-The ReScript toolchain is developed using OCaml, however, the version of ReScript is decoupled against the version of OCaml,
+The ReScript toolchain is developed using OCaml, however, the version of ReScript is decoupled against the version of OCaml,
ReScript compiler should build against any reasonable modern version of OCaml compiler.
For the majority of ReScript users, they don't need to learn OCaml or use OCaml toolchain to be productive in ReScript.
-
-
**What’s the relationship with Reason?**
See [here](/blog/bucklescript-is-rebranding). Reason is a syntax layer for OCaml that BuckleScript also adopted. The current ReScript compiler also supports the old Reason syntax v3.6 for backward compatibility. We will support it for a long time to make sure existing users do not get breaking changes.
diff --git a/pages/docs/manual/v9.0.0/function.mdx b/pages/docs/manual/v9.0.0/function.mdx
index 79af09f5d..9618fd6a7 100644
--- a/pages/docs/manual/v9.0.0/function.mdx
+++ b/pages/docs/manual/v9.0.0/function.mdx
@@ -15,6 +15,7 @@ ReScript functions are declared with an arrow and return an expression, just lik
```res prelude
let greet = (name) => "Hello " ++ name
```
+
```js
function greet(name) {
return "Hello " + name;
@@ -30,6 +31,7 @@ This declares a function and assigns to it the name `greet`, which you can call
```res example
greet("world!") // "Hello world!"
```
+
```js
greet("world!");
```
@@ -44,9 +46,10 @@ Multi-arguments functions have arguments separated by comma:
let add = (x, y, z) => x + y + z
add(1, 2, 3) // 6
```
+
```js
function add(x, y, z) {
- return (x + y | 0) + z | 0;
+ return (((x + y) | 0) + z) | 0;
}
```
@@ -62,6 +65,7 @@ let greetMore = (name) => {
part1 ++ " " ++ name
}
```
+
```js
function greetMore(name) {
return "Hello " + name;
@@ -85,6 +89,7 @@ let addCoordinates = (x, y) => {
// ...
addCoordinates(5, 6) // which is x, which is y?
```
+
```js
function addCoordinates(x, y) {
// use x and y here
@@ -106,6 +111,7 @@ let addCoordinates = (~x, ~y) => {
// ...
addCoordinates(~x=5, ~y=6)
```
+
```js
function addCoordinates(x, y) {
// use x and y here
@@ -123,6 +129,7 @@ You can provide the arguments in **any order**:
```res
addCoordinates(~y=6, ~x=5)
```
+
```js
addCoordinates(5, 6);
```
@@ -142,6 +149,7 @@ let drawCircle = (~radius as r, ~color as c) => {
drawCircle(~radius=10, ~color="red")
```
+
```js
function drawCircle(r, c) {
setColor(c);
@@ -164,6 +172,7 @@ let drawCircle = (~radius as r: int, ~color as c: string) => {
// code here
}
```
+
```js
function drawCircle(r, c) {
// code here
@@ -188,6 +197,7 @@ let drawCircle = (~color, ~radius=?, ()) => {
}
}
```
+
```js
var Caml_option = require("./stdlib/caml_option.js");
@@ -227,6 +237,7 @@ let drawCircle: (~color: color, ~radius: int=?, unit) => unit =
}
}
```
+
```js
function drawCircle(color, radius, param) {
setColor(color);
@@ -259,12 +270,14 @@ let result =
| Some(r) => drawCircle(~color, ~radius=r, ())
}
```
+
```js
var r = payloadRadius;
-var result = r !== undefined
- ? drawCircle(color, Caml_option.valFromOption(r), undefined)
- : drawCircle(color, undefined);
+var result =
+ r !== undefined
+ ? drawCircle(color, Caml_option.valFromOption(r), undefined)
+ : drawCircle(color, undefined);
```
@@ -276,6 +289,7 @@ This quickly gets tedious. We provide a shortcut:
```res
let result = drawCircle(~color, ~radius=?payloadRadius, ())
```
+
```js
var result = drawCircle(1, undefined, undefined);
```
@@ -296,6 +310,7 @@ let drawCircle = (~radius=1, ~color, ()) => {
startAt(radius, radius)
}
```
+
```js
function drawCircle(radiusOpt, color, param) {
var radius = radiusOpt !== undefined ? radiusOpt : 1;
@@ -315,12 +330,13 @@ ReScript chooses the sane default of preventing a function to be called recursiv
```res example
let rec neverTerminate = () => neverTerminate()
```
+
```js
function neverTerminate(_param) {
- while(true) {
+ while (true) {
_param = undefined;
- continue ;
- };
+ continue;
+ }
}
```
@@ -339,9 +355,10 @@ let rec listHas = (list, item) =>
| list{a, ...rest} => a === item || listHas(rest, item)
}
```
+
```js
function listHas(_list, item) {
- while(true) {
+ while (true) {
var list = _list;
if (!list) {
return false;
@@ -350,8 +367,8 @@ function listHas(_list, item) {
return true;
}
_list = list.tl;
- continue ;
- };
+ continue;
+ }
}
```
@@ -370,19 +387,20 @@ Mutually recursive functions start like a single recursive function using the
let rec callSecond = () => callFirst()
and callFirst = () => callSecond()
```
+
```js
function callSecond(_param) {
- while(true) {
+ while (true) {
_param = undefined;
- continue ;
- };
+ continue;
+ }
}
function callFirst(_param) {
- while(true) {
+ while (true) {
_param = undefined;
- continue ;
- };
+ continue;
+ }
}
```
@@ -399,9 +417,10 @@ let add = (. x, y) => x + y
add(. 1, 2)
```
+
```js
function add(x, y) {
- return x + y | 0;
+ return (x + y) | 0;
}
add(1, 2);
@@ -429,7 +448,6 @@ echo(undefined);
-
If you write down the uncurried function's type, you'll add a dot there as well.
**Note**: both the declaration site and the call site need to have the uncurry annotation. That's part of the guarantee/requirement.
diff --git a/pages/docs/manual/v9.0.0/generate-converters-accessors.mdx b/pages/docs/manual/v9.0.0/generate-converters-accessors.mdx
index a87bf7872..4502232e9 100644
--- a/pages/docs/manual/v9.0.0/generate-converters-accessors.mdx
+++ b/pages/docs/manual/v9.0.0/generate-converters-accessors.mdx
@@ -34,14 +34,14 @@ type action =
```js
function submit(param_0) {
- return /* Submit */[param_0];
+ return /* Submit */ [param_0];
}
-var click = /* Click */0;
+var click = /* Click */ 0;
-var cancel = /* Cancel */1;
+var cancel = /* Cancel */ 1;
-exports.click = click;
+exports.click = click;
exports.submit = submit;
exports.cancel = cancel;
```
@@ -51,6 +51,7 @@ exports.cancel = cancel;
Variants constructors with payloads generate functions, payload-less constructors generate plain integers (the internal representation of variants).
**Note**:
+
- The generated accessors are lower-cased.
- You can now use these helpers on the JavaScript side! But don't rely on their actual values please.
@@ -71,7 +72,6 @@ Please note that in case you just want to _pipe a payload into a constructor_, y
Use `@deriving(accessors)` on a record type to create accessors for its record field names.
-
```res
@@ -93,11 +93,11 @@ function name(param) {
var pets = [
{
- name: "bob"
+ name: "bob",
},
{
- name: "bob2"
- }
+ name: "bob2",
+ },
];
console.log(Belt_Array.map(pets, name).join("&"));
@@ -113,7 +113,6 @@ console.log(Belt_Array.map(pets, name).join("&"));
Use `@deriving(jsConverter)` on a record type to create convertion functions between records / JS object runtime values.
-
```res
@deriving(jsConverter)
type coordinates = {
@@ -336,7 +335,7 @@ let joe = person(~name="Joe", ~age=20, ~job="teacher")
var joe = {
name: "Joe",
age: 20,
- job: "teacher"
+ job: "teacher",
};
```
@@ -363,7 +362,7 @@ let d = data(~type_="message", ~ariaLabel="hello");
```js
var d = {
type: "message",
- "aria-label": "hello"
+ "aria-label": "hello",
};
```
@@ -389,7 +388,7 @@ let joe = person(~age=20, ~job="teacher", ());
```js
var joe = {
age: 20,
- job: "teacher"
+ job: "teacher",
};
```
@@ -573,7 +572,6 @@ This is very handy because you can make some of those labelled parameters option
For example, suppose you need a JavaScript object like this:
-
```js
var homeRoute = {
type: "GET",
diff --git a/pages/docs/manual/v9.0.0/import-export.mdx b/pages/docs/manual/v9.0.0/import-export.mdx
index 137646038..965a1b983 100644
--- a/pages/docs/manual/v9.0.0/import-export.mdx
+++ b/pages/docs/manual/v9.0.0/import-export.mdx
@@ -16,9 +16,10 @@ Unlike JavaScript, ReScript doesn't have or need import statements:
// Inside School.res
let studentMessage = Student.message
```
+
```js
var Student = require("./Student.bs");
-var studentMessage = Student.message
+var studentMessage = Student.message;
```
diff --git a/pages/docs/manual/v9.0.0/import-from-export-to-js.mdx b/pages/docs/manual/v9.0.0/import-from-export-to-js.mdx
index 166f7fcfb..8bbc3cfdc 100644
--- a/pages/docs/manual/v9.0.0/import-from-export-to-js.mdx
+++ b/pages/docs/manual/v9.0.0/import-from-export-to-js.mdx
@@ -34,10 +34,12 @@ Use the `module` [external](external.md):
@module("path") external dirname: string => string = "dirname"
let root = dirname("/User/github") // returns "User"
```
+
```js
var Path = require("path");
var root = Path.dirname("/User/github");
```
+
```js
import * as Path from "path";
var root = Path.dirname("/User/github");
@@ -63,10 +65,12 @@ By omitting the string argument to `module`, you bind to the whole JS module:
@module external leftPad: string => int => string = "./leftPad"
let paddedResult = leftPad("hi", 5)
```
+
```js
var LeftPad = require("./leftPad");
var paddedResult = LeftPad("hi", 5);
```
+
```js
import * as LeftPad from "./leftPad";
var paddedResult = LeftPad("hi", 5);
@@ -86,6 +90,7 @@ Use the value `"default"` on the right hand side:
@module("./student") external studentName: string = "default"
Js.log(studentName)
```
+
```js
import Student from "./student";
var studentName = Student;
@@ -110,7 +115,7 @@ export default name = "Al";
```js
// teacher.js
-import studentName from 'student.js';
+import studentName from "student.js";
```
A JavaScript default export is really just syntax sugar for a named export implicitly called `default` (now you know!). So to export a default value from ReScript, you can just do:
@@ -121,6 +126,7 @@ A JavaScript default export is really just syntax sugar for a named export impli
// ReScriptStudent.res
let default = "Bob"
```
+
```js
var $$default = "Bob";
@@ -129,13 +135,11 @@ exports.default = $$default;
// informal transpiler-compatible marker of a default export compiled from ES6
exports.__esModule = true;
```
+
```js
var $$default = "Bob";
-export {
- $$default,
- $$default as default,
-}
+export { $$default, $$default as default };
```
@@ -144,7 +148,7 @@ You can then import this default export as usual on the JS side:
```js
// teacher2.js
-import studentName from 'ReScriptStudent.js';
+import studentName from "ReScriptStudent.js";
```
If your JavaScript's ES6 default import is transpiled by Babel/Webpack/Jest into CommonJS `require`s, we've taken care of that too! See the CommonJS output tab for `__esModule`.
diff --git a/pages/docs/manual/v9.0.0/inlining-constants.mdx b/pages/docs/manual/v9.0.0/inlining-constants.mdx
index 45609df20..5673c1e93 100644
--- a/pages/docs/manual/v9.0.0/inlining-constants.mdx
+++ b/pages/docs/manual/v9.0.0/inlining-constants.mdx
@@ -9,16 +9,16 @@ canonical: "/docs/manual/latest/inlining-constants"
Sometime, in the JavaScript output, you might want a certain value to be forcefully inlined. For example:
```js
-if (process.env.mode === 'development') {
- console.log("Dev-only code here!")
+if (process.env.mode === "development") {
+ console.log("Dev-only code here!");
}
```
The reason is that your JavaScript bundler (e.g. Webpack) might turn that into:
```js
-if ('production' === 'development') {
- console.log("Dev-only code here!")
+if ("production" === "development") {
+ console.log("Dev-only code here!");
}
```
@@ -37,6 +37,7 @@ if (process["env"]["mode"] === mode) {
Js.log("Dev-only code here!")
}
```
+
```js
var mode = "development";
@@ -61,6 +62,7 @@ if (process["env"]["mode"] === mode) {
Js.log("Dev-only code here!")
}
```
+
```js
if (process.env.mode === "development") {
console.log("Dev-only code here!");
diff --git a/pages/docs/manual/v9.0.0/installation.mdx b/pages/docs/manual/v9.0.0/installation.mdx
index b219b9580..1c8d702ab 100644
--- a/pages/docs/manual/v9.0.0/installation.mdx
+++ b/pages/docs/manual/v9.0.0/installation.mdx
@@ -68,6 +68,7 @@ If you already have a JavaScript project into which you'd like to add ReScript:
Since ReScript compiles to clean readable JS files, the rest of your existing toolchain (e.g. Babel and Webpack) should just work!
Helpful guides:
+
- [Converting from JS](converting-from-js).
- [Shared Data Types](shared-data-types).
- [Import from/Export to JS](import-from-export-to-js).
diff --git a/pages/docs/manual/v9.0.0/interop-cheatsheet.mdx b/pages/docs/manual/v9.0.0/interop-cheatsheet.mdx
index a509c366a..55891053e 100644
--- a/pages/docs/manual/v9.0.0/interop-cheatsheet.mdx
+++ b/pages/docs/manual/v9.0.0/interop-cheatsheet.mdx
@@ -51,8 +51,8 @@ This is a glossary with examples. All the features are described by later pages.
- [`%debugger`](embed-raw-javascript#debugger)
- [`%external`](bind-to-global-js-values#special-global-values)
-
-
+
+
- [`%raw`](embed-raw-javascript#paste-raw-js-code)
- [`%re`](primitive-types#regular-expression)
@@ -64,9 +64,10 @@ This is a glossary with examples. All the features are described by later pages.
let add = %raw("(a, b) => a + b")
%%raw("const a = 1")
```
+
```js
-var add = ((a, b) => a + b);
-const a = 1
+var add = (a, b) => a + b;
+const a = 1;
```
@@ -78,6 +79,7 @@ const a = 1
```res example
@val external setTimeout: (unit => unit, int) => float = "setTimeout"
```
+
```js
// Empty output
```
@@ -97,6 +99,7 @@ let someNumber = random()
@val @scope(("window", "location", "ancestorOrigins"))
external length: int = "length"
```
+
```js
var someNumber = Math.random();
```
@@ -111,6 +114,7 @@ var someNumber = Math.random();
let a = Some(5) // compiles to 5
let b = None // compiles to undefined
```
+
```js
var a = 5;
var b;
@@ -129,6 +133,7 @@ let result1: Js.Nullable.t = Js.Nullable.return("hello")
let result2: Js.Nullable.t = Js.Nullable.fromOption(Some(10))
let result3: option = Js.Nullable.toOption(Js.Nullable.return(10))
```
+
```js
var Caml_option = require("./stdlib/caml_option.js");
var Js_null_undefined = require("./stdlib/js_null_undefined.js");
@@ -162,6 +167,7 @@ var result3 = Caml_option.nullable_to_opt(10);
->filter(a => mod(a, 2) == 0)
->Js.log
```
+
```js
console.log(
[1, 2, 3]
@@ -170,7 +176,7 @@ console.log(
})
.filter(function (a) {
return a % 2 === 0;
- })
+ }),
);
```
@@ -184,6 +190,7 @@ console.log(
@module("path") @variadic
external join: array => string = "join"
```
+
```js
// Empty output
```
@@ -198,6 +205,7 @@ external join: array => string = "join"
@module("Drawing") external drawCat: unit => unit = "draw"
@module("Drawing") external drawDog: (~giveName: string) => unit = "draw"
```
+
```js
// Empty output
```
@@ -219,6 +227,7 @@ external padLeft: (
padLeft("Hello World", #Int(4))
padLeft("Hello World", #Str("Message from ReScript: "))
```
+
```js
padLeft("Hello World", 4);
padLeft("Hello World", "Message from ReScript: ");
@@ -241,6 +250,7 @@ external convertToFloat: int => float = "%identity"
let age = 10
let gpa = 2.1 +. convertToFloat(age)
```
+
```js
var age = 10;
var gpa = 2.1 + 10;
diff --git a/pages/docs/manual/v9.0.0/introduction.mdx b/pages/docs/manual/v9.0.0/introduction.mdx
index 9fa73cdca..ab8764d7b 100644
--- a/pages/docs/manual/v9.0.0/introduction.mdx
+++ b/pages/docs/manual/v9.0.0/introduction.mdx
@@ -21,7 +21,6 @@ We respect TypeScript very much and think that it's a positive force in the Java
- TypeScript's (admittedly noble) goal is to cover the entire JavaScript feature set and more. **ReScript covers only a curated subset of JavaScript**. For example, we emphasize plain data + functions over classes, clean [pattern matching](pattern-matching-destructuring.md) over fragile `if`s and virtual dispatches, [proper data modeling](variant.md) over string abuse, etc. JavaScript supersets will only grow larger over time; ReScript doesn't. \*
- Consequently, TypeScript's type system is necessarily complex, pitfalls-ridden, potentially requires tweaking, sometimes slow, and requires quite a bit of noisy annotations that often feel like manual bookkeeping rather than clear documentation. In contrast, ReScript's type system:
-
- Is deliberately curated to be a simple subset most folks will have an easier time to use.
- Has **no** pitfalls, aka the type system is "sound" (the types will always be correct). E.g. If a type isn't marked as nullable, its value will never lie and let through some `undefined` value silently. **ReScript code has no null/undefined errors**.
- Is the same for everyone. No knobs, no bikeshedding opportunity.
diff --git a/pages/docs/manual/v9.0.0/json.mdx b/pages/docs/manual/v9.0.0/json.mdx
index b223cc228..55c0efee3 100644
--- a/pages/docs/manual/v9.0.0/json.mdx
+++ b/pages/docs/manual/v9.0.0/json.mdx
@@ -23,8 +23,9 @@ external parseIntoMyData: string => data = "parse"
let result = parseIntoMyData(`{"names": ["Luke", "Christine"]}`)
let name1 = result.names[0]
```
+
```js
-var result = JSON.parse("{\"names\": [\"Luke\", \"Christine\"]}");
+var result = JSON.parse('{"names": ["Luke", "Christine"]}');
var name1 = result.names[0];
```
@@ -41,11 +42,9 @@ Use `Js.Json.stringify`:
```res example
Js.log(Js.Json.stringifyAny(["Amy", "Joe"]))
```
+
```js
-console.log(JSON.stringify([
- "Amy",
- "Joe"
-]));
+console.log(JSON.stringify(["Amy", "Joe"]));
```
diff --git a/pages/docs/manual/v9.0.0/jsx.mdx b/pages/docs/manual/v9.0.0/jsx.mdx
index b1690b2c4..8819bb705 100644
--- a/pages/docs/manual/v9.0.0/jsx.mdx
+++ b/pages/docs/manual/v9.0.0/jsx.mdx
@@ -19,10 +19,11 @@ ReScript supports the JSX syntax, with some slight differences compared to the o
```res
```
+
```js
React.createElement(
MyComponent.make,
- MyComponent.makeProps("ReScript", undefined)
+ MyComponent.makeProps("ReScript", undefined),
);
```
@@ -35,10 +36,11 @@ becomes
```res
@JSX MyComponent.createElement(~name="ReScript", ~children=list{}, ())
```
+
```js
React.createElement(
MyComponent.make,
- MyComponent.makeProps("ReScript", undefined)
+ MyComponent.makeProps("ReScript", undefined),
);
```
@@ -51,10 +53,16 @@ React.createElement(
```res
child1 child2
```
+
```js
-React.createElement("div", {
- onClick: handler
-}, child1, child2);
+React.createElement(
+ "div",
+ {
+ onClick: handler,
+ },
+ child1,
+ child2,
+);
```
@@ -66,10 +74,16 @@ becomes
```res
@JSX div(~onClick=handler, ~children=list{child1, child2}, ())
```
+
```js
-React.createElement("div", {
- onClick: handler
-}, child1, child2);
+React.createElement(
+ "div",
+ {
+ onClick: handler,
+ },
+ child1,
+ child2,
+);
```
@@ -81,6 +95,7 @@ React.createElement("div", {
```res
<> child1 child2 >
```
+
```js
React.createElement(React.Fragment, undefined, child1, child2);
```
@@ -94,6 +109,7 @@ becomes
```res
@JSX list{child1, child2}
```
+
```js
React.createElement(React.Fragment, undefined, child1, child2);
```
@@ -107,8 +123,14 @@ React.createElement(React.Fragment, undefined, child1, child2);
```res
child1 child2
```
+
```js
-React.createElement(MyComponent.make, MyComponent.makeProps(null, undefined), child1, child2);
+React.createElement(
+ MyComponent.make,
+ MyComponent.makeProps(null, undefined),
+ child1,
+ child2,
+);
```
@@ -120,8 +142,14 @@ This is the syntax for passing a list of two items, `child1` and `child2`, to th
```res
@JSX MyComponent.createElement(~children=list{child1, child2}, ())
```
+
```js
-React.createElement(MyComponent.make, MyComponent.makeProps(null, undefined), child1, child2);
+React.createElement(
+ MyComponent.make,
+ MyComponent.makeProps(null, undefined),
+ child1,
+ child2,
+);
```
@@ -139,8 +167,12 @@ To solve the above problem, we've introduced
```res
...myChild
```
+
```js
-React.createElement(MyComponent.make, MyComponent.makeProps(myChild, undefined));
+React.createElement(
+ MyComponent.make,
+ MyComponent.makeProps(myChild, undefined),
+);
```
@@ -152,8 +184,12 @@ This passes the value `myChild` _without_ wrapping it in a list (or array, in th
```res
@JSX MyComponent.createElement(~children=myChild, ())
```
+
```js
-React.createElement(MyComponent.make, MyComponent.makeProps(myChild, undefined));
+React.createElement(
+ MyComponent.make,
+ MyComponent.makeProps(myChild, undefined),
+);
```
@@ -167,6 +203,7 @@ This is extra useful in the cases where you are handled `myChild` that is alread
...("Hello", "Submit")
```
+
```js
React.createElement(
make,
@@ -174,10 +211,13 @@ React.createElement(
return React.createElement("div", {
className: theClassName,
});
- }, undefined)
+ }, undefined),
);
-React.createElement(MyForm.make, MyForm.makeProps(["Hello", "Submit"], undefined));
+React.createElement(
+ MyForm.make,
+ MyForm.makeProps(["Hello", "Submit"], undefined),
+);
```
@@ -200,6 +240,7 @@ Here's a JSX tag that shows most of the features.
{React.string("hello")}
```
+
```js
React.createElement(
MyComponent.make,
@@ -210,8 +251,8 @@ React.createElement(
"hello",
handleClick,
React.createElement("div", undefined, "hello"),
- undefined
- )
+ undefined,
+ ),
);
```
@@ -220,7 +261,7 @@ React.createElement(
## Departures From JS JSX
- Attributes and children don't mandate `{}`, but we show them anyway for ease of learning. Once you format your file, some of them go away and some turn into parentheses.
-- There is no support for JSX prop spread: ` `. Though somewhat related, we do have children spread, described above: ` ...children `.
+- There is no support for JSX prop spread: ` `. Though somewhat related, we do have children spread, described above: ` ...children `.
- Punning!
### Punning
@@ -234,10 +275,11 @@ Reason JSX supports punning. ` ` is just a shorthand for `
```
+
```js
React.createElement(
MyComponent.make,
- MyComponent.makeProps(isLoading, text, onClick, undefined)
+ MyComponent.makeProps(isLoading, text, onClick, undefined),
);
```
diff --git a/pages/docs/manual/v9.0.0/lazy-values.mdx b/pages/docs/manual/v9.0.0/lazy-values.mdx
index 7fde6bb26..5ef3ab575 100644
--- a/pages/docs/manual/v9.0.0/lazy-values.mdx
+++ b/pages/docs/manual/v9.0.0/lazy-values.mdx
@@ -17,15 +17,16 @@ let expensiveFilesRead = lazy({
Node.Fs.readdirSync("./pages")
})
```
+
```js
var Fs = require("fs");
var expensiveFilesRead = {
LAZY_DONE: false,
- VAL: (function () {
+ VAL: function () {
console.log("Reading dir");
return Fs.readdirSync("./pages");
- })
+ },
};
```
@@ -48,6 +49,7 @@ Js.log(Lazy.force(expensiveFilesRead)) // logs "Reading dir" and the directory c
// Second call. Will just return the already calculated result
Js.log(Lazy.force(expensiveFilesRead)) // logs the directory content
```
+
```js
console.log(CamlinternalLazy.force(expensiveFilesRead));
@@ -69,6 +71,7 @@ switch expensiveFilesRead {
| lazy(result) => Js.log(result)
}
```
+
```js
var result = CamlinternalLazy.force(expensiveFilesRead);
```
@@ -83,6 +86,7 @@ Since pattern matching also works on a `let` binding, you can also do:
let lazy(result) = expensiveFilesRead
Js.log(result)
```
+
```js
var result = CamlinternalLazy.force(expensiveFilesRead);
console.log(result);
@@ -103,6 +107,7 @@ let result = try {
| Not_found => [] // empty array of files
}
```
+
```js
var result;
diff --git a/pages/docs/manual/v9.0.0/let-binding.mdx b/pages/docs/manual/v9.0.0/let-binding.mdx
index f746be3ab..5db39032c 100644
--- a/pages/docs/manual/v9.0.0/let-binding.mdx
+++ b/pages/docs/manual/v9.0.0/let-binding.mdx
@@ -15,6 +15,7 @@ let greeting = "hello!"
let score = 10
let newScore = 10 + score
```
+
```js
var greeting = "hello!";
var score = 10;
@@ -37,6 +38,7 @@ let message = {
}
// `part1` and `part2` not accessible here!
```
+
```js
var message = "hello world";
```
@@ -58,6 +60,7 @@ if displayGreeting {
}
// `message` not accessible here!
```
+
```js
if (displayGreeting) {
console.log("Enjoying the docs so far?");
@@ -99,6 +102,7 @@ let result1 = 0
let result2 = calculate(result1)
let result3 = calculateSomeMore(result2)
```
+
```js
var result1 = 0;
var result2 = calculate(0);
@@ -116,6 +120,7 @@ let result = 0
let result = calculate(result)
let result = calculateSomeMore(result)
```
+
```js
var result = calculate(0);
var result$1 = calculateSomeMore(result);
@@ -135,6 +140,7 @@ Js.log(result) // prints "hello"
let result = 1
Js.log(result) // prints 1
```
+
```js
var result = 1;
console.log("hello");
@@ -150,8 +156,8 @@ If you need _real_ mutation, e.g. passing a value around, have it modified by ma
Private let bindings are introduced in the release [7.2](https://rescript-lang.org/blog/bucklescript-release-7-2).
-In the module system, everything is public by default,
-the only way to hide some values is by providing a separate signature to
+In the module system, everything is public by default,
+the only way to hide some values is by providing a separate signature to
list public fields and their types:
```res
@@ -162,6 +168,7 @@ module A: {
let b = 4
}
```
+
`%private` gives you an option to mark private fields directly
```res
@@ -171,15 +178,14 @@ module A = {
}
```
-`%private` also applies to file level modules, so in some cases,
+`%private` also applies to file level modules, so in some cases,
users do not need to provide a separate interface file just to hide some particular values.
-Note interface files are still recommended as a general best practice since they give you better
-separate compilation units and also they're better for documentation.
+Note interface files are still recommended as a general best practice since they give you better
+separate compilation units and also they're better for documentation.
Still, `%private` is useful in the following scenarios:
- Code generators. Some code generators want to hide some values but it is sometimes very hard or time consuming for code generators to synthesize the types for public fields.
- Quick prototyping. During prototyping, we still want to hide some values, but the interface file is not stable yet. `%private` provides you such convenience.
-
diff --git a/pages/docs/manual/v9.0.0/migrate-from-bucklescript-reason.mdx b/pages/docs/manual/v9.0.0/migrate-from-bucklescript-reason.mdx
index 27d476461..164837aa0 100644
--- a/pages/docs/manual/v9.0.0/migrate-from-bucklescript-reason.mdx
+++ b/pages/docs/manual/v9.0.0/migrate-from-bucklescript-reason.mdx
@@ -19,7 +19,7 @@ There are lots of exciting improvements in the new syntax (features, speed, erro
- Choose a file to convert, for example `MyFile.re`
- Compile your project and keep the generated JavaScript file around (probably `MyFile.bs.js` but might depend on your `bsconfig.json` config).
- Run `node_modules/.bin/bsc -format MyFile.re > MyFile.res`.
-- If your new `MyFile.res` looks good, you can delete (or move/rename) `MyFile.re` before compiling again your project (otherwise you will have an error `Invalid bsconfig.json implementation and interface have different path names or different cases MyFile vs MyFile` because 2 files with the same module name (file basename) cannot coexist in your project).
+- If your new `MyFile.res` looks good, you can delete (or move/rename) `MyFile.re` before compiling again your project (otherwise you will have an error `Invalid bsconfig.json implementation and interface have different path names or different cases MyFile vs MyFile` because 2 files with the same module name (file basename) cannot coexist in your project).
- Last thing you can do to ensure conversion is correct: build your project with the new `MyFile.res` file to compare the newly generated JavaScript file with the old one. You should get almost identical generated JavaScript code.
**That's it**! `MyFile.re` could be any `.re`, `.rei`, `.ml` and `.mli` file.
diff --git a/pages/docs/manual/v9.0.0/module.mdx b/pages/docs/manual/v9.0.0/module.mdx
index 8b76a1458..c723c2250 100644
--- a/pages/docs/manual/v9.0.0/module.mdx
+++ b/pages/docs/manual/v9.0.0/module.mdx
@@ -31,6 +31,7 @@ module School = {
}
}
```
+
```js
function getProfession(person) {
if (person) {
@@ -41,8 +42,8 @@ function getProfession(person) {
}
var School = {
- person1: /* Teacher */0,
- getProfession: getProfession
+ person1: /* Teacher */ 0,
+ getProfession: getProfession,
};
```
@@ -57,8 +58,9 @@ using the `.` notation. This demonstrates modules' utility for namespacing.
let anotherPerson: School.profession = School.Teacher
Js.log(School.getProfession(anotherPerson)) /* "A teacher" */
```
+
```js
-var anotherPerson = /* Teacher */0;
+var anotherPerson = /* Teacher */ 0;
console.log("A teacher");
```
@@ -77,13 +79,14 @@ module MyModule = {
let message = MyModule.NestedModule.message
```
+
```js
var NestedModule = {
- message: message
+ message: message,
};
var MyModule = {
- NestedModule: NestedModule
+ NestedModule: NestedModule,
};
var message = MyModule.NestedModule.message;
@@ -101,6 +104,7 @@ module's name. Instead of writing:
```res
let p = School.getProfession(School.person1)
```
+
```js
var p = School.getProfession(School.person1);
```
@@ -115,6 +119,7 @@ We can write:
open School
let p = getProfession(person1)
```
+
```js
var p = School.getProfession(School.person1);
```
@@ -134,6 +139,7 @@ let p = {
}
/* School's content isn't visible here anymore */
```
+
```js
var p = School.getProfession(School.person1);
```
@@ -179,6 +185,7 @@ module ActualComponent = {
let render = () => defaultGreeting ++ " " ++ getAudience(~excited=true)
}
```
+
```js
function getAudience(excited) {
if (excited) {
@@ -190,7 +197,7 @@ function getAudience(excited) {
var BaseComponent = {
defaultGreeting: "Hello",
- getAudience: getAudience
+ getAudience: getAudience,
};
var defaultGreeting = "Hey";
@@ -202,7 +209,7 @@ function render(param) {
var ActualComponent = {
getAudience: getAudience,
defaultGreeting: defaultGreeting,
- render: render
+ render: render,
};
```
@@ -237,6 +244,7 @@ module type EstablishmentType = {
let getProfession: profession => string
}
```
+
```js
// Empty output
```
@@ -281,6 +289,7 @@ module Company: EstablishmentType = {
let person2 = ...
}
```
+
```js
function getProfession(person) {
...
@@ -321,6 +330,7 @@ module type ActualComponent = {
let render: unit => string
}
```
+
```js
// Empty output
```
@@ -342,6 +352,7 @@ module type MyList = {
let myListFun: list<'a> => list<'a>
}
```
+
```js
// Empty output
```
@@ -363,6 +374,7 @@ in the ecosystem to also document the public API of their corresponding modules.
type state = int
let render = (str) => str
```
+
```js
function render(str) {
return str;
@@ -381,7 +393,7 @@ let render: string => string
Modules can be passed to functions! It would be the equivalent of passing a file
as a first-class item. However, modules are at a different "layer" of the
-language than other common concepts, so we can't pass them to *regular*
+language than other common concepts, so we can't pass them to _regular_
functions. Instead, we pass them to special functions called "functors".
The syntax for defining and using functors is very much like the syntax
@@ -389,7 +401,7 @@ for defining and using regular functions. The primary differences are:
- Functors use the `module` keyword instead of `let`.
- Functors take modules as arguments and return a module.
-- Functors *require* annotating arguments.
+- Functors _require_ annotating arguments.
- Functors must start with a capital letter (just like modules/signatures).
Here's an example `MakeSet` functor, that takes in a module of the type
@@ -419,13 +431,14 @@ module MakeSet = (Item: Comparable) => {
}
}
```
+
```js
var List = require("./stdlib/list.js");
function MakeSet(Item) {
- var add = function(currentSet, newItem) {
+ var add = function (currentSet, newItem) {
if (
- List.exists(function(x) {
+ List.exists(function (x) {
return Item.equal(x, newItem);
}, currentSet)
) {
@@ -461,6 +474,7 @@ module IntPair = {
/* IntPair abides by the Comparable signature required by MakeSet */
module SetOfIntPairs = MakeSet(IntPair)
```
+
```js
function equal(param, param$1) {
if (param[0] === param$1[0]) {
@@ -511,6 +525,7 @@ module MakeSet: MakeSetType = (Item: Comparable) => {
...
}
```
+
```js
// Empty output
```
diff --git a/pages/docs/manual/v9.0.0/mutation.mdx b/pages/docs/manual/v9.0.0/mutation.mdx
index 750613a4a..d7bbf3d03 100644
--- a/pages/docs/manual/v9.0.0/mutation.mdx
+++ b/pages/docs/manual/v9.0.0/mutation.mdx
@@ -17,9 +17,10 @@ Let-bindings are immutable, but you can wrap it with a `ref`, exposed as a recor
```res prelude
let myValue = ref(5)
```
+
```js
var myValue = {
- contents: 5
+ contents: 5,
};
```
@@ -34,6 +35,7 @@ You can get the actual value of a `ref` box through accessing its `contents` fie
```res example
let five = myValue.contents // 5
```
+
```js
var five = myValue.contents;
```
@@ -47,6 +49,7 @@ Assign a new value to `myValue` like so:
```res example
myValue.contents = 6
```
+
```js
myValue.contents = 6;
```
@@ -60,6 +63,7 @@ We provide a syntax sugar for this:
```res example
myValue := 6
```
+
```js
myValue.contents = 6;
```
diff --git a/pages/docs/manual/v9.0.0/newcomer-examples.mdx b/pages/docs/manual/v9.0.0/newcomer-examples.mdx
index 4f701411d..360c86fab 100644
--- a/pages/docs/manual/v9.0.0/newcomer-examples.mdx
+++ b/pages/docs/manual/v9.0.0/newcomer-examples.mdx
@@ -25,6 +25,7 @@ switch possiblyNullValue2 {
| Some(message) => Js.log(message)
}
```
+
```js
var possiblyNullValue1;
var possiblyNullValue2 = "Hello";
@@ -34,7 +35,6 @@ if (possiblyNullValue2 !== undefined) {
} else {
console.log("Nothing to see here.");
}
-
```
@@ -51,6 +51,7 @@ type response<'studentType> = {
student: 'studentType,
}
```
+
```js
// Empty output
```
@@ -67,6 +68,7 @@ let student1 = {
"age": 30,
}
```
+
```js
var student1 = {
name: "John",
@@ -91,6 +93,7 @@ let student1 = {
age: 30,
}
```
+
```js
var student1 = {
name: "John",
@@ -119,6 +122,7 @@ let greetByName = (possiblyNullName) => {
}
}
```
+
```js
function greetByName(possiblyNullName) {
if (possiblyNullName == null) {
diff --git a/pages/docs/manual/v9.0.0/null-undefined-option.mdx b/pages/docs/manual/v9.0.0/null-undefined-option.mdx
index 422fa413c..125cc874d 100644
--- a/pages/docs/manual/v9.0.0/null-undefined-option.mdx
+++ b/pages/docs/manual/v9.0.0/null-undefined-option.mdx
@@ -17,6 +17,7 @@ We represent the existence and nonexistence of a value by wrapping it with the `
```res example
type option<'a> = None | Some('a)
```
+
```js
// Empty output
```
@@ -36,6 +37,7 @@ Here's a normal value:
```res example
let licenseNumber = 5
```
+
```js
var licenseNumber = 5;
```
@@ -54,6 +56,7 @@ let licenseNumber =
None
}
```
+
```js
var licenseNumber = personHasACar ? 5 : undefined;
```
@@ -72,6 +75,7 @@ switch licenseNumber {
Js.log("The person's license number is " ++ Js.Int.toString(number))
}
```
+
```js
var number = licenseNumber;
@@ -95,6 +99,7 @@ The `option` type is common enough that we special-case it when compiling to Jav
```res example
let x = Some(5)
```
+
```js
var x = 5;
```
@@ -108,6 +113,7 @@ simply compiles down to `5`, and
```res example
let x = None
```
+
```js
var x;
```
@@ -125,6 +131,7 @@ The option-to-undefined translation isn't perfect, because on our side, `option`
```res example
let x = Some(Some(Some(5)))
```
+
```js
var x = 5;
```
@@ -138,6 +145,7 @@ This still compiles to `5`, but this gets troublesome:
```res example
let x = Some(None)
```
+
```js
var Caml_option = require("./stdlib/caml_option.js");
@@ -172,6 +180,7 @@ If you're receiving, for example, a JS string that can be `null` and `undefined`
```res example
@module("MyConstant") external myId: Js.Nullable.t = "myId"
```
+
```js
// Empty output
```
@@ -188,6 +197,7 @@ let personId: Js.Nullable.t = Js.Nullable.return("abc123")
let result = validate(personId)
```
+
```js
var MyIdValidator = require("MyIdValidator");
var personId = "abc123";
diff --git a/pages/docs/manual/v9.0.0/object.mdx b/pages/docs/manual/v9.0.0/object.mdx
index 6726b9595..419580c25 100644
--- a/pages/docs/manual/v9.0.0/object.mdx
+++ b/pages/docs/manual/v9.0.0/object.mdx
@@ -29,6 +29,7 @@ type person = {
"name": string
};
```
+
```js
// Empty output
```
@@ -51,10 +52,11 @@ let me = {
"name": "Big ReScript"
}
```
+
```js
var me = {
- "age": 5,
- "name": "Big ReScript"
+ age: 5,
+ name: "Big ReScript",
};
```
@@ -73,9 +75,10 @@ let me = {
"age": "hello!" // age is a string. No error.
}
```
+
```js
var me = {
- "age": "hello!"
+ age: "hello!",
};
```
@@ -98,6 +101,7 @@ Now the type system will error properly.
```res
let age = me["age"]
```
+
```js
var age = me["age"];
```
@@ -119,6 +123,7 @@ type student = {
student1["name"] = "Mary"
```
+
```js
var MyJSFile = require("MyJSFile");
MyJSFile.student1.name = "Mary";
@@ -148,8 +153,9 @@ let loc = document["location"]
// set a property
document["location"]["href"] = "rescript-lang.org"
```
+
```js
-document.addEventListener("mouseup", function(_event) {
+document.addEventListener("mouseup", function (_event) {
console.log("clicked!");
});
var loc = document.location;
diff --git a/pages/docs/manual/v9.0.0/overview.mdx b/pages/docs/manual/v9.0.0/overview.mdx
index b91a5b778..fbe887ecb 100644
--- a/pages/docs/manual/v9.0.0/overview.mdx
+++ b/pages/docs/manual/v9.0.0/overview.mdx
@@ -11,44 +11,44 @@ canonical: "/docs/manual/latest/overview"
### Semicolon
-| JavaScript | ReScript |
-| ------------------------------------ | -------------------- |
-| Rules enforced by linter/formatter | No semicolon needed! |
+| JavaScript | ReScript |
+| ---------------------------------- | -------------------- |
+| Rules enforced by linter/formatter | No semicolon needed! |
### Comments
-| JavaScript | ReScript |
-| ----------------- | ----------- |
-| `/* Comment */` | Same |
-| `// Line comment` | Same |
+| JavaScript | ReScript |
+| ----------------- | -------- |
+| `/* Comment */` | Same |
+| `// Line comment` | Same |
### Variable
-| JavaScript | ReScript |
-| ----------------------- | ------------------------------ |
-| `const x = 5;` | `let x = 5` |
-| `var x = y;` | No equivalent (thankfully) |
+| JavaScript | ReScript |
+| ----------------------- | ------------------------------------- |
+| `const x = 5;` | `let x = 5` |
+| `var x = y;` | No equivalent (thankfully) |
| `let x = 5; x = x + 1;` | `let x = ref(5); x := x.contents + 1` |
### String & Character
-| JavaScript | ReScript |
-| --------------------------| --------------------- |
-| `"Hello world!"` | Same |
-| `'Hello world!'` | Strings must use `"` |
-| `"hello " + "world"` | `"hello " ++ "world"` |
-| `` `hello ${message}` `` | Same |
+| JavaScript | ReScript |
+| ------------------------ | --------------------- |
+| `"Hello world!"` | Same |
+| `'Hello world!'` | Strings must use `"` |
+| `"hello " + "world"` | `"hello " ++ "world"` |
+| `` `hello ${message}` `` | Same |
### Boolean
-| JavaScript | ReScript |
-| ------------------------------------- | ---------------------------------------------- |
-| `true`, `false` | Same |
-| `!true` | Same |
-| `\|\|`, `&&`, `<=`, `>=`, `<`, `>` | Same |
-| `a === b`, `a !== b` | Same |
-| No deep equality (recursive compare) | `a == b`, `a != b` |
-| `a == b` | No equality with implicit casting (thankfully) |
+| JavaScript | ReScript |
+| ------------------------------------ | ---------------------------------------------- |
+| `true`, `false` | Same |
+| `!true` | Same |
+| `\|\|`, `&&`, `<=`, `>=`, `<`, `>` | Same |
+| `a === b`, `a !== b` | Same |
+| No deep equality (recursive compare) | `a == b`, `a != b` |
+| `a == b` | No equality with implicit casting (thankfully) |
### Number
@@ -74,11 +74,11 @@ canonical: "/docs/manual/latest/overview"
### Array
-| JavaScript | ReScript |
-| --------------------- | ---------------------------------- |
-| `[1, 2, 3]` | Same |
-| `myArray[1] = 10` | Same |
-| `[1, "Bob", true]` | `(1, "Bob", true)` \* |
+| JavaScript | ReScript |
+| ------------------ | --------------------- |
+| `[1, 2, 3]` | Same |
+| `myArray[1] = 10` | Same |
+| `[1, "Bob", true]` | `(1, "Bob", true)` \* |
\* Heterogenous arrays in JS are disallowed for us. Use tuple instead.
@@ -134,31 +134,31 @@ canonical: "/docs/manual/latest/overview"
### If-else
-| JavaScript | ReScript |
-| --------------------- | ------------------------------------------------------------------- |
-| `if (a) {b} else {c}` | `if a {b} else {c}` \* |
-| `a ? b : c` | Same |
+| JavaScript | ReScript |
+| --------------------- | --------------------------------------------------------------------------------- |
+| `if (a) {b} else {c}` | `if a {b} else {c}` \* |
+| `a ? b : c` | Same |
| `switch` | `switch` but [super-powered pattern matching!](pattern-matching-destructuring.md) |
\* Our conditionals are always expressions! You can write `let result = if a {"hello"} else {"bye"}`
### Destructuring
-| JavaScript | ReScript |
-| ----------------------------- | --------------------------------------------- |
-| `const {a, b} = data` | `let {a, b} = data` |
-| `const [a, b] = data` | let [a, b] = data
\* |
-| `const {a: aa, b: bb} = data` | `let {a: aa, b: bb} = data` |
+| JavaScript | ReScript |
+| ----------------------------- | --------------------------------- |
+| `const {a, b} = data` | `let {a, b} = data` |
+| `const [a, b] = data` | let [a, b] = data
\* |
+| `const {a: aa, b: bb} = data` | `let {a: aa, b: bb} = data` |
\* Gives good compiler warning that `data` might not be of length 2.
### Loop
-| JavaScript | ReScript |
-| ------------------------------------- | ------------------------------ |
-| `for (let i = 0; i <= 10; i++) {...}` | `for i in 0 to 10 {...}` |
-| `for (let i = 10; i >= 0; i--) {...}` | `for i in 10 downto 0 {...}` |
-| `while (true) {...}` | `while true {...}` |
+| JavaScript | ReScript |
+| ------------------------------------- | ---------------------------- |
+| `for (let i = 0; i <= 10; i++) {...}` | `for i in 0 to 10 {...}` |
+| `for (let i = 10; i >= 0; i--) {...}` | `for i in 10 downto 0 {...}` |
+| `while (true) {...}` | `while true {...}` |
### JSX
@@ -173,10 +173,10 @@ canonical: "/docs/manual/latest/overview"
### Exception
-| JavaScript | ReScript |
-| ----------------------------------------------- | ------------------------------------------ |
-| `throw new SomeError(...)` | `raise(SomeError(...))` |
-| `try {a} catch (Err) {...} finally {...}` | `try a catch { \| Err => ...}` \* |
+| JavaScript | ReScript |
+| ----------------------------------------- | --------------------------------- |
+| `throw new SomeError(...)` | `raise(SomeError(...))` |
+| `try {a} catch (Err) {...} finally {...}` | `try a catch { \| Err => ...}` \* |
\* No finally.
@@ -215,30 +215,29 @@ The last expression of a block delimited by `{}` implicitly returns (including f
-
## Common Features' JS Output
-Feature | Example | JavaScript Output
---------------------------------|--------------------------------------|----------------------
-String | `"Hello"` | `"Hello"`
-String Interpolation | `` `Hello ${message}` `` | `"Hello " + message`
-Character (disrecommended) | `'x'` | `120` (char code)
-Integer | `23`, `-23` | `23`, `-23`
-Float | `23.0`, `-23.0` | `23.0`, `-23.0`
-Integer Addition | `23 + 1` | `23 + 1`
-Float Addition | `23.0 +. 1.0` | `23.0 + 1.0`
-Integer Division/Multiplication | `2 / 23 * 1` | `2 / 23 * 1`
-Float Division/Multiplication | `2.0 /. 23.0 *. 1.0` | `2.0 / 23.0 * 1.0`
-Float Exponentiation | `2.0 ** 3.0` | `Math.pow(2.0, 3.0)`
-String Concatenation | `"Hello " ++ "World"` | `"Hello " + "World"`
-Comparison | `>`, `<`, `>=`, `<=` | `>`, `<`, `>=`, `<=`
-Boolean operation | `!`, `&&`, `\|\|` | `!`, `&&`, `\|\|`
-Shallow and deep Equality | `===`, `==` | `===`, `==`
-List (disrecommended) | `list{1, 2, 3}` | `{hd: 1, tl: {hd: 2, tl: {hd: 3, tl: 0}}}`
-List Prepend | `list{a1, a2, ...oldList}` | `{hd: a1, tl: {hd: a2, tl: theRest}}`
-Array | `[1, 2, 3]` | `[1, 2, 3]`
-Record | `type t = {b: int}; let a = {b: 10}` | `var a = {b: 10}`
-Multiline Comment | `/* Comment here */` | Not in output
-Single line Comment | `// Comment here` | Not in output
+| Feature | Example | JavaScript Output |
+| ------------------------------- | ------------------------------------ | ------------------------------------------ |
+| String | `"Hello"` | `"Hello"` |
+| String Interpolation | `` `Hello ${message}` `` | `"Hello " + message` |
+| Character (disrecommended) | `'x'` | `120` (char code) |
+| Integer | `23`, `-23` | `23`, `-23` |
+| Float | `23.0`, `-23.0` | `23.0`, `-23.0` |
+| Integer Addition | `23 + 1` | `23 + 1` |
+| Float Addition | `23.0 +. 1.0` | `23.0 + 1.0` |
+| Integer Division/Multiplication | `2 / 23 * 1` | `2 / 23 * 1` |
+| Float Division/Multiplication | `2.0 /. 23.0 *. 1.0` | `2.0 / 23.0 * 1.0` |
+| Float Exponentiation | `2.0 ** 3.0` | `Math.pow(2.0, 3.0)` |
+| String Concatenation | `"Hello " ++ "World"` | `"Hello " + "World"` |
+| Comparison | `>`, `<`, `>=`, `<=` | `>`, `<`, `>=`, `<=` |
+| Boolean operation | `!`, `&&`, `\|\|` | `!`, `&&`, `\|\|` |
+| Shallow and deep Equality | `===`, `==` | `===`, `==` |
+| List (disrecommended) | `list{1, 2, 3}` | `{hd: 1, tl: {hd: 2, tl: {hd: 3, tl: 0}}}` |
+| List Prepend | `list{a1, a2, ...oldList}` | `{hd: a1, tl: {hd: a2, tl: theRest}}` |
+| Array | `[1, 2, 3]` | `[1, 2, 3]` |
+| Record | `type t = {b: int}; let a = {b: 10}` | `var a = {b: 10}` |
+| Multiline Comment | `/* Comment here */` | Not in output |
+| Single line Comment | `// Comment here` | Not in output |
_Note that this is a cleaned-up comparison table; a few examples' JavaScript output are slightly different in reality._
diff --git a/pages/docs/manual/v9.0.0/pattern-matching-destructuring.mdx b/pages/docs/manual/v9.0.0/pattern-matching-destructuring.mdx
index ac09f9c3a..e20f4d36e 100644
--- a/pages/docs/manual/v9.0.0/pattern-matching-destructuring.mdx
+++ b/pages/docs/manual/v9.0.0/pattern-matching-destructuring.mdx
@@ -25,6 +25,7 @@ let coordinates = (10, 20, 30)
let (x, _, _) = coordinates
Js.log(x) // 10
```
+
```js
var coordinates = [10, 20, 30];
var x = 10;
@@ -49,28 +50,25 @@ type result =
let myResult = Success("You did it!")
let Success(message) = myResult // "You did it!" assigned to `message`
```
+
```js
var student1 = {
name: "John",
- age: 10
+ age: 10,
};
var name = "John";
-var myResult = /* Success */{
- _0: "You did it!"
+var myResult = /* Success */ {
+ _0: "You did it!",
};
-var message = "You did it!"
+var message = "You did it!";
var myArray = [1, 2, 3];
if (myArray.length !== 2) {
throw {
RE_EXN_ID: "Match_failure",
- _1: [
- "playground.res",
- 14,
- 4
- ],
- Error: new Error()
+ _1: ["playground.res", 14, 4],
+ Error: new Error(),
};
}
var item1 = myArray[0];
@@ -82,9 +80,9 @@ var myList = {
hd: 2,
tl: {
hd: 3,
- tl: /* [] */0
- }
- }
+ tl: /* [] */ 0,
+ },
+ },
};
// ...
```
@@ -105,14 +103,17 @@ let displayMessage = (Success(m)) => {
}
displayMessage(Success("You did it!"))
```
+
```js
function displayMessage(m) {
console.log(m._0);
}
-displayMessage(/* Success */{
- _0: "You did it!"
-});
+displayMessage(
+ /* Success */ {
+ _0: "You did it!",
+ },
+);
```
@@ -124,6 +125,7 @@ For a record, you can rename the field while destructuring:
```res
let {name: n} = student1 // "John" assigned to `n`
```
+
```js
var n = "John";
```
@@ -158,6 +160,7 @@ type payload =
| GoodResult(string)
| NoResult
```
+
```js
// Empty output
```
@@ -181,16 +184,19 @@ switch data {
Js.log("Bah.")
}
```
+
```js
var data = {
- TAG: /* GoodResult */1,
- _0: "Product shipped!"
+ TAG: /* GoodResult */ 1,
+ _0: "Product shipped!",
};
if (typeof data === "number") {
console.log("Bah.");
} else if (data.TAG === /* BadResult */ 0) {
- console.log("Something's wrong. The error code is: " + "Product shipped!".toString());
+ console.log(
+ "Something's wrong. The error code is: " + "Product shipped!".toString(),
+ );
} else {
console.log("Success! Product shipped!");
}
@@ -222,6 +228,7 @@ type person =
reportCard: reportCard,
})
```
+
```js
// Empty output
```
@@ -262,11 +269,12 @@ let message = switch person1 {
`Good luck next semester ${name}!`
}
```
+
```js
var person1 = {
- TAG: /* Teacher */0,
+ TAG: /* Teacher */ 0,
name: "Jane",
- age: 35
+ age: 35,
};
var message;
@@ -282,12 +290,12 @@ if (person1.TAG) {
match$2.gpa.toString() +
" you got there!"
: typeof match$1 === "number"
- ? match$1 !== 0
- ? "Good luck next semester " + name + "!"
- : "How are you feeling?"
- : person1.reportCard.gpa !== 0.0
- ? "Good luck next semester " + name + "!"
- : "Come back in " + match$1._0.toString() + " days!";
+ ? match$1 !== 0
+ ? "Good luck next semester " + name + "!"
+ : "How are you feeling?"
+ : person1.reportCard.gpa !== 0.0
+ ? "Good luck next semester " + name + "!"
+ : "Come back in " + match$1._0.toString() + " days!";
} else {
var name$1 = person1.name;
switch (name$1) {
@@ -304,6 +312,7 @@ if (person1.TAG) {
**Note** how we've:
+
- drilled deep down into the value concisely
- using a **nested pattern check** `"Mary" | "Joe"` and `Vacations | Sabbatical`
- while extracting the `daysLeft` number from the latter case
@@ -323,6 +332,7 @@ let categoryId = switch (isBig, myAnimal) {
| (false, Bird) => 5
}
```
+
```js
var categoryId = isBig ? (myAnimal + 1) | 0 : myAnimal >= 2 ? 5 : 4;
```
@@ -331,10 +341,10 @@ var categoryId = isBig ? (myAnimal + 1) | 0 : myAnimal >= 2 ? 5 : 4;
**Note** how pattern matching on a tuple is equivalent to a 2D table:
-isBig \ myAnimal | Dog | Cat | Bird
------------------|-----|-----|------
-true | 1 | 2 | 3
-false | 4 | 4 | 5
+| isBig \ myAnimal | Dog | Cat | Bird |
+| ---------------- | --- | --- | ---- |
+| true | 1 | 2 | 3 |
+| false | 4 | 4 | 5 |
### Fall-Through Patterns
@@ -352,10 +362,11 @@ switch myStatus {
| Present => Js.log("Hey! How are you?")
}
```
+
```js
var myStatus = {
- TAG: /* Vacations */0,
- _0: 10
+ TAG: /* Vacations */ 0,
+ _0: 10,
};
if (typeof myStatus === "number") {
@@ -381,6 +392,7 @@ switch person1 {
| Student(_) => Js.log("Hey student")
}
```
+
```js
if (person1.TAG) {
console.log("Hey student");
@@ -401,6 +413,7 @@ switch myStatus {
| _ => Js.log("Ok.")
}
```
+
```js
if (typeof myStatus === "number" || myStatus.TAG) {
console.log("Ok.");
@@ -421,6 +434,7 @@ switch myStatus {
| Sabbatical(_) | Sick | Present => Js.log("Ok.")
}
```
+
```js
if (typeof myStatus === "number" || myStatus.TAG) {
console.log("Ok.");
@@ -450,6 +464,7 @@ switch person1 {
}
}
```
+
```js
if (person1.TAG) {
if (person1.reportCard.gpa < 0.5) {
@@ -476,6 +491,7 @@ switch person1 {
Js.log("Heyo")
}
```
+
```js
if (person1.TAG) {
if (person1.reportCard.gpa < 0.5) {
@@ -502,18 +518,18 @@ switch List.find(i => i === theItem, myItems) {
| exception Not_found => Js.log("No such item found!")
}
```
+
```js
var exit = 0;
var item;
try {
- item = List.find(function(i) {
+ item = List.find(function (i) {
return i === theItem;
}, myItems);
exit = 1;
-}
-catch (raw_exn){
+} catch (raw_exn) {
var exn = Caml_js_exceptions.internalToOCamlException(raw_exn);
if (exn.RE_EXN_ID === "Not_found") {
console.log("No such item found!");
@@ -544,6 +560,7 @@ switch students {
Js.log2("The students are: ", manyStudents)
}
```
+
```js
var students = ["Jane", "Harvey", "Patrick"];
@@ -581,9 +598,10 @@ let rec printStudents = (students) => {
}
printStudents(list{"Jane", "Harvey", "Patrick"})
```
+
```js
function printStudents(_students) {
- while(true) {
+ while (true) {
var students = _students;
if (!students) {
return;
@@ -597,7 +615,7 @@ function printStudents(_students) {
}
console.log("Last student: " + student);
return;
- };
+ }
}
printStudents({
@@ -606,15 +624,14 @@ printStudents({
hd: "Harvey",
tl: {
hd: "Patrick",
- tl: /* [] */0
- }
- }
+ tl: /* [] */ 0,
+ },
+ },
});
```
-
### Small Pitfall
**Note**: you can only pass literals (i.e. concrete values) as a pattern, not let-binding names or other things. The following doesn't work as expected:
@@ -628,6 +645,7 @@ switch coordinates {
| (x, centerY, _) => Js.log(x)
}
```
+
```js
var coordinates = [10, 20, 30];
var centerY = 20;
@@ -664,18 +682,23 @@ let message = switch person1 {
`Good luck next semester ${name}!`
}
```
+
```js
if (person1.TAG) {
var match$1 = person1.status;
var name = person1.name;
var match$2 = person1.reportCard;
if (match$2.passing) {
- "Congrats " + name + ", nice GPA of " + match$2.gpa.toString() + " you got there!";
+ "Congrats " +
+ name +
+ ", nice GPA of " +
+ match$2.gpa.toString() +
+ " you got there!";
} else if (typeof match$1 === "number") {
if (match$1 !== 0) {
"Good luck next semester " + name + "!";
} else {
- "How are you feeling?";
+ ("How are you feeling?");
}
} else if (person1.reportCard.gpa !== 0.0) {
"Good luck next semester " + name + "!";
@@ -690,12 +713,8 @@ if (person1.TAG) {
default:
throw {
RE_EXN_ID: "Match_failure",
- _1: [
- "playground.res",
- 13,
- 0
- ],
- Error: new Error()
+ _1: ["playground.res", 13, 0],
+ Error: new Error(),
};
}
}
@@ -725,6 +744,7 @@ switch myNullableValue {
| None => Js.log("value is absent")
}
```
+
```js
var myNullableValue = 5;
@@ -764,6 +784,7 @@ let optionBoolToBool = opt => {
}
}
```
+
```js
function optionBoolToBool(opt) {
if (opt === undefined) {
@@ -788,6 +809,7 @@ let optionBoolToBool = opt => {
}
}
```
+
```js
function optionBoolToBool(opt) {
if (opt !== undefined && opt) {
@@ -813,6 +835,7 @@ let optionBoolToBool = opt => {
}
}
```
+
```js
function optionBoolToBool(opt) {
if (opt !== undefined && opt) {
@@ -837,6 +860,7 @@ let optionBoolToBool = opt => {
}
}
```
+
```js
function optionBoolToBool(opt) {
if (opt !== undefined && opt) {
@@ -861,6 +885,7 @@ let optionBoolToBool = opt => {
}
}
```
+
```js
function optionBoolToBool(opt) {
if (opt !== undefined) {
diff --git a/pages/docs/manual/v9.0.0/pipe.mdx b/pages/docs/manual/v9.0.0/pipe.mdx
index 706915d40..9b98d1d25 100644
--- a/pages/docs/manual/v9.0.0/pipe.mdx
+++ b/pages/docs/manual/v9.0.0/pipe.mdx
@@ -15,6 +15,7 @@ Why would you use it? Imagine you have the following:
```res
validateAge(getAge(parseData(person)))
```
+
```js
validateAge(getAge(parseData(person)));
```
@@ -31,6 +32,7 @@ person
->getAge
->validateAge
```
+
```js
validateAge(getAge(parseData(person)));
```
@@ -46,6 +48,7 @@ Basically, `parseData(person)` is transformed into `person->parseData`, and `get
```res
a(one, two, three)
```
+
```js
a(one, two, three);
```
@@ -59,6 +62,7 @@ is the same as
```res
one->a(two, three)
```
+
```js
a(one, two, three);
```
@@ -80,11 +84,9 @@ _This section requires understanding of [our binding API](bind-to-js-function.md
JavaScript's APIs are often attached to objects, and often chainable, like so:
```js
-const result = [1, 2, 3].map(a => a + 1).filter(a => a % 2 === 0);
+const result = [1, 2, 3].map((a) => a + 1).filter((a) => a % 2 === 0);
-asyncRequest()
- .setWaitDuration(4000)
- .send();
+asyncRequest().setWaitDuration(4000).send();
```
Assuming we don't need the chaining behavior above, we'd bind to each case this using `bs.send` from the aforementioned binding API page:
@@ -100,6 +102,7 @@ type request
@bs.send external setWaitDuration: (request, int) => request = "setWaitDuration"
@bs.send external send: request => unit = "send"
```
+
```js
// Empty output
```
@@ -118,12 +121,15 @@ let result = Js.Array2.filter(
send(setWaitDuration(asyncRequest(), 4000))
```
+
```js
-var result = [1, 2, 3].map(function(a) {
- return a + 1 | 0;
-}).filter(function(a) {
- return a % 2 === 0;
-});
+var result = [1, 2, 3]
+ .map(function (a) {
+ return (a + 1) | 0;
+ })
+ .filter(function (a) {
+ return a % 2 === 0;
+ });
asyncRequest().setWaitDuration(4000).send();
```
@@ -141,12 +147,15 @@ let result = [1, 2, 3]
asyncRequest()->setWaitDuration(4000)->send
```
+
```js
-var result = [1, 2, 3].map(function(a) {
- return a + 1 | 0;
-}).filter(function(a) {
- return a % 2 === 0;
-});
+var result = [1, 2, 3]
+ .map(function (a) {
+ return (a + 1) | 0;
+ })
+ .filter(function (a) {
+ return a % 2 === 0;
+ });
asyncRequest().setWaitDuration(4000).send();
```
@@ -162,6 +171,7 @@ You can pipe into a variant's constructor as if it was a function:
```res
let result = name->preprocess->Some
```
+
```js
var result = preprocess(name);
```
@@ -175,6 +185,7 @@ We turn this into:
```res
let result = Some(preprocess(name))
```
+
```js
var result = preprocess(name);
```
@@ -202,6 +213,7 @@ Let's say you have a function `namePerson`, which takes a `person` then a `name`
makePerson(~age=47, ())
->namePerson("Jane")
```
+
```js
namePerson(makePerson(47), "Jane");
```
@@ -216,6 +228,7 @@ If you have a name that you want to apply to a person object, you can use a plac
getName(input)
->namePerson(personDetails, _)
```
+
```js
var __x = getName(input);
namePerson(personDetails, __x);
@@ -231,6 +244,7 @@ This allows you to pipe into any positional argument. It also works for named ar
getName(input)
->namePerson(~person=personDetails, ~name=_)
```
+
```js
var __x = getName(input);
namePerson(personDetails, __x);
diff --git a/pages/docs/manual/v9.0.0/polymorphic-variant.mdx b/pages/docs/manual/v9.0.0/polymorphic-variant.mdx
index d411ac432..9b2962d4a 100644
--- a/pages/docs/manual/v9.0.0/polymorphic-variant.mdx
+++ b/pages/docs/manual/v9.0.0/polymorphic-variant.mdx
@@ -119,7 +119,7 @@ let acc: account = #Instagram("test")
```js
var acc = {
NAME: "Instagram",
- VAL: "test"
+ VAL: "test",
};
```
@@ -203,8 +203,8 @@ var content = {
NAME: "Paragraph",
VAL: {
NAME: "Text",
- VAL: "hello world"
- }
+ VAL: "hello world",
+ },
};
```
@@ -229,7 +229,6 @@ let background: [< #Red | #Blue] = #Red
Don't worry about the upper / lower bound feature just yet, since this is a very advanced topic that's often not really needed. For the sake of completeness, we mention a few details about it [later on](#lower--upper-bound-constraints).
-
## Polymorphic Variants are Structurally Typed
As we've already seen in the section above, poly variants don't need any explicit type definition to be used as a value.
@@ -261,7 +260,7 @@ let other = [#Green]
let all = Belt.Array.concat(colors, other)
```
-As you can see in the example above, the type checker doesn't really care about the fact that `other` is not annotated as an `array` type.
+As you can see in the example above, the type checker doesn't really care about the fact that `other` is not annotated as an `array` type.
As soon as it hits the first constraint (`Belt.Array.concat`), it will try to check if the structural types of `colors` and `other` unify into one poly variant type. If there's a mismatch, you will get an error on the `Belt.Array.concat` call.
@@ -289,7 +288,6 @@ A value compiles to the following JavaScript output:
Check the output in these examples:
-
```res example
@@ -308,7 +306,7 @@ var lowercased = "goodbye";
var err = {
NAME: "error",
- VAL: "oops!"
+ VAL: "oops!",
};
var num = "1";
@@ -316,7 +314,6 @@ var num = "1";
-
### Bind to JS Functions
Poly variants play an important role for binding to functions in JavaScript.
@@ -347,11 +344,10 @@ var intl = Intl.NumberFormat("de-DE");
-The JS Output is practically identical to handwritten JS, but we also get to enjoy all the benefits of a variant.
+The JS Output is practically identical to handwritten JS, but we also get to enjoy all the benefits of a variant.
More usage examples for poly variant interop can be found in [Bind to JS Function](bind-to-js-function#constrain-arguments-better) and [Generate Converters and Helper](generate-converters-accessors#generate-converters-for-js-string-enums-and-polymorphic-variants).
-
### Bind to String Enums
Let's assume we have a TypeScript module that expresses following (stringly typed) enum export:
@@ -370,7 +366,6 @@ export const myDirection = Direction.Up
For this particular example, we can also inline poly variant type definitions to design the type for the imported `myDirection` value:
-
```res
@@ -406,7 +401,7 @@ let color: rgb = #Green
In the example above, `color` will only allow one of the three constructors that are defined in the `rgb` type. This is usually the way how poly variants should be defined.
-In case you want to define a type that is extensible in polymorphic ways (or in other words, subtyping allowed sets of constructors), you'll need to use the lower / upper bound syntax.
+In case you want to define a type that is extensible in polymorphic ways (or in other words, subtyping allowed sets of constructors), you'll need to use the lower / upper bound syntax.
### Lower Bound (`[>`)
@@ -424,7 +419,7 @@ let color: color = #Purple
type notWorking = basicBlueTone<[#Purple]>
```
-Here, the compiler will enforce the user to define `#Blue | #DeepBlue | #LightBlue` as the minimum set of constructors when trying to extend `basicBlueTone<'a>`.
+Here, the compiler will enforce the user to define `#Blue | #DeepBlue | #LightBlue` as the minimum set of constructors when trying to extend `basicBlueTone<'a>`.
**Note:** Since we want to define an extensible poly variant, we need to provide a type placeholder `<'a>`, and also add `as 'a` after the poly variant declaration, which essentially means: "Given type `'a` is constraint to the minimum set of constructors (`#Blue | #DeepBlue | #LightBlue`) defined in `basicBlueTone`".
diff --git a/pages/docs/manual/v9.0.0/primitive-types.mdx b/pages/docs/manual/v9.0.0/primitive-types.mdx
index 9276e8682..5ff3bec1b 100644
--- a/pages/docs/manual/v9.0.0/primitive-types.mdx
+++ b/pages/docs/manual/v9.0.0/primitive-types.mdx
@@ -21,6 +21,7 @@ let greeting = "Hello world!"
let multilineGreeting = "Hello
world!"
```
+
```js
var greeting = "Hello world!";
var multilineGreeting = "Hello\n world!";
@@ -35,6 +36,7 @@ To concatenate strings, use `++`:
```res example
let greetings = "Hello " ++ "world!"
```
+
```js
var greetings = "Hello world!";
```
@@ -61,6 +63,7 @@ World
${name}
`
```
+
```js
var name = "Joe";
@@ -79,6 +82,7 @@ For interpolation, you'll have to convert the binding (`name` in the example) in
let age = 10
let message = j`Today I am $age years old.`
```
+
```js
var message = "Today I am " + 10 + " years old.";
```
@@ -110,8 +114,9 @@ ReScript has a type for a string with a single letter:
```res example
let firstLetterOfAlphabet = 'a'
```
+
```js
-var firstLetterOfAlphabet = /* "a" */97;
+var firstLetterOfAlphabet = /* "a" */ 97;
```
@@ -129,6 +134,7 @@ ReScript regular expressions compile cleanly to their JavaScript counterpart:
```res example
let r = %re("/b/g")
```
+
```js
var r = /b/g;
```
diff --git a/pages/docs/manual/v9.0.0/promise.mdx b/pages/docs/manual/v9.0.0/promise.mdx
index 43c96c84e..bb3bd0f45 100644
--- a/pages/docs/manual/v9.0.0/promise.mdx
+++ b/pages/docs/manual/v9.0.0/promise.mdx
@@ -29,8 +29,7 @@ Js.Promise.make: (
) => Js.Promise.t<'a>
```
-This type signature means that `make` takes a callback that takes 2 named arguments, `resolve` and `reject`. Both arguments are themselves [uncurried callbacks](
-function.md#uncurried-function) (with a dot). `make` returns the created promise.
+This type signature means that `make` takes a callback that takes 2 named arguments, `resolve` and `reject`. Both arguments are themselves [uncurried callbacks](function.md#uncurried-function) (with a dot). `make` returns the created promise.
## Usage
@@ -52,6 +51,7 @@ myPromise->Js.Promise.then_(value => {
Js.Promise.resolve(-2)
}, _)
```
+
```js
var myPromise = new Promise(function (resolve, reject) {
return resolve(2);
@@ -73,5 +73,3 @@ myPromise
```
-
-
diff --git a/pages/docs/manual/v9.0.0/record.mdx b/pages/docs/manual/v9.0.0/record.mdx
index d936ce59f..73c5ee1ca 100644
--- a/pages/docs/manual/v9.0.0/record.mdx
+++ b/pages/docs/manual/v9.0.0/record.mdx
@@ -23,6 +23,7 @@ type person = {
name: string
}
```
+
```js
// Empty output
```
@@ -41,10 +42,11 @@ let me = {
name: "Big ReScript"
}
```
+
```js
var me = {
age: 5,
- name: "Big ReScript"
+ name: "Big ReScript",
};
```
@@ -60,6 +62,7 @@ The type is found by looking above the `me` value. **Note**: if the type instead
// School.res
type person = {age: int, name: string}
```
+
```js
// Empty output
```
@@ -75,14 +78,15 @@ let me: School.person = {age: 20, name: "Big ReScript"}
/* or */
let me2 = {School.age: 20, name: "Big ReScript"}
```
+
```js
var me = {
age: 20,
- name: "Big ReScript"
+ name: "Big ReScript",
};
var me2 = {
age: 20,
- name: "Big ReScript"
+ name: "Big ReScript",
};
```
@@ -99,6 +103,7 @@ Use the familiar dot notation:
```res example
let name = me.name
```
+
```js
var name = "Big ReScript";
```
@@ -114,10 +119,11 @@ New records can be created from old records with the `...` spread operator. The
```res example
let meNextYear = {...me, age: me.age + 1}
```
+
```js
var meNextYear = {
age: 21,
- name: "Big ReScript"
+ name: "Big ReScript",
};
```
@@ -140,13 +146,14 @@ type person = {
let baby = {name: "Baby ReScript", age: 5}
baby.age = baby.age + 1 // `baby.age` is now 6. Happy birthday!
```
+
```js
var baby = {
name: "Baby ReScript",
- age: 5
+ age: 5,
};
-baby.age = baby.age + 1 | 0;
+baby.age = (baby.age + 1) | 0;
```
@@ -169,6 +176,7 @@ type monster = {age: int, hasTentacles: bool}
let getAge = (entity) => entity.age
```
+
```js
function getAge(entity) {
return entity.age;
diff --git a/pages/docs/manual/v9.0.0/reserved-keywords.mdx b/pages/docs/manual/v9.0.0/reserved-keywords.mdx
index aab048bcb..f649ebebb 100644
--- a/pages/docs/manual/v9.0.0/reserved-keywords.mdx
+++ b/pages/docs/manual/v9.0.0/reserved-keywords.mdx
@@ -14,81 +14,70 @@ canonical: "/docs/manual/latest/reserved-keywords"
- `as`
- `assert`
-
-
-- `constraint`
+- `constraint`
-- `downto`
+- `downto`
- `else`
-
-
+
+
- `exception`
- `external`
-
- `false`
- `for`
-
-
-
-
+
+
+
- `if`
- `in`
- `include`
-
-
-
+
+
- `lazy`
- `let`
-
- `module`
- `mutable`
-
-
+
- `of`
- `open`
-
-
- `rec`
-
-- `switch`
+- `switch`
+
- `to`
- `true`
- `try`
- `type`
-
-
- `when`
- `while`
- `with`
diff --git a/pages/docs/manual/v9.0.0/shared-data-types.mdx b/pages/docs/manual/v9.0.0/shared-data-types.mdx
index d6ae8e914..523e0df55 100644
--- a/pages/docs/manual/v9.0.0/shared-data-types.mdx
+++ b/pages/docs/manual/v9.0.0/shared-data-types.mdx
@@ -13,6 +13,7 @@ This means that if you're passing e.g. a ReScript string to the JavaScript side,
Unlike most compiled-to-js languages, in ReScript, **you don't need to write data converters back and forth for most of our values**!
**Shared, bidirectionally usable types**:
+
- String. ReScript strings are JavaScript strings, vice-versa. (Caveat: only our backtick string `` `hello 👋 ${personName}` `` supports unicode and interpolation).
- Float. ReScript floats are JS numbers, vice-versa.
- Array. In addition to the [JS Array API](api/js/array), we provide our own [Belt.Array](api/belt/array#set) API too.
@@ -27,6 +28,7 @@ Unlike most compiled-to-js languages, in ReScript, **you don't need to write dat
**Types that are slightly different than JS, but that you can still use from JS**:
+
- Int. **Ints are 32-bits**! Be careful, you can potentially treat them as JS numbers and vice-versa, but if the number's large, then you better treat JS numbers as floats. For example, we bind to Js.Date using `float`s.
- Option. The `option` type's `None` value compiles into JS `undefined`. The `Some` value, e.g. `Some(5)`, compiles to `5`. Likewise, you can treat an incoming JS `undefined` as `None`. **JS `null` isn't handled here**. If your JS value can be `null`, use [Js.Nullable](api/js/nullable) helpers.
- Exception.
diff --git a/pages/docs/manual/v9.0.0/tuple.mdx b/pages/docs/manual/v9.0.0/tuple.mdx
index 951584c4f..669408775 100644
--- a/pages/docs/manual/v9.0.0/tuple.mdx
+++ b/pages/docs/manual/v9.0.0/tuple.mdx
@@ -19,6 +19,7 @@ Tuples are a ReScript-specific data structure that don't exist in JavaScript. Th
let ageAndName = (24, "Lil' ReScript")
let my3dCoordinates = (20.0, 30.5, 100.0)
```
+
```js
var ageAndName = [24, "Lil' ReScript"];
var my3dCoordinates = [20.0, 30.5, 100.0];
@@ -36,10 +37,12 @@ let ageAndName: (int, string) = (24, "Lil' ReScript")
type coord3d = (float, float, float)
let my3dCoordinates: coord3d = (20.0, 30.5, 100.0)
```
+
```js
var ageAndName = [24, "Lil' ReScript"];
var my3dCoordinates = [20.0, 30.5, 100.0];
```
+
**Note**: there's no tuple of size 1. You'd just use the value itself.
@@ -53,6 +56,7 @@ To get a specific member of a tuple, destructure it:
```res example
let (_, y, _) = my3dCoordinates // now you've retrieved y
```
+
```js
var y = 30.5;
```
@@ -70,6 +74,7 @@ let coordinates1 = (10, 20, 30)
let (c1x, _, _) = coordinates1
let coordinates2 = (c1x + 50, 20, 30)
```
+
```js
var coordinates1 = [10, 20, 30];
var c1x = 10;
@@ -91,6 +96,7 @@ let getCenterCoordinates = () => {
(x, y)
}
```
+
```js
function getCenterCoordinates(param) {
var x = doSomeOperationsHere(undefined);
diff --git a/pages/docs/manual/v9.0.0/type.mdx b/pages/docs/manual/v9.0.0/type.mdx
index 905581cb1..a3ba6b4ed 100644
--- a/pages/docs/manual/v9.0.0/type.mdx
+++ b/pages/docs/manual/v9.0.0/type.mdx
@@ -7,6 +7,7 @@ canonical: "/docs/manual/latest/type"
# Type
Types are the highlight of ReScript! They are:
+
- **Strong**. A type can't change into another type. In JavaScript, your variable's type might change when the code runs (aka at runtime). E.g. a `number` variable might change into a `string` sometimes. This is an anti-feature; it makes the code much harder to understand when reading or debugging.
- **Static**. ReScript types are erased after compilation and don't exist at runtime. Never worry about your types dragging down performance. You don't need type info during runtime; we report all the information (especially all the type errors) during compile time. Catch the bugs earlier!
- **Sound**. This is our biggest differentiator versus many other typed languages that compile to JavaScript. Our type system is guaranteed to **never** be wrong. Most type systems make a guess at the type of a value and show you a type in your editor that's sometime incorrect. We don't do that. We believe that a type system that is sometime incorrect can end up being dangerous due to expectation mismatches.
@@ -25,10 +26,11 @@ This let-binding doesn't contain any written type:
let score = 10
let add = (a, b) => a + b
```
+
```js
var score = 10;
function add(a, b) {
- return a + b | 0;
+ return (a + b) | 0;
}
```
@@ -45,6 +47,7 @@ But you can also optionally write down the type, aka annotate your value:
```res example
let score: int = 10
```
+
```js
var score = 10;
```
@@ -64,10 +67,11 @@ let myInt = (5: int) + (4: int)
let add = (x: int, y: int) : int => x + y
let drawCircle = (~radius as r: int): circleType => /* code here */
```
+
```js
var myInt = 9;
function add(x, y) {
- return x + y | 0;
+ return (x + y) | 0;
}
function drawCircle(r) {
/* code here */
@@ -88,6 +92,7 @@ You can refer to a type by a different name. They'll be equivalent:
type scoreType = int
let x: scoreType = 10
```
+
```js
var x = 10;
```
@@ -110,6 +115,7 @@ type floatCoordinates = (float, float, float)
let a: intCoordinates = (10, 20, 20)
let b: floatCoordinates = (10.5, 20.5, 20.5)
```
+
```js
var a = [10, 20, 20];
var b = [10.5, 20.5, 20.5];
@@ -127,6 +133,7 @@ type coordinates<'a> = ('a, 'a, 'a)
let a: coordinates = (10, 20, 20)
let b: coordinates = (10.5, 20.5, 20.5)
```
+
```js
var a = [10, 20, 20];
var b = [10.5, 20.5, 20.5];
@@ -141,6 +148,7 @@ Note that the above codes are just contrived examples for illustration purposes.
```res example
let buddy = (10, 20, 20)
```
+
```js
var buddy = [10, 20, 20];
```
@@ -157,6 +165,7 @@ Type arguments appear in many places. Our `array<'a>` type is such a type that r
// inferred as `array`
let greetings = ["hello", "world", "how are you"]
```
+
```js
// inferred as `array`
var greetings = ["hello", "world", "how are you"];
@@ -187,20 +196,21 @@ let payloadResults: myPayloadResults = [
Error("Something wrong happened!")
]
```
+
```js
var payloadResults = [
{
- TAG: /* Ok */0,
- _0: {data: "hi"}
+ TAG: /* Ok */ 0,
+ _0: { data: "hi" },
},
{
- TAG: /* Ok */0,
- _0: {data: "bye"}
+ TAG: /* Ok */ 0,
+ _0: { data: "bye" },
},
{
- TAG: /* Error */1,
- _0: "Something wrong happened!"
- }
+ TAG: /* Error */ 1,
+ _0: "Something wrong happened!",
+ },
];
```
@@ -218,6 +228,7 @@ type rec person = {
friends: array
}
```
+
```js
// Empty output
```
@@ -234,6 +245,7 @@ Types can also be _mutually_ recursive through `and`:
type rec student = {taughtBy: teacher}
and teacher = {students: array}
```
+
```js
// Empty output
```
@@ -249,6 +261,7 @@ ReScript's type system is robust and does not allow dangerous, unsafe stuff like
```res
external myShadyConversion: myType1 => myType2 = "%identity"
```
+
```js
// Empty output
```
@@ -264,6 +277,7 @@ external convertToFloat : int => float = "%identity"
let age = 10
let gpa = 2.1 +. convertToFloat(age)
```
+
```js
var age = 10;
var gpa = 2.1 + 10;
diff --git a/pages/docs/manual/v9.0.0/unboxed.mdx b/pages/docs/manual/v9.0.0/unboxed.mdx
index 6ebe3c4b3..85a053a22 100644
--- a/pages/docs/manual/v9.0.0/unboxed.mdx
+++ b/pages/docs/manual/v9.0.0/unboxed.mdx
@@ -17,13 +17,14 @@ let studentName = Name("Joe")
type greeting = {message: string}
let hi = {message: "hello!"}
```
+
```js
-var studentName = /* Name */{
- _0: "Joe"
+var studentName = /* Name */ {
+ _0: "Joe",
};
var hi = {
- message: "hello!"
+ message: "hello!",
};
```
@@ -44,6 +45,7 @@ let studentName = Name("Joe")
type greeting = {message: string}
let hi = {message: "hello!"}
```
+
```js
var studentName = "Joe";
@@ -80,6 +82,7 @@ let playerLocalCoordinates = {x: 20.5, y: 30.5}
renderDot(playerLocalCoordinates)
```
+
```js
function renderDot(coordinates) {
console.log("Pretend to draw at:", coordinates.x, coordinates.y);
@@ -88,13 +91,13 @@ function renderDot(coordinates) {
function toWorldCoordinates(localCoordinates) {
return {
x: localCoordinates.x + 10,
- y: localCoordinates.x + 20
+ y: localCoordinates.x + 20,
};
}
var playerLocalCoordinates = {
x: 20.5,
- y: 30.5
+ y: 30.5,
};
renderDot(playerLocalCoordinates);
@@ -129,6 +132,7 @@ let playerLocalCoordinates = Local({x: 20.5, y: 30.5})
// We're forced to do this instead:
renderDot(playerLocalCoordinates->toWorldCoordinates)
```
+
```js
function renderDot(coordinates) {
console.log("Pretend to draw at:", coordinates.x, coordinates.y);
@@ -137,13 +141,13 @@ function renderDot(coordinates) {
function toWorldCoordinates(coordinates) {
return {
x: coordinates.x + 10,
- y: coordinates.x + 20
+ y: coordinates.x + 20,
};
}
var playerLocalCoordinates = {
x: 20.5,
- y: 30.5
+ y: 30.5,
};
renderDot(toWorldCoordinates(playerLocalCoordinates));
@@ -154,4 +158,3 @@ renderDot(toWorldCoordinates(playerLocalCoordinates));
Now `renderDot` only takes `worldCoordinates`. Through a nice combination of using distinct variant types + argument destructuring, we've achieved better safety **without compromising on performance**: the `unboxed` attribute compiled to clean, variant-wrapper-less JS code! Check the output.
As for a record with a single field, the use-cases are a bit more edgy. We won't mention them here.
-
diff --git a/pages/docs/manual/v9.0.0/use-illegal-identifier-names.mdx b/pages/docs/manual/v9.0.0/use-illegal-identifier-names.mdx
index a1e2eaf58..b1fc91e98 100644
--- a/pages/docs/manual/v9.0.0/use-illegal-identifier-names.mdx
+++ b/pages/docs/manual/v9.0.0/use-illegal-identifier-names.mdx
@@ -7,6 +7,7 @@ canonical: "/docs/manual/latest/use-illegal-identifier-names"
# Use Illegal Identifier Names
Sometime, for e.g. a let binding or a record field, you might want to use:
+
- A capitalized name.
- A name that contains illegal characters (e.g. emojis, hyphen, space).
- A name that's one of ReScript's reserved keywords.
@@ -32,17 +33,18 @@ let calculate = (~\"Props") => {
\"Props" + 1
}
```
+
```js
var my$$unknown$unknown$unknown$unknown = 10;
var myElement = {
- "aria-label": "close"
+ "aria-label": "close",
};
var label = myElement["aria-label"];
function calculate(Props) {
- return Props + 1 | 0;
+ return (Props + 1) | 0;
}
```
diff --git a/pages/docs/manual/v9.0.0/variant.mdx b/pages/docs/manual/v9.0.0/variant.mdx
index 5ce99deb0..4b26abfd2 100644
--- a/pages/docs/manual/v9.0.0/variant.mdx
+++ b/pages/docs/manual/v9.0.0/variant.mdx
@@ -20,8 +20,9 @@ type myResponse =
let areYouCrushingIt = Yes
```
+
```js
-var areYouCrushingIt = /* Yes */0;
+var areYouCrushingIt = /* Yes */ 0;
```
@@ -40,6 +41,7 @@ If the variant you're using is in a different file, bring it into scope like you
// Zoo.res
type animal = Dog | Cat | Bird
```
+
```js
// Empty output
```
@@ -54,9 +56,10 @@ let pet: Zoo.animal = Dog // preferred
// or
let pet2 = Zoo.Dog
```
+
```js
-var pet = /* Dog */0;
-var pet2 = /* Dog */0;
+var pet = /* Dog */ 0;
+var pet2 = /* Dog */ 0;
```
@@ -73,6 +76,7 @@ type account =
| Instagram(string)
| Facebook(string, int)
```
+
```js
// Empty output
```
@@ -87,15 +91,16 @@ Here, `Instagram` holds a `string`, and `Facebook` holds a `string` and an `int`
let myAccount = Facebook("Josh", 26)
let friendAccount = Instagram("Jenny")
```
+
```js
var myAccount = {
- TAG: /* Facebook */1,
+ TAG: /* Facebook */ 1,
_0: "Josh",
- _1: 26
+ _1: 26,
};
var friendAccount = {
- TAG: /* Instagram */0,
- _0: "Jenny"
+ TAG: /* Instagram */ 0,
+ _0: "Jenny",
};
```
@@ -114,11 +119,12 @@ type user =
let me = Id({name: "Joe", password: "123"})
```
+
```js
var me = {
- TAG: /* Id */1,
+ TAG: /* Id */ 1,
name: "Joe",
- password: "123"
+ password: "123",
};
```
@@ -138,13 +144,14 @@ type user =
let me = Id({name: "Joe", password: "123"})
```
+
```js
var me = {
- TAG: /* Id */1,
+ TAG: /* Id */ 1,
_0: {
name: "Joe",
- password: "123"
- }
+ password: "123",
+ },
};
```
@@ -192,40 +199,41 @@ type adventurer = Warrior(s) | Wizard(string)
let a1 = Warrior({score: 10.5})
let a2 = Wizard("Joe")
```
+
```js
-var g1 = /* Hello */0;
-var g2 = /* Goodbye */1;
+var g1 = /* Hello */ 0;
+var g2 = /* Goodbye */ 1;
-var o1 = /* Good */0;
-var o2 = /* Error */{
- _0: "oops!"
+var o1 = /* Good */ 0;
+var o2 = /* Error */ {
+ _0: "oops!",
};
-var f1 = /* Child */0;
+var f1 = /* Child */ 0;
var f2 = {
- TAG: /* Mom */0,
+ TAG: /* Mom */ 0,
_0: 30,
- _1: "Jane"
+ _1: "Jane",
};
var f3 = {
- TAG: /* Dad */1,
- _0: 32
+ TAG: /* Dad */ 1,
+ _0: 32,
};
-var p1 = /* Teacher */0;
-var p2 = /* Student */{
- gpa: 99.5
+var p1 = /* Teacher */ 0;
+var p2 = /* Student */ {
+ gpa: 99.5,
};
var a1 = {
- TAG: /* Warrior */0,
+ TAG: /* Warrior */ 0,
_0: {
- score: 10.5
- }
+ score: 10.5,
+ },
};
var a2 = {
- TAG: /* Wizard */1,
- _0: "Joe"
+ TAG: /* Wizard */ 1,
+ _0: "Joe",
};
```
@@ -243,6 +251,7 @@ type account =
type account2 =
| Instagram((string, int)) // 1 argument - happens to be a 2-tuple
```
+
```js
// Empty output
```
@@ -277,6 +286,7 @@ let betterDraw = (animal) =>
betterDraw(MyFloat(1.5))
```
+
```js
var MyLibrary = require("myLibrary");
@@ -285,8 +295,8 @@ function betterDraw(animal) {
}
betterDraw({
- TAG: /* MyFloat */0,
- _0: 1.5
+ TAG: /* MyFloat */ 0,
+ _0: 1.5,
});
```
@@ -300,6 +310,7 @@ betterDraw({
@bs.module("myLibrary") external drawFloat: float => unit = "draw"
@bs.module("myLibrary") external drawString: string => unit = "draw"
```
+
```js
// Empty output
```
@@ -344,10 +355,11 @@ switch data {
| Bird => Js.log("Kashiiin")
}
```
+
```js
console.log("Wof");
-var data = /* Dog */0;
+var data = /* Dog */ 0;
```
diff --git a/pages/docs/react/latest/arrays-and-keys.mdx b/pages/docs/react/latest/arrays-and-keys.mdx
index 869804f28..6f27203fc 100644
--- a/pages/docs/react/latest/arrays-and-keys.mdx
+++ b/pages/docs/react/latest/arrays-and-keys.mdx
@@ -38,21 +38,25 @@ function Playground(props) {
var todos = [
{
id: "todo1",
- text: "Todo 1"
+ text: "Todo 1",
},
{
id: "todo2",
- text: "Todo 2"
- }
+ text: "Todo 2",
+ },
];
var items = todos.map(function (todo) {
- return JsxRuntime.jsx("li", {
- children: todo.text
- }, todo.id);
- });
+ return JsxRuntime.jsx(
+ "li",
+ {
+ children: todo.text,
+ },
+ todo.id,
+ );
+ });
return JsxRuntime.jsx("ul", {
- children: items
- });
+ children: items,
+ });
}
```
@@ -73,19 +77,17 @@ let items = Array.map(numbers, (number) => {
```
```js
-var numbers = [
- 1,
- 2,
- 3,
- 4,
- 5
-];
+var numbers = [1, 2, 3, 4, 5];
var items = numbers.map(function (number) {
- return JsxRuntime.jsx("li", {
- children: number
- }, number.toString());
- });
+ return JsxRuntime.jsx(
+ "li",
+ {
+ children: number,
+ },
+ number.toString(),
+ );
+});
```
@@ -111,19 +113,23 @@ let items = Array.map(todos, todo => {
var todos = [
{
id: "todo1",
- text: "Todo 1"
+ text: "Todo 1",
},
{
id: "todo2",
- text: "Todo 2"
- }
+ text: "Todo 2",
+ },
];
var items = todos.map(function (todo) {
- return JsxRuntime.jsx("li", {
- children: todo.text
- }, todo.id);
- });
+ return JsxRuntime.jsx(
+ "li",
+ {
+ children: todo.text,
+ },
+ todo.id,
+ );
+});
```
@@ -143,15 +149,18 @@ let items = Array.mapWithIndex(todos, (todo, i) => {
```js
var items = todos.map(function (todo, i) {
- return JsxRuntime.jsx("li", {
- children: todo.text
- }, i.toString());
- });
+ return JsxRuntime.jsx(
+ "li",
+ {
+ children: todo.text,
+ },
+ i.toString(),
+ );
+});
```
-
### Keys Must Only Be Unique Among Siblings
Keys used within arrays should be unique among their siblings. However they don’t need to be globally unique. We can use the same keys when we produce two different arrays:
@@ -206,58 +215,61 @@ let blog =
function Playground$Blog(props) {
var posts = props.posts;
var sidebar = JsxRuntime.jsx("ul", {
- children: posts.map(function (post) {
- return JsxRuntime.jsx("li", {
- children: post.title
- }, post.id);
- })
- });
+ children: posts.map(function (post) {
+ return JsxRuntime.jsx(
+ "li",
+ {
+ children: post.title,
+ },
+ post.id,
+ );
+ }),
+ });
var content = posts.map(function (post) {
- return JsxRuntime.jsxs("div", {
- children: [
- JsxRuntime.jsx("h3", {
- children: post.title
- }),
- JsxRuntime.jsx("p", {
- children: post.content
- })
- ]
- }, post.id);
- });
+ return JsxRuntime.jsxs(
+ "div",
+ {
+ children: [
+ JsxRuntime.jsx("h3", {
+ children: post.title,
+ }),
+ JsxRuntime.jsx("p", {
+ children: post.content,
+ }),
+ ],
+ },
+ post.id,
+ );
+ });
return JsxRuntime.jsxs("div", {
- children: [
- sidebar,
- JsxRuntime.jsx("hr", {}),
- content
- ]
- });
+ children: [sidebar, JsxRuntime.jsx("hr", {}), content],
+ });
}
var Blog = {
- make: Playground$Blog
+ make: Playground$Blog,
};
var posts = [
{
id: "1",
title: "Hello World",
- content: "Welcome to learning ReScript & React!"
+ content: "Welcome to learning ReScript & React!",
},
{
id: "2",
title: "Installation",
- content: "You can install reason-react from npm."
- }
+ content: "You can install reason-react from npm.",
+ },
];
var blog = JsxRuntime.jsx(Playground$Blog, {
- posts: posts
- });
+ posts: posts,
+});
```
-
## Rendering `list` Values
In case you ever want to render a `list` of items, you can do something like this:
@@ -289,25 +301,29 @@ let make = () => {
```js
function Playground(props) {
var items = Core__List.toArray({
- hd: {
- id: "todo1",
- text: "Todo 1"
- },
- tl: {
- hd: {
- id: "todo2",
- text: "Todo 2"
- },
- tl: /* [] */0
- }
- }).map(function (todo) {
- return JsxRuntime.jsx("li", {
- children: todo.text
- }, todo.id);
- });
+ hd: {
+ id: "todo1",
+ text: "Todo 1",
+ },
+ tl: {
+ hd: {
+ id: "todo2",
+ text: "Todo 2",
+ },
+ tl: /* [] */ 0,
+ },
+ }).map(function (todo) {
+ return JsxRuntime.jsx(
+ "li",
+ {
+ children: todo.text,
+ },
+ todo.id,
+ );
+ });
return JsxRuntime.jsx("div", {
- children: items
- });
+ children: items,
+ });
}
```
@@ -316,4 +332,3 @@ function Playground(props) {
We use `List.toArray` to convert our list to an array before creating our `array`. Please note that using `list` has performance impact due to extra conversion costs.
99% of the time you'll want to use arrays (seamless interop, faster JS code), but in some cases it might make sense to use a `list` to leverage advanced pattern matching features etc.
-
diff --git a/pages/docs/react/latest/beyond-jsx.mdx b/pages/docs/react/latest/beyond-jsx.mdx
index 01816cb0d..ee2afa0b9 100644
--- a/pages/docs/react/latest/beyond-jsx.mdx
+++ b/pages/docs/react/latest/beyond-jsx.mdx
@@ -18,7 +18,7 @@ JSX is a syntax sugar that allows us to use React components in an HTML like man
## Component Types
-A plain React component is defined as a `('props) => React.element` function. You can also express a component more efficiently with our shorthand type `React.component<'props>`.
+A plain React component is defined as a `('props) => React.element` function. You can also express a component more efficiently with our shorthand type `React.component<'props>`.
Here are some examples on how to define your own component types (often useful when interoping with existing JS code, or passing around components):
@@ -32,6 +32,7 @@ type friendComp = friend => React.element
type props = {padding: string, children: React.element}
type containerComp = React.component
```
+
The types above are pretty low level (basically the JS representation of a React component), but since ReScript React has its own ways of defining React components in a more language specific way, let's have a closer look on the anatomy of such a construct.
## JSX Component Interface
@@ -66,6 +67,7 @@ module Friend = {
}
}
```
+
```res example
module Friend = {
type props<'name, 'children> = {
@@ -78,18 +80,16 @@ module Friend = {
}
}
```
+
```js
function Playground$Friend(props) {
return JsxRuntime.jsxs("div", {
- children: [
- props.name,
- props.children
- ]
- });
+ children: [props.name, props.children],
+ });
}
var Friend = {
- make: Playground$Friend
+ make: Playground$Friend,
};
```
@@ -104,7 +104,6 @@ In the expanded output:
The `@react.component` decorator also works for `React.forwardRef` calls:
-
```res
@@ -140,13 +139,14 @@ So now that we know how the ReScript React component transformation works, let's
## JSX Under the Hood
-Whenever we are using JSX with a custom component ("capitalized JSX"), we are actually using `React.createElement` to create a new element. Here is an example of a React component without children:
+Whenever we are using JSX with a custom component ("capitalized JSX"), we are actually using `React.createElement` to create a new element. Here is an example of a React component without children:
```res example
let _ =
```
+
```res example
// classic
React.createElement(Friend.make, {name: "Fred", age:20})
@@ -154,6 +154,7 @@ React.createElement(Friend.make, {name: "Fred", age:20})
// automatic
React.jsx(Friend.make, {name: "Fred", age: 20})
```
+
```js
JsxRuntime.jsx(Playground$Friend, { name: "Fred", age: 20 });
```
@@ -194,10 +195,9 @@ JsxRuntime.jsx(Container, { width: 200, children: null }, "Hello", "World");
Note that the `children: React.null` field has no relevance since React will only care about the children array passed as a third argument.
-
### Dom Elements
-"Uncapitalized JSX" expressions are treated as DOM elements and will be converted to `ReactDOM.createDOMElementVariadic` calls:
+"Uncapitalized JSX" expressions are treated as DOM elements and will be converted to `ReactDOM.createDOMElementVariadic` calls:
@@ -243,15 +243,19 @@ ReactDOM.jsx("div", {title: "test", children: ?ReactDOM.someElement(ReactDOM.jsx
```js
JsxRuntime.jsx("div", {
- children: JsxRuntime.jsx("span", {}),
- title: "test"
- });
+ children: JsxRuntime.jsx("span", {}),
+ title: "test",
+});
```
```js
-React.createElement("div", {
- title: "test"
- }, React.createElement("span", undefined));
+React.createElement(
+ "div",
+ {
+ title: "test",
+ },
+ React.createElement("span", undefined),
+);
```
diff --git a/pages/docs/react/latest/components-and-props.mdx b/pages/docs/react/latest/components-and-props.mdx
index fc3ab0d87..02b87ed12 100644
--- a/pages/docs/react/latest/components-and-props.mdx
+++ b/pages/docs/react/latest/components-and-props.mdx
@@ -8,13 +8,13 @@ canonical: "/docs/react/latest/components-and-props"
-Components let you split the UI into independent, reusable pieces, and think about each piece in isolation. This page provides an introduction to the idea of components.
+Components let you split the UI into independent, reusable pieces, and think about each piece in isolation. This page provides an introduction to the idea of components.
## What is a Component?
-A React component is a function describing a UI element that receives a `props` object as a parameter (data describing the dynamic parts of the UI) and returns a `React.element`.
+A React component is a function describing a UI element that receives a `props` object as a parameter (data describing the dynamic parts of the UI) and returns a `React.element`.
The nice thing about this concept is that you can solely focus on the input and output. The component function receives some data and returns some opaque `React.element` that is managed by the React framework to render your UI.
@@ -35,12 +35,13 @@ let make = () => {
}
```
+
```js
import * as React from "react";
function Greeting(props) {
return JsxRuntime.jsx("div", {
- children: "Hello ReScripters!"
+ children: "Hello ReScripters!",
});
}
@@ -53,7 +54,7 @@ var make = Greeting;
We've created a `Greeting.res` file that contains a `make` function that doesn't receive any props (the function doesn't receive any parameters), and returns a `React.element` that represents `` transforms into a `JsxRuntime.jsx("div",...)` call in JavaScript.
+You can also see in the the JS output that the function we created was directly translated into the pure JS version of a ReactJS component. Note how a `
` transforms into a `JsxRuntime.jsx("div",...)` call in JavaScript.
## Defining Props
@@ -73,12 +74,19 @@ let make = (~title: string, ~visitorCount: int, ~children: React.element) => {
}
```
+
```js
import * as React from "react";
function Article(props) {
var visitorCountMsg = "You are visitor number: " + String(props.visitorCount);
- return React.createElement("div", undefined, React.createElement("div", undefined, props.title), React.createElement("div", undefined, visitorCountMsg), props.children);
+ return React.createElement(
+ "div",
+ undefined,
+ React.createElement("div", undefined, props.title),
+ React.createElement("div", undefined, visitorCountMsg),
+ props.children,
+ );
}
var make = Article;
@@ -114,7 +122,7 @@ function Greeting(props) {
-**Note:** The `@react.component` attribute implicitly adds the last `()` parameter to our `make` function for us (no need to do it ourselves).
+**Note:** The `@react.component` attribute implicitly adds the last `()` parameter to our `make` function for us (no need to do it ourselves).
In JSX, you can apply optional props with some special syntax:
@@ -141,7 +149,7 @@ let name = Some("Andrea")
var name = "Andrea";
React.createElement(Greeting, {
- name: name
+ name: name,
});
```
@@ -155,13 +163,12 @@ Check out the corresponding [Arrays and Keys](./arrays-and-keys) and [Forwarding
### Handling Invalid Prop Names (e.g. keywords)
-Prop names like `type` (as in `
`) aren't syntactically valid; `type` is a reserved keyword in ReScript. Use `
` instead.
+Prop names like `type` (as in `
`) aren't syntactically valid; `type` is a reserved keyword in ReScript. Use `
` instead.
For `aria-*` use camelCasing, e.g., `ariaLabel`. For DOM components, we'll translate it to `aria-label` under the hood.
For `data-*` this is a bit trickier; words with `-` in them aren't valid in ReScript. When you do want to write them, e.g., `
`, check out the [React.cloneElement](./elements-and-jsx#cloning-elements) or [React.createDOMElementVariadic](./elements-and-jsx#creating-dom-elements) section.
-
## Children Props
In React `props.children` is a special attribute to represent the nested elements within a parent element:
@@ -197,13 +204,17 @@ function MyList(props) {
}
var MyList = {
- make: MyList
+ make: MyList,
};
-React.createElement(MyList, {
- children: null
- }, React.createElement("li", undefined, "Item 1"),
- React.createElement("li", undefined, "Item 2"));
+React.createElement(
+ MyList,
+ {
+ children: null,
+ },
+ React.createElement("li", undefined, "Item 1"),
+ React.createElement("li", undefined, "Item 2"),
+);
```
@@ -273,7 +284,6 @@ The best way to approach this kind of issue is by using props instead of childre
**The best use-case for `children` is to pass down `React.element`s without any semantic order or implementation details!**
-
## @react decorators
You might've wondered what `@react.component` actually does.
@@ -325,10 +335,7 @@ import * as JsxRuntime from "react/jsx-runtime";
function Counter(props) {
return JsxRuntime.jsxs("h1", {
- children: [
- props.title,
- props.count
- ]
+ children: [props.title, props.count],
});
}
@@ -339,11 +346,10 @@ let make = Counter;
## Props & Type Inference
-The ReScript type system is really good at inferring the prop types just by looking at its prop usage.
+The ReScript type system is really good at inferring the prop types just by looking at its prop usage.
For simple cases, well-scoped usage, or experimentation, it's still fine to omit type annotations:
-
```res example
// Button.res
@@ -376,12 +382,17 @@ let make = () => {
}
```
+
```js
var React = require("react");
-var Greeting = require("./Greeting.js")
+var Greeting = require("./Greeting.js");
function App(Props) {
- return React.createElement("div", undefined, React.createElement(Greeting.make, {}));
+ return React.createElement(
+ "div",
+ undefined,
+ React.createElement(Greeting.make, {}),
+ );
}
var make = App;
@@ -391,7 +402,6 @@ var make = App;
**Note:** React components are capitalized; primitive DOM elements like `div` or `button` are uncapitalized. More infos on the JSX specifics and code transformations can be found in our [JSX language manual section](/docs/manual/latest/jsx#capitalized-tag).
-
### Handwritten Components
You don't need to use the `@react.component` decorator to write components that can be used in JSX. Instead you can write the `make` function with type `props` and these will always work as React components. But then you will have the issue with the component name being "make" in the React dev tools.
@@ -403,8 +413,8 @@ For example:
```res example
module Link = {
type props = {href: string, children: React.element};
-
- let make = (props: props) => {
+
+ let make = (props: props) => {