### Rescript WeakMap make example Source: https://rescript-lang.org/docs/manual/api/stdlib/weakmap Demonstrates creating an empty WeakMap. Subsequent gets on non-existent keys will return None. ```rescript let cache = WeakMap.make() WeakMap.get(cache, Object.make()) == None ``` -------------------------------- ### Create a New ReScript Project with npm Source: https://rescript-lang.org/docs/manual/installation Use this command to start a new ReScript project with a Next.js or Vite template. Follow the on-screen prompts for setup. ```bash npm create rescript-app@latest ``` -------------------------------- ### String.make Examples Source: https://rescript-lang.org/docs/manual/api/stdlib/string Converts a value to its string representation. ```rescript String.make(3.5) == "3.5" String.make([1, 2, 3]) == "1,2,3" ``` -------------------------------- ### Rescript WeakMap get example Source: https://rescript-lang.org/docs/manual/api/stdlib/weakmap Demonstrates retrieving a value from a WeakMap using its key. Returns Some(value) if the key exists, otherwise None. ```rescript let cache = WeakMap.make() let key = Object.make() WeakMap.get(cache, key) == None let _ = WeakMap.set(cache, key, "user") WeakMap.get(cache, key) == Some("user") ``` -------------------------------- ### ReScript Exception Analysis Example Source: https://rescript-lang.org/docs/manual/editor-plugins Demonstrates how the ReScript exception analysis reports warnings when an exception is thrown and not caught. This example shows the basic setup for triggering a warning. ```rescript let throws = () => throw(Not_found) ``` -------------------------------- ### String.indexOfFrom Examples Source: https://rescript-lang.org/docs/manual/api/stdlib/string Finds the index of a substring starting from a specified position. Returns -1 if not found. ```rescript String.indexOfFrom("bookseller", "ok", 1) == 2 String.indexOfFrom("bookseller", "sell", 2) == 4 String.indexOfFrom("bookseller", "sell", 5) == -1 ``` -------------------------------- ### Belt.List.mapWithIndex Example Source: https://rescript-lang.org/docs/manual/api/belt/list Applies a function to each element along with its index. The function takes the index (starting from 0) and the element as arguments. ```rescript list{1, 2, 3}->Belt.List.mapWithIndex((index, x) => index + x) == list{1, 3, 5} ``` -------------------------------- ### Install ReScript Manually Source: https://rescript-lang.org/docs/manual/installation Install ReScript as a local dependency in an existing JavaScript project. ```bash npm install rescript ``` -------------------------------- ### Pad string start Source: https://rescript-lang.org/docs/manual/api/stdlib/string Pads the current string with a given string (repeated as necessary) until the resulting string reaches the specified length. Padding is applied from the start. ```rescript String.padStart("abc", 5, " ") == " abc" String.padStart("abc", 6, "123465") == "123abc" ``` -------------------------------- ### Belt.Range.forEach Source: https://rescript-lang.org/docs/manual/api/belt/range Executes an action for each integer in the inclusive range `[start, finish]`. This is equivalent to `Belt.Array.forEach(Belt.Array.range(start, finish), action)`. ```APIDOC ## Belt.Range.forEach ### Description Executes an action for each integer in the inclusive range `[start, finish]`. ### Signature `let forEach: (int, int, int => unit) => unit` ### Equivalent `Belt.Array.forEach(Belt.Array.range(start, finish), action)` ### Examples ```res Belt.Range.forEach(0, 4, i => Js.log(i)) // Prints: // 0 // 1 // 2 // 3 // 4 ``` ``` -------------------------------- ### JavaScript Default Export Example Source: https://rescript-lang.org/docs/manual/import-from-export-to-js This demonstrates a standard JavaScript default export. ```javascript // student.js export default name = "Al"; ``` -------------------------------- ### String.length Examples Source: https://rescript-lang.org/docs/manual/api/stdlib/string Returns the length of a given string. ```rescript String.length("abcd") == 4 ``` -------------------------------- ### Implement a Generic JSX Transform Module (Preact Example) Source: https://rescript-lang.org/docs/manual/jsx This is a comprehensive example of implementing a generic JSX transform module for Preact. It includes type definitions and external function bindings for Preact's JSX runtime. Adapt the '@module' values for other frameworks. ```rescript `// Preact.res /* Below is a number of aliases to the common `Jsx` module */ type element = Jsx.element type component<'props> = Jsx.component<'props> type componentLike<'props, 'return> = Jsx.componentLike<'props, 'return> @module("preact/jsx-runtime") external jsx: (component<'props>, 'props) => element = "jsx" @module("preact/jsx-runtime") external jsxKeyed: (component<'props>, 'props, ~key: string=?, @ignore unit) => element = "jsx" @module("preact/jsx-runtime") external jsxs: (component<'props>, 'props) => element = "jsxs" @module("preact/jsx-runtime") 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 define though is `array`, which the JSX transform will output. */ external array: array => element = "%identity" @val external null: element = "null" external float: float => element = "%identity" external int: int => element = "%identity" external string: string => element = "%identity" external promise: promise => element = "%identity" /* These are needed for Fragment (<> ) support */ type fragmentProps = {children?: element} @module("preact/jsx-runtime") external jsxFragment: component = "Fragment" /* The Elements module is the equivalent to the ReactDOM module in Preact. 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 autocompletion etc for your specific type. */ type props = JsxDOM.domProps @module("preact/jsx-runtime") external jsx: (string, props) => Jsx.element = "jsx" @module("preact/jsx-runtime") external div: (string, props) => Jsx.element = "jsx" @module("preact/jsx-runtime") external jsxKeyed: (string, props, ~key: string=?, @ignore unit) => Jsx.element = "jsx" @module("preact/jsx-runtime") external jsxs: (string, props) => Jsx.element = "jsxs" @module("preact/jsx-runtime") external jsxsKeyed: (string, props, ~key: string=?, @ignore unit) => Jsx.element = "jsxs" external someElement: element => option = "%identity" } ` ``` -------------------------------- ### Get the next match starting index Source: https://rescript-lang.org/docs/manual/api/stdlib/regexp Use `RegExp.lastIndex` to get the index where the next search for a match will begin. This is particularly relevant for global regular expressions. ```rescript // Match the first word in a sentence let regexp = RegExp.fromString("\\w+") let someStr = "Many words here." Console.log(regexp->RegExp.lastIndex) // Logs `0` to the console regexp->RegExp.exec(someStr)->ignore Console.log(regexp->RegExp.lastIndex) // Logs `4` to the console ``` -------------------------------- ### HashMap Creation and Usage Source: https://rescript-lang.org/docs/manual/api/belt/hashmap Demonstrates how to create and initialize HashMaps with different hash identities, and how to add elements. ```APIDOC ## HashMap Overview A **mutable** Hash map which allows customized `hash` behavior. All data are parameterized by not its only type but also a unique identity in the time of initialization, so that two _HashMaps of ints_ initialized with different _hash_ functions will have different type. ### Examples ```res type t = int module I0 = Belt.Id.unpack(Belt.Id.hashable(~hash=(_: t) => 0xff_ff, ~eq=(a, b) => a == b)) let s0: Belt.HashMap.t = Belt.HashMap.make(~hintSize=40, ~id=module(I0)) module I1 = Belt.Id.unpack(Belt.Id.hashable(~hash=(_: t) => 0xff, ~eq=(a, b) => a == b)) let s1: Belt.HashMap.t = Belt.HashMap.make(~hintSize=40, ~id=module(I1)) let () = { Belt.HashMap.set(s0, 0, 3) Belt.HashMap.set(s1, 1, "3") } ``` ``` -------------------------------- ### Math.sinh Examples Source: https://rescript-lang.org/docs/manual/api/stdlib/math Demonstrates the usage of the Math.sinh function for calculating hyperbolic sine. ```rescript Math.sinh(-0.0) == -0.0 Math.sinh(0.0) == 0.0 Math.sinh(1.0) == 1.1752011936438014 ``` -------------------------------- ### JavaScript Default Import Example Source: https://rescript-lang.org/docs/manual/import-from-export-to-js This shows how to import a default export in JavaScript. ```javascript // teacher.js import studentName from "student.js"; ``` -------------------------------- ### Create and Initialize Belt.Set Source: https://rescript-lang.org/docs/manual/api/belt/set Demonstrates creating an empty set with a custom comparator and initializing a set from an array. ```rescript module IntCmp = Belt.Id.MakeComparable({ type t = int let cmp = Pervasives.compare }) let s0 = Belt.Set.make(~id=module(IntCmp)) let s1 = Belt.Set.fromArray([3, 2, 1, 5], ~id=module(IntCmp)) s0->Belt.Set.minUndefined->Js.Undefined.toOption == None s1->Belt.Set.minUndefined->Js.Undefined.toOption == Some(1) ``` -------------------------------- ### getExn Example Source: https://rescript-lang.org/docs/manual/api/stdlib/result Demonstrates extracting the Ok value or throwing an exception. Use when you expect the Result to be Ok and want to fail fast otherwise. ```rescript Result.getExn(Result.Ok(42)) == 42 switch Result.getExn(Error("Invalid data")) { | exception _ => true | _ => false } == true switch Result.getExn(Error("Invalid data"), ~message="was Error!") { | exception _ => true // Throws a JsError with the message "was Error!" | _ => false } == true ``` -------------------------------- ### Belt.List.reduceWithIndex Example Source: https://rescript-lang.org/docs/manual/api/belt/list Applies a function to each element of a list, accumulating a result with access to the element's index. The accumulator starts with an initial value. ```rescript list{1, 2, 3, 4}->Belt.List.reduceWithIndex(0, (acc, item, index) => acc + item + index) == 16 ``` -------------------------------- ### Run a ReScript Demo File Source: https://rescript-lang.org/docs/manual/installation If you selected the 'basic' template, use this command to execute a ReScript demo file after compilation. ```bash node src/Demo.res.mjs ``` -------------------------------- ### padStart Source: https://rescript-lang.org/docs/manual/api/stdlib/string Pads the current string with a given string (repeated, if needed) until the resulting string reaches the given length. Padding is applied from the start. ```APIDOC ## padStart RES `let padStart: (string, int, string) => string` `padStart(str, n, padStr)` returns a string that has been padded with `padStr` (multiple times, if needed) until the resulting string reaches the given `n` length. The padding is applied from the start of the current string. See `String.padStart` on MDN. ### Examples ```res String.padStart("abc", 5, " ") == " abc" String.padStart("abc", 6, "123465") == "123abc" ``` ``` -------------------------------- ### Get DataView Byte Offset Source: https://rescript-lang.org/docs/manual/api/stdlib/dataview Returns the starting byte position of the DataView within its ArrayBuffer. This is useful when a DataView represents a slice of a larger buffer. ```rescript let array_buffer = ArrayBuffer.make(16) let dv = DataView.fromBuffer(array_buffer, ~byteOffset=4) DataView.byteOffset(dv) == 4 ``` -------------------------------- ### Display ReScript Help Information Source: https://rescript-lang.org/docs/manual/build-overview Run `rescript help` to display available options and subcommands for the ReScript build tool. Use `rescript -h` for subcommand-specific help. ```bash rescript help ``` -------------------------------- ### Belt.List.reduceReverse Example Source: https://rescript-lang.org/docs/manual/api/belt/list Reduces a list to a single value by applying a function from end to beginning. The function takes an accumulator and the current element. The accumulator starts with an initial value. ```rescript list{1, 2, 3, 4}->Belt.List.reduceReverse(0, (a, b) => a + b) == 10 ``` ```rescript list{1, 2, 3, 4}->Belt.List.reduceReverse(10, (a, b) => a - b) == 0 ``` ```rescript list{1, 2, 3, 4}->Belt.List.reduceReverse(list{}, Belt.List.add) == list{1, 2, 3, 4} ``` -------------------------------- ### make Source: https://rescript-lang.org/docs/manual/api/belt/hashset/string Creates a new hash set with a specified hint for the initial size. ```APIDOC ## make ### Description Creates a new hash set with a specified hint for the initial size. ### Signature `let make: (~hintSize: int) => t` ``` -------------------------------- ### make Source: https://rescript-lang.org/docs/manual/api/belt/hashmap/string Creates a new, empty HashMap with a specified hint for the initial size. ```APIDOC ## make ### Description Creates a new, empty HashMap with a specified hint for the initial size. ### Signature `let make: (~hintSize: int) => t<'b>` ``` -------------------------------- ### Belt.List.reduce Example Source: https://rescript-lang.org/docs/manual/api/belt/list Reduces a list to a single value by applying a function from beginning to end. The function takes an accumulator and the current element. The accumulator starts with an initial value. ```rescript list{1, 2, 3, 4}->Belt.List.reduce(0, (a, b) => a + b) == 10 ``` ```rescript list{1, 2, 3, 4}->Belt.List.reduce(0, (acc, item) => acc + item) == 10 ``` -------------------------------- ### Creating Promises with Promise.make, Promise.resolve, and Promise.reject Source: https://rescript-lang.org/docs/manual/promise Shows how to create promises using `Promise.make` for custom logic, `Promise.resolve` for immediate resolution, and `Promise.reject` for immediate rejection with an exception. ```rescript let p1 = Promise.make((resolve, reject) => { resolve("hello world") }) let p2 = Promise.resolve("some value") // You can only reject `exn` values for streamlined catch handling exception MyOwnError(string) let p3 = Promise.reject(MyOwnError("some rejection")) ``` -------------------------------- ### Troubleshoot Monorepo Build with Verbose Flag Source: https://rescript-lang.org/docs/manual/build-monorepo-setup Use the `-v` flag during the build process to get detailed information about how Rewatch interprets the project structure and configuration files. This is helpful for diagnosing monorepo setup issues. ```bash rescript build -v ``` -------------------------------- ### Check if string starts with substring from an index Source: https://rescript-lang.org/docs/manual/api/stdlib/string Checks if a string starts with a substring from a specific index. Negative indices are treated as the start of the string. ```rescript String.startsWithFrom("BuckleScript", "kle", 3) == true String.startsWithFrom("BuckleScript", "", 3) == true String.startsWithFrom("JavaScript", "Buckle", 2) == false ``` -------------------------------- ### make Source: https://rescript-lang.org/docs/manual/api/belt/list Creates a list of a specified length, with all elements initialized to a given value. ```APIDOC ## make RES `let make: (int, 'a) => t<'a>` Returns a list of length `numItems` with each element filled with value `v`. Returns an empty list if `numItems` is negative. ### Examples ``` RES Belt.List.make(3, 1) == list{1, 1, 1} ``` ``` -------------------------------- ### includesFrom Source: https://rescript-lang.org/docs/manual/api/stdlib/string `includesFrom(str, searchValue, start)` returns `true` if `searchValue` is found within `str` starting at character position `start`, `false` otherwise. ```APIDOC ## includesFrom RES `let includesFrom: (string, string, int) => bool` `includesFrom(str, searchValue, start)` returns `true` if `searchValue` is found anywhere within `str` starting at character number `start` (where 0 is the first character), `false` otherwise. See `String.includes` on MDN. ### Examples ``` RES String.includesFrom("programmer", "gram", 1) == true String.includesFrom("programmer", "gram", 4) == false String.includesFrom(`대한민국`, `한`, 1) == true ``` ``` -------------------------------- ### make Source: https://rescript-lang.org/docs/manual/api/belt/hashset/int Creates a new hash set with an optional hint for the initial size. ```APIDOC ## make ### Description Creates a new hash set with an optional hint for the initial size. ### Signature `let make: (~hintSize: int) => t` ``` -------------------------------- ### Dependencies Source: https://rescript-lang.org/docs/manual/build-configuration-schema An array of build system dependencies. ```json { "type": "array", "items": { "$ref": "https://raw.githubusercontent.com/rescript-lang/rescript/master/docs/docson/build-schema.json#/definitions/bs-dependency" } } ``` -------------------------------- ### indexOfFrom Source: https://rescript-lang.org/docs/manual/api/stdlib/string `indexOfFrom(str, searchValue, start)` returns the position of the first occurrence of `searchValue` within `str` starting at character position `start`, or `-1` if not found in that portion. ```APIDOC ## indexOfFrom RES `let indexOfFrom: (string, string, 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` on MDN. ``` -------------------------------- ### make Source: https://rescript-lang.org/docs/manual/api/belt/hashmap/int Creates a new hash map with a specified hint for the initial size. ```APIDOC ## make ### Description Creates a new hash map with a specified hint for the initial size. ### Signature `let make: (~hintSize: int) => t<'b>` ``` -------------------------------- ### Create an inclusive range of integers Source: https://rescript-lang.org/docs/manual/api/belt/array Use `range` to create an array of integers starting from `start` and ending at `finish`, inclusive. If `start` is greater than `finish`, an empty array is returned. ```rescript Belt.Array.range(0, 3) == [0, 1, 2, 3] ``` ```rescript Belt.Array.range(3, 0) == [] ``` ```rescript Belt.Array.range(3, 3) == [3] ``` -------------------------------- ### Create a New Map with a Comparator Source: https://rescript-lang.org/docs/manual/api/belt/map Use `Belt.Map.make` to initialize an empty map. You must provide a comparator function for the key type. ```rescript module IntCmp = Belt.Id.MakeComparable({ type t = int let cmp = (a, b) => Pervasives.compare(a, b) }) let m = Belt.Map.make(~id=module(IntCmp)) Belt.Map.set(m, 0, "a") ``` -------------------------------- ### make Source: https://rescript-lang.org/docs/manual/api/belt/hashmap Creates a new hash map. It requires a hintSize for initial capacity and an id module for key comparison and hashing. ```APIDOC ## make ### Description Creates a new map by taking in the comparator and `hintSize`. ### Signature `let make: (~hintSize: int, ~id: id<'key, 'id>) => t<'key, 'value, 'id>` ### Example ```res module IntHash = Belt.Id.MakeHashable({ type t = int let hash = a => a let eq = (a, b) => a == b }) let hMap = Belt.HashMap.make(~hintSize=10, ~id=module(IntHash)) Belt.HashMap.set(hMap, 0, "a") ``` ``` -------------------------------- ### Slice a string from a start index to the end Source: https://rescript-lang.org/docs/manual/api/stdlib/string Extracts a substring from a specified start index to the end of the string. Negative indices count from the end. If the start index is beyond the string length, an empty string is returned. ```rescript String.sliceToEnd("abcdefg", ~start=4) == "efg" String.sliceToEnd("abcdefg", ~start=-2) == "fg" String.sliceToEnd("abcdefg", ~start=7) == "" ``` -------------------------------- ### getOr Example Source: https://rescript-lang.org/docs/manual/api/stdlib/result Shows how to provide a default value when the Result is an Error. This is useful for safely accessing a value without crashing. ```rescript Result.getOr(Ok(42), 0) == 42 Result.getOr(Error("Invalid Data"), 0) == 0 ``` -------------------------------- ### get Source: https://rescript-lang.org/docs/manual/api/stdlib/typedarray `get(typedArray, index)` returns the element at `index` of `typedArray`. Returns `None` if the index does not exist. ```APIDOC ## get RES `let get: (t<'a>, int) => option<'a>` `get(typedArray, index)` returns the element at `index` of `typedArray`. Returns `None` if the index does not exist in the typed array. Equivalent to doing `typedArray[index]` in JavaScript. ### Examples ``` RES let view = Int32Array.fromArray([1, 2, 3]) TypedArray.get(view, 0) == Some(1) TypedArray.get(view, 10) == None ``` ``` -------------------------------- ### Math.sqrt Examples Source: https://rescript-lang.org/docs/manual/api/stdlib/math Shows how to use Math.sqrt to find the square root of a number. Returns NaN for negative inputs. ```rescript Math.sqrt(-1.0)->Float.isNaN == true Math.sqrt(-0.0) == -0.0 Math.sqrt(0.0) == 0.0 Math.sqrt(1.0) == 1.0 Math.sqrt(9.0) == 3.0 ``` -------------------------------- ### Slice a string with start and end indices Source: https://rescript-lang.org/docs/manual/api/stdlib/string Extracts a portion of a string between a start index (inclusive) and an end index (exclusive). Negative indices are supported and count from the end of the string. If `start` is greater than `end`, an empty string is returned. ```rescript String.slice("abcdefg", ~start=2, ~end=5) == "cde" String.slice("abcdefg", ~start=2, ~end=9) == "cdefg" String.slice("abcdefg", ~start=-4, ~end=-2) == "de" String.slice("abcdefg", ~start=5, ~end=1) == "" String.slice("abcdefg", ~start=2) == "cdefg" String.slice("Hello World", ~start=6) == "World" ``` -------------------------------- ### Ascending For Loop in ReScript Source: https://rescript-lang.org/docs/manual/overview Iterate from a starting number up to an ending number (inclusive) using `for i in start to end {...}`. ```rescript for i in 0 to 10 {...} ``` -------------------------------- ### Enable Experimental Compiler Features Source: https://rescript-lang.org/docs/manual/build-configuration-schema Use this object to enable experimental compiler features. Currently, it supports enabling the `let?` syntax. ```json { "type": "object", "description": "Enable experimental compiler features.", "properties": { "LetUnwrap": { "type": "boolean", "description": "Enable `let?` syntax." } }, "additionalProperties": false } ``` -------------------------------- ### get Source: https://rescript-lang.org/docs/manual/api/stdlib/string `get(str, index)` returns an `option` at the given `index`. Returns `None` if the index is out of range. ```APIDOC ## get RES `let get: (string, int) => option` `get(str, index)` returns an `option` at the given `index` number. If `index` is out of range, this function returns `None`. ### Examples ``` RES String.get("ReScript", 0) == Some("R") String.get("Hello", 4) == Some("o") String.get(`JS`, 4) == None ``` ``` -------------------------------- ### fromInitializer Source: https://rescript-lang.org/docs/manual/api/stdlib/list Creates a list of a specified length, with elements initialized by a function. ```APIDOC ## fromInitializer RES `let fromInitializer: (~length: int, int => 'a) => list<'a>` `fromInitializer(length, f)` return a list of length `length` with element initialized with `f`. Returns an empty list if `length` is negative. ### Examples ```res List.fromInitializer(~length=5, i => i) == list{0, 1, 2, 3, 4} List.fromInitializer(~length=5, i => i * i) == list{0, 1, 4, 9, 16} ``` ``` -------------------------------- ### ReScript 11 Bitwise AND operations Source: https://rescript-lang.org/docs/manual/migrate-to-v12 Example of bitwise AND operation syntax in ReScript v11. ```rescript let y = land(a, b) // bitwise AND ``` -------------------------------- ### Run migration tool Source: https://rescript-lang.org/docs/manual/migrate-to-v12 Use the npx rescript-tools migrate-all command to automatically replace common name changes and syntax. ```bash npx rescript-tools migrate-all # preview the changes via rescript-tools migrate [--stdout] ``` -------------------------------- ### Get Absolute Value of an Integer Source: https://rescript-lang.org/docs/manual/api/stdlib/math/int Use `Math.Int.abs` to get the absolute value of an integer. This is equivalent to `Math.abs` in JavaScript. ```rescript Math.Int.abs(-2) == 2 Math.Int.abs(3) == 3 ``` -------------------------------- ### Create a ListFormat formatter with options Source: https://rescript-lang.org/docs/manual/api/stdlib/intl/listformat Use `make` to create a new `Intl.ListFormat` instance. Specify locales and options like `type` to control how lists are formatted (e.g., conjunction, disjunction). ```rescript let formatter = Intl.ListFormat.make(~locales=["en"], ~options={"type": #conjunction}) formatter->Intl.ListFormat.format(["apples", "bananas", "cherries"]) == "apples, bananas, and cherries" ``` -------------------------------- ### Descending For Loop in ReScript Source: https://rescript-lang.org/docs/manual/overview Iterate from a starting number down to an ending number (inclusive) using `for i in start downto end {...}`. ```rescript for i in 10 downto 0 {...} ``` -------------------------------- ### make Source: https://rescript-lang.org/docs/manual/api/stdlib/array `make(~length, init)` creates an array of a specified length initialized with a given value. ```APIDOC ## make RES `let make: (~length: int, 'a) => array<'a>` `make(~length, init)` creates an array of length `length` initialized with the value of `init`. ### Examples ```res Array.make(~length=3, #apple) == [#apple, #apple, #apple] Array.make(~length=6, 7) == [7, 7, 7, 7, 7, 7] ``` ``` -------------------------------- ### get Source: https://rescript-lang.org/docs/manual/api/belt/set/int `get(s, x)` attempts to retrieve the value equal to `x` from the set `s`. Returns `Some(value)` if found, `None` otherwise. ```APIDOC ## get RES `let get: (t, value) => option` ``` -------------------------------- ### Creating an Iterator Source: https://rescript-lang.org/docs/manual/api/stdlib/iterator Demonstrates how to create a basic string iterator using raw JavaScript. ```rescript let iterator: Iterator.t = %raw( (() => { var array1 = ['a']; var iterator1 = array1[Symbol.iterator](); return iterator1 })() ) (iterator->Iterator.next).done == false (iterator->Iterator.next).done == true ``` -------------------------------- ### Extract substring to the end Source: https://rescript-lang.org/docs/manual/api/stdlib/string Extracts a substring from a specified start index to the end of the string. Handles negative and out-of-bounds start indices. ```rescript String.substringToEnd("playground", ~start=4) == "ground" String.substringToEnd("playground", ~start=-3) == "playground" String.substringToEnd("playground", ~start=12) == "" ``` -------------------------------- ### Create a NumberFormat Instance Source: https://rescript-lang.org/docs/manual/api/stdlib/intl/numberformat Use `make` to create a formatter for a specific locale and options, such as currency style. This is useful for displaying numbers in a culturally appropriate format. ```rescript let formatter = Intl.NumberFormat.make(~locales=["en-US"], ~options={style: #currency, currency: "USD"}) formatter->Intl.NumberFormat.format(1234.5) == "$1,234.50" ``` -------------------------------- ### Int.shiftLeft Example Source: https://rescript-lang.org/docs/manual/api/stdlib/int Demonstrates the left bitwise shift operation. Ensure the input is an integer. ```rescript Int.shiftLeft(4, 1) == 8 ``` -------------------------------- ### Complex JSX Element Example Source: https://rescript-lang.org/docs/manual/jsx A comprehensive example showcasing various attribute types and nested children within a JSX component. ```jsx
{React.string("hello")}
``` -------------------------------- ### Share Project-Specific Types with External Bindings Source: https://rescript-lang.org/docs/manual/module-functions This example shows how to create a module function that returns a module with a typed `getEnv` function, allowing consumers to define their own environment variable types. ```rescript @val external env: 'a = "import.meta.env" let getEnv = () => { env } ``` ```rescript type t = {"LOG_LEVEL": string} let values: t = getEnv() ``` ```rescript module MakeEnv = ( E: { type t }, ) => { @val external env: E.t = "import.meta.env" let getEnv = () => { env } } ``` ```rescript module Env = MakeEnv({ type t = {"LOG_LEVEL": string} }) let values = Env.getEnv() ``` -------------------------------- ### Start and Log Timer Source: https://rescript-lang.org/docs/manual/api/stdlib/console Use `Console.time` to start a timer with a given label and `Console.timeLog` to print the elapsed time. This helps in performance measurement. ```rescript Console.time("for_time") for x in 3 downto 1 { Console.log(x) Console.timeLog("for_time") } Console.timeEnd("for_time") ``` -------------------------------- ### Get First Element of List (Throws Error) Source: https://rescript-lang.org/docs/manual/api/stdlib/list Use `List.headOrThrow` to get the first element of a list. It will throw an error if the list is empty. ```rescript List.headOrThrow(list{1, 2, 3}) == 1 ``` ```rescript switch List.headOrThrow(list{}) { | exception Not_found => assert(true) | _ => assert(false) } ``` -------------------------------- ### Async/Await Equivalent for Logging a Message Source: https://rescript-lang.org/docs/manual/promise Provides the equivalent functionality of the Promise chaining example using the more ergonomic `async`/`await` syntax. This version is generally preferred for its readability and reduced type-related issues. ```rescript let logAsyncMessage = async () => { let msg = await Promise.resolve("hello world") Console.log(`Message: ${msg}`) } ``` -------------------------------- ### ReScript @inline Attribute Example Source: https://rescript-lang.org/docs/manual/attribute The @inline attribute suggests that the value of 'mode' should be inlined into its usage sites. This is a basic example of attribute usage. ```rescript @inline let mode = "dev" let mode2 = mode ``` -------------------------------- ### JavaScript Output Examples for Variants Source: https://rescript-lang.org/docs/manual/variant Demonstrates how different variant structures compile to JavaScript. Simple variants become strings, variants with payloads become objects with 'TAG' and payload fields, and labeled variants use field names. ```rescript type greeting = Hello | Goodbye let g1 = Hello let g2 = Goodbye type outcome = Good | Error(string) let o1 = Good let o2 = Error("oops!") type family = Child | Mom(int, string) | Dad (int) let f1 = Child let f2 = Mom(30, "Jane") let f3 = Dad(32) type person = Teacher | Student({gpa: float}) let p1 = Teacher let p2 = Student({gpa: 99.5}) type s = {score: float} type adventurer = Warrior(s) | Wizard(string) let a1 = Warrior({score: 10.5}) let a2 = Wizard("Joe") ``` -------------------------------- ### Belt.Range.every Source: https://rescript-lang.org/docs/manual/api/belt/range Checks if a predicate `p` holds true for all integers in the inclusive range `[start, finish]`. This is equivalent to `Belt.Array.every(Belt.Array.range(start, finish), p)`. ```APIDOC ## Belt.Range.every ### Description Checks if a predicate `p` holds true for all integers in the inclusive range `[start, finish]`. ### Signature `let every: (int, int, int => bool) => bool` ### Equivalent `Belt.Array.every(Belt.Array.range(start, finish), p)` ### Examples ```res Belt.Range.every(0, 4, i => i < 5) == true Belt.Range.every(0, 4, i => i < 4) == false ``` ``` -------------------------------- ### Source Directory Configuration Source: https://rescript-lang.org/docs/manual/build-configuration-schema Configures a source directory with optional slow regex for file matching and a list of files to exclude. Useful for optimizing incremental build performance. ```json { "type": "object", "properties": { "slow-re": { "type": "string", "description": "Regex to glob the patterns, syntax is documented [here](http://caml.inria.fr/pub/docs/manual-ocaml/libref/Str.html), for better incremental build performance, we'd suggest listing files explicitly" }, "excludes": { "type": "array", "items": { "type": "string" }, "description": "Files to be excluded" } } } ``` -------------------------------- ### Get character at index with option Source: https://rescript-lang.org/docs/manual/api/stdlib/string Use `get` to safely retrieve a character at a specific index. Returns `Some(char)` if the index is valid, otherwise `None`. ```rescript String.get("ReScript", 0) == Some("R") String.get("Hello", 4) == Some("o") String.get(`JS`, 4) == None ``` -------------------------------- ### Get First Element of List (Unsafe) Source: https://rescript-lang.org/docs/manual/api/stdlib/list Use `List.headExn` to get the first element of a list. This function is deprecated and will throw an exception if the list is empty. ```rescript List.headExn(list{1, 2, 3}) == 1 ``` ```rescript switch List.headExn(list{}) { | exception Not_found => assert(true) | _ => assert(false) } ``` -------------------------------- ### init Source: https://rescript-lang.org/docs/manual/api/belt/array Creates a new array of a specified size, where each element is generated by a function that takes the index as an argument. ```APIDOC ## init RES `let init: (int, int => 'a) => t<'a>` ``` -------------------------------- ### Profile ReScript Build with bstracing Source: https://rescript-lang.org/docs/manual/build-performance Run this command in your ReScript project's root to generate a JSON trace file for build performance visualization in Chrome. ```bash ./node_modules/.bin/bstracing ``` -------------------------------- ### Get First Element or Throw (Alternative) Source: https://rescript-lang.org/docs/manual/api/belt/list An alternative function to get the first element of a list, throwing an exception if the list is empty. Similar to `headExn`. ```rescript Belt.List.headOrThrow(list{1, 2, 3}) == 1 switch Belt.List.headOrThrow(list{}) { // Throws an Error | exception _ => assert(true) | _ => assert(false) } ``` -------------------------------- ### make Source: https://rescript-lang.org/docs/manual/api/stdlib/dict `make()` creates a new, empty dictionary. ```APIDOC ## make RES `let make: unit => dict<'a>` `make()` creates a new, empty dictionary. ### Examples ``` ``` RES let dict1: dict = Dict.make() // You can annotate the type of the values of your dict yourself if you want let dict2 = Dict.make() // Or you can let ReScript infer it via usage. dict2->Dict.set("someKey", 12) ``` ``` ``` -------------------------------- ### Extract substring with start and end indices Source: https://rescript-lang.org/docs/manual/api/stdlib/string Extracts characters from a string between a start index and an end index (exclusive). Handles swapped indices and out-of-bounds values. ```rescript String.substring("playground", ~start=3, ~end=6) == "ygr" String.substring("playground", ~start=6, ~end=3) == "ygr" String.substring("playground", ~start=4, ~end=12) == "ground" String.substring("playground", ~start=4) == "ground" String.substring("Hello World", ~start=6) == "World" ``` -------------------------------- ### Promise.reject Source: https://rescript-lang.org/docs/manual/api/stdlib/promise Shows how to create a promise that is immediately rejected with a given exception. ```APIDOC ## reject ### Description The `reject` function creates and returns a Promise that is immediately rejected with the provided exception. This is useful for explicitly signaling an error condition or for testing error handling logic. ### Method `Promise.reject` ### Endpoint N/A (SDK function calls) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```rescript exception TestError(string) TestError("some rejected value") ->Promise.reject ->Promise.catch(v => { switch v { | TestError(msg) => msg == "some rejected value" | _ => assert(false) } Promise.resolve() }) ->ignore ``` ### Response N/A (Boolean assertion within catch block) ``` -------------------------------- ### Get First Element of List Source: https://rescript-lang.org/docs/manual/api/stdlib/list Use `List.head` to safely get the first element of a list. It returns `Some(value)` if the list is not empty, and `None` if the list is empty. ```rescript List.head(list{}) == None ``` ```rescript List.head(list{1, 2, 3}) == Some(1) ``` -------------------------------- ### Promise.make Source: https://rescript-lang.org/docs/manual/api/stdlib/promise Shows how to create a new promise using `Promise.make` with explicit resolve and reject callbacks. ```APIDOC ## make ### Description The `make` function creates a new Promise. It accepts a callback function that receives two arguments: `resolve` and `reject`. These functions are used to signal the outcome of the asynchronous operation. ### Method `Promise.make` ### Endpoint N/A (SDK function calls) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```rescript open Promise let n = 4 Promise.make((resolve, reject) => { if n < 5 { resolve("success") } else { reject("failed") } }) ->then(str => { Console.log(str)->resolve }) ->catch(_ => { Console.log("Error occurred") resolve() }) ->ignore ``` ### Response N/A (Console logging) ``` -------------------------------- ### Get JavaScript Type of a Value Source: https://rescript-lang.org/docs/manual/api/stdlib/type Use `Type.typeof` to get the underlying JavaScript type of any runtime value. This function is equivalent to JavaScript's `typeof` operator. ```rescript Console.Log(Type.typeof("Hello")) // Logs "string" to the console. let someVariable = true switch someVariable->Type.typeof { | #boolean => Console.log("This is a bool, yay!") | _ => Console.log("Oh, not a bool sadly...") } ``` -------------------------------- ### startsWith Source: https://rescript-lang.org/docs/manual/api/stdlib/string Checks if a string begins with a specified substring. Returns true if it does, false otherwise. ```APIDOC ## startsWith RES `let startsWith: (string, string) => bool` `startsWith(str, substr)` returns `true` if the `str` starts with `substr`, `false` otherwise. See `String.startsWith` on MDN. ### Examples ```res String.startsWith("BuckleScript", "Buckle") == true String.startsWith("BuckleScript", "") == true String.startsWith("JavaScript", "Buckle") == false ``` ``` -------------------------------- ### ReScript Build Configuration Source: https://rescript-lang.org/docs/manual/installation Create a `rescript.json` file at the root of your project to configure the ReScript build process. Update 'dir' to your source directory. ```json { "name": "your-project-name", "sources": [ { "dir": "src", // update this to wherever you're putting ReScript files "subdirs": true } ], "package-specs": [ { "module": "esmodule", "in-source": true } ], "suffix": ".res.js" } ``` -------------------------------- ### Array.fillToEnd - Mutate array with a value from start (Deprecated) Source: https://rescript-lang.org/docs/manual/api/stdlib/array Fills an array with a specified value starting from a given index to the end. This function mutates the original array and is deprecated. ```rescript let myArray = [1, 2, 3, 4] myArray->Array.fillToEnd(9, ~start=1) myArray == [1, 9, 9, 9] ``` -------------------------------- ### Rescript WeakMap set example Source: https://rescript-lang.org/docs/manual/api/stdlib/weakmap Demonstrates setting a key-value pair in a WeakMap. The map is returned for chaining. ```rescript let cache = WeakMap.make() let key = Object.make() let _ = WeakMap.set(cache, key, 42) WeakMap.get(cache, key) == Some(42) ``` -------------------------------- ### Belt.Range.some Source: https://rescript-lang.org/docs/manual/api/belt/range Checks if a predicate `p` holds true for at least one integer in the inclusive range `[start, finish]`. This is equivalent to `Belt.Array.some(Belt.Array.range(start, finish), p)`. ```APIDOC ## Belt.Range.some ### Description Checks if a predicate `p` holds true for at least one integer in the inclusive range `[start, finish]`. ### Signature `let some: (int, int, int => bool) => bool` ### Equivalent `Belt.Array.some(Belt.Array.range(start, finish), p)` ### Examples ```res Belt.Range.some(0, 4, i => i > 5) == false Belt.Range.some(0, 4, i => i > 2) == true ``` ``` -------------------------------- ### Check if string includes substring from a start index Source: https://rescript-lang.org/docs/manual/api/stdlib/string Use `includesFrom` to check if a string contains a substring starting from a specified index. Returns `true` if found, `false` otherwise. ```rescript String.includesFrom("programmer", "gram", 1) == true String.includesFrom("programmer", "gram", 4) == false String.includesFrom(`대한민국`, "한", 1) == true ``` -------------------------------- ### Array Reduce Examples Source: https://rescript-lang.org/docs/manual/api/belt/array Demonstrates the use of Belt.Array.reduce for accumulating values in an array. It can be used for summing numbers or concatenating strings. ```rescript Belt.Array.reduce([2, 3, 4], 1, (a, b) => a + b) == 10 ``` ```rescript Belt.Array.reduce(["a", "b", "c", "d"], "", (a, b) => a ++ b) == "abcd" ``` -------------------------------- ### Array.fill - Mutate array with a value Source: https://rescript-lang.org/docs/manual/api/stdlib/array Fills a portion of an array with a specified value. This function mutates the original array. The start and end indices are inclusive for the start and exclusive for the end. ```rescript let myArray = [1, 2, 3, 4] myArray->Array.fill(9) myArray == [9, 9, 9, 9] myArray->Array.fill(0, ~start=1) myArray == [9, 0, 0, 0] myArray->Array.fill(5, ~start=1, ~end=3) myArray == [9, 5, 5, 0] ``` -------------------------------- ### String.localeCompare Examples Source: https://rescript-lang.org/docs/manual/api/stdlib/string Compares two strings based on sort order. Returns a float indicating their relative order. ```rescript String.localeCompare("a", "c") < 0.0 == true String.localeCompare("a", "a") == 0.0 ``` -------------------------------- ### Belt.Range.everyBy Source: https://rescript-lang.org/docs/manual/api/belt/range Checks if a predicate `p` holds true for all integers in the inclusive range `[start, finish]` with a specified step. This is equivalent to `Belt.Array.every(Belt.Array.rangeBy(start, finish, ~step), p)`. ```APIDOC ## Belt.Range.everyBy ### Description Checks if a predicate `p` holds true for all integers in the inclusive range `[start, finish]` with a specified step. ### Signature `let everyBy: (int, int, ~step: int, int => bool) => bool` ### Equivalent `Belt.Array.every(Belt.Array.rangeBy(start, finish, ~step), p)` ### Examples ```res Belt.Range.everyBy(0, 4, ~step=1, i => mod(i, 2) === 0) == false Belt.Range.everyBy(0, 4, ~step=2, i => mod(i, 2) === 0) == true ``` ``` -------------------------------- ### Get Input String Source: https://rescript-lang.org/docs/manual/api/stdlib/regexp/result Use `input` to get the original string that was searched by the regular expression. This function is helpful for context when processing matches, especially if the input string is large or complex. ```rescript let regexp = RegExp.fromString("(\w+) (\w+)") // This below will log the full input string "ReScript is pretty cool, right?" to the console. switch regexp->RegExp.exec("ReScript is pretty cool, right?") { | None => Console.log("Nope, no match...") | Some(result) => Console.log(result->RegExp.Result.input) } ``` -------------------------------- ### Basic Source Directory Configuration Source: https://rescript-lang.org/docs/manual/build-configuration Specifies an array of source directories for the project. These directories will be scanned for ReScript files to compile. ```json { "sources": ["src", "examples"] } ```