MelScript Documentation

Introduction to MelScript

MelScript is a web programming language designed to facilitate the development of interactive and dynamic applications. With a simple yet powerful syntax, MelScript allows you to create responsive and functional web pages, easily integrating visual and logical elements. It is ideal for developers who are looking for an efficient tool to create intuitive and customized user interfaces, using advanced features such as DOM manipulation and integration with external APIs in a direct and efficient manner.

MelScript is a tribute to Mel, the dog of Ravy Novais Sales, the creator of the language. The development of MelScript began on June 13, 2024, with the goal of making web programming accessible and powerful for all developers. In total, there are 73 keywords in MelScript, each playing a fundamental role in the creation of dynamic and interactive applications. Mel, the dog, unfortunately passed away, but her memory lives on through this programming language.

Representational Image of MelScript

Below is an image that represents MelScript:

Representational Image of MelScript

Running MelScript in your HTML

To run MelScript, you need to include the appropriate HTML in your project. Below is an example of HTML that includes the MelScript library script from the specified link and MelScript code within the <mel></mel> tag.


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>MelScript Example</title>
    <script src="https://mel-script.vercel.app/Rec/1.0.3"></script>
    <!-- or -->
    <script src="https://mel-script.netlify.app/Rec/1.0.3"></script>
</head>
<body>
    <mel>
        print("Hello, world!");
    </mel>
</body>
</html>

You should choose only one of the links to include the MelScript library script, either from Vercel or Netlify. Including both links simultaneously can cause conflicts and execution errors due to the duplication of definitions and functions. Choose the one that is most convenient for your development environment or the one that performs and is most stable in your tests.

What is HTML?

HTML (HyperText Markup Language) is the standard language used to create web pages. It defines the structure and content of a web document through a series of elements and tags that describe different parts of the page, such as headings, paragraphs, links, images, and more. HTML is the backbone of any website and works together with CSS (Cascading Style Sheets) and JavaScript to create interactive and visually appealing web pages.

An HTML document starts with the declaration <!DOCTYPE html>, which informs the browser that the document is in HTML5. The <html> element contains all the content of the page, divided into two main sections: <head> and <body>. The <head> section includes metadata about the document, such as the character set, the page title, and links to scripts and style sheets. The <body> section contains the visible content of the page, such as text, images, videos, and other multimedia elements.

Incorporating scripts from libraries like MelScript is done in the <head> section using the <script> tag. This allows you to add advanced functionality and interactivity to your web page, making it more dynamic and responsive.

Defining the Language for MelScript Code

To specify the language in MelScript code, you can use one of the following methods:

Explanation: These methods ensure that the MelScript code is interpreted according to the desired language, facilitating the understanding and execution of the scripts.

Example of using keywords

Example of using `print()`

Example of using the `print()` function to display a message.


print("Hello, world!");

Explanation: The `print()` function is used to display a message in the output. In this example, it prints "Hello, world!".

Example of using `print()` with .position() and .color()

Example of using the `print()` function with specified positioning and color.


print("Hello, world!")
    .position(100, 50)
    .color("#ff0000");

Explanation:
The `print()` function can be extended with the `.position(x, y)` method to set the position of the text on the screen and `.color()` to specify the color of the text.
In this example, "Hello, world!" is printed at the position (100, 50) on the screen with the color red (#ff0000).

Use of img, vid, aud, exb in `print()`

Example of using the `img`, `vid`, `aud`, and `exb` functions with `print()`.



// use of img to print an image
print({ img: "MelScript.jpg" })

// use of vid to print a video
print({ vid: "mov.mp4" })

// use of aud to print audio
print({ aud: "horse.ogg" })

// use of exb to print image, audio, video
print({ exb: "150.jpg" })

Explanation:

Example of variable definition

Example of how to define a variable and assign a value to it.


variable = "Hello, world!";
print(variable);

Explanation: In this example, the variable `variable` is defined and assigned the value `"Hello, world!"`. Then, the content of the variable is printed using the `print()` function.

Example of Using `if`, `else`, and `else if`

Example that checks if a user is logged in and prints an appropriate message.


userIsLoggedIn = true; // Defining if the user is logged in as true

if(userIsLoggedIn) { // Starts a conditional check to see if the user is logged in
    print("Welcome to the system!"); // Prints a welcome message
} 
else { // If the condition is false
    print("Please log in to access."); // Prints a login request message
}
    

Explanation: `if` is used to evaluate a condition (in this case, if the user is logged in). If the condition is true (`else`), an action is executed (printing a welcome message). If the condition is false (`else`), another action is executed (printing a login request message).

Explanation of the `if` Usage

`if` is a conditional structure used to evaluate a condition and decide which block of code should be executed based on the result of that evaluation.

In the example below, `if` checks if the user is logged in, and if the condition is satisfied, it displays a welcome message.


userIsLoggedIn = true;

if(userIsLoggedIn) { // Starts the conditional check
    print("Welcome to the system!"); // Action to be executed
}
    

How `if` Works:

Example of Using `if`, `else`, `else if`

This example demonstrates how to use the conditional structures `if`, `else`, and `else if` to handle different conditions and execute appropriate actions.


userIsLoggedIn = null; // Defining the login state as null

if(userIsLoggedIn) { // Starts a conditional check to see if the user is logged in
    print("Welcome to the system!"); // Prints a welcome message
} else if(userIsLoggedIn === null) { // If the condition in 'if' is false and the new condition is true (userIsLoggedIn is null)
    print("Error: login state undefined."); // Prints an error message
} else { // If none of the previous conditions are true
    print("Please log in to access."); // Prints a login request message
}
    

Explanation:

Defining a function in MelScript

Functions in MelScript allow you to encapsulate blocks of code for reuse. See how to define a simple function that prints a message:


function printMessage(message) {
    print("Received message: " , message);
}

Explanation:
1. function printMessage(message) {: Here, a function called printMessage is declared, which accepts a parameter message.
2. print("Received message: " , message);: Inside the function, we use print() to display the received message, concatenated with the text "Received message: ".

Example of using `while`

Example of a `while` loop, which repeatedly executes as long as the specified condition is true.


i = 0;
while(() => {
    return i < 5;
}).effect(() => {
    print("Iteration " , i);
    i++;
});

Explanation: The `while` structure evaluates the condition `i < 5`. As long as this condition is true, the code block inside `.effect` is executed repeatedly, incrementing the value of `i` and printing the current iteration.

Example of using try, catch and finally

Example of how to handle exceptions using `try`, `catch` and `finally`.


try(() => {
    password = "123n5";
    if(password.length < 6){
        throw new Error("The password must be at least 6 characters long.");
    }
    print("Valid password");
})
.catch((error) => {
    print("Error caught: " , error.message);
})
.finally(() => {
    print("Final block executed.");
});

Explanation: The `try` block is used to wrap code that may throw exceptions. If an exception is thrown inside the `try` block, the `catch` block captures the exception and executes a specific treatment for it. The `finally` block is optional and is always executed, regardless of whether an exception occurs or not.

Example of using a callback

Example of how to use a callback function in MelScript.


function hi(h, callback) {
    callback(h, callback);
}

function displayMessage(message) {
    print("Received message: " , message);
}

message = "Hello, world!";
hi(message, displayMessage);

Explanation: In this example, the `hi` function is defined to accept two arguments: `h`, which is the message to be processed, and `callback`, which is the callback function. Inside `hi`, the `callback` function is called with `h` and `callback`, performing the callback. The `displayMessage` function is the callback function passed to `hi`, which simply prints the received message using `print()`.

Example of using the `for` loop

Example of using the `for` loop to iterate and print a message multiple times.


for(
    0,                    // Start: starting from 0
    i => i < 5,           // Condition: while i is less than 5
    i => i , 1,           // Increment: incrementing i by 1 on each iteration
    i => print("Hi, " , i) // Loop body: print "Hi," followed by the value of i
);

Explanation: The `for` loop is used to perform a controlled loop, with the parameters specified within the parentheses. In this example, it starts at 0, continues while i is less than 5, increments i by 1 on each iteration, and prints "Hi," followed by the value of i.

Example of using `_iMSE()`

The `_iMSE()` is used to execute MelScript code directly.


    value = "print('hi')"
    _iMSE(value)

Explanation:
1. value = "print('hi')": Defines a variable `value` that contains a string with MelScript code to print "hi".
2. _iMSE(value): Calls the `_iMSE()` function, passing `value` as an argument to execute the MelScript code contained in the variable.
3. The code inside the `mel` block is executed directly, resulting in the printing of "hi" to the output.

Example of using "this" and "new"

Example of how to define and instantiate objects using "this" and "new".


function Person(name, age) {
    this.name = name;
    this.age = age;
}

person1 = new Person('Maria', 30);
print(person1.name);
print(person1.age);

person2 = new Person('João', 25);
print(person2.name);
print(person2.age);

Explanation:
Here, the `Person` function is defined to create person objects with `name` and `age` properties.
Using `this.name = name;` and `this.age = age;`, we define the properties of the object within the constructor function.
Then, we create two instances (`person1` and `person2`) using `new Person('name', age);`.
Finally, we print the name and age of each person using `print(person1.name);`, `print(person1.age);`, `print(person2.name);` and `print(person2.age);`.

Example of using MEL_SCRIPT_VERSION

Example that shows how to access and use the `MEL_SCRIPT_VERSION` constant.


print("Current MelScript version: " , MEL_SCRIPT_VERSION);

Explanation:
Here, the `MEL_SCRIPT_VERSION` constant is directly accessed to print the current version of MelScript.

Example of using create.doc.element()

Example of how to dynamically create a <p> element using `create.doc.element()`.


create.doc.element('p', 'This is a paragraph dynamically created by create.doc.element()');

Explanation:
This code demonstrates how to dynamically create a <p> element in the HTML document using `create.doc.element()`, inserting the content "This is a paragraph dynamically created by create.doc.element()".

Example of using create.doc.write()

Example of how to insert a script into the document using `create.doc.write()`.


create.doc.write('<script>console.error("n")</script>');

Explanation:
This code shows how to dynamically insert a script into the HTML document using `create.doc.write()`, but it will be displayed as text without being executed.

Example of using create.button() and EventClick()

Example of how to create a button and set a click event using `create.button()` and `EventClick()`.


create.button("btn", "Click here").backgroundColor("white").color("black").position(200, 200);
EventClick('btn', () => {
    print("Button clicked!");
});

Explanation:
This code dynamically creates a button with ID "btn", text "Click here", white background color, black text color, and positioning at (200, 200) pixels on the page. It also sets a click event to print "Button clicked!" when the button is clicked.

Example of using a class in MelScript

Example of how to define and use a class in MelScript.


class Person {
    // Constructor method
    constructor(name, age) {
        this.name = name;
        this.age = age;
    }

    // Method to print person's information
    introduce() {
        print("Name: ", this.name , ", Age: " , this.age);
    }
}

// Creating instances of the Person class
person1 = new Person('Maria', 30);
person2 = new Person('John', 25);

// Calling method to introduce the people's information
person1.introduce();
person2.introduce();

Explanation:
Here, a `Person` class is defined using the `class` keyword.
The constructor method `constructor(name, age)` is used to initialize the `name` and `age` attributes of each `Person` object created.
The `introduce()` method is defined to print the person's information (name and age).
Then, two instances (`person1` and `person2`) of the `Person` class are created using `new Person('name', age);`.
Finally, we call the `introduce()` method of each instance to print the information of the created people.

Example of using `throw` in MelScript

Example that demonstrates how to throw and catch an exception using `throw` and `catch`.


function validateAge(age) {
    if(age < 18).then(() => {
        throw new Error("The minimum age is 18 years.");
    });

    print("Valid age: " , age);
}

try(() => {
    validateAge(20); // Calling the function with a valid age
})
.catch((error) => {
    print("Caught error: " , error.message);
})
.finally(() => {
    print("Finally block executed.");
});

Explanation:
1. The `validateAge(age)` function is defined to check if the provided age is 18 or older. If not, an exception is thrown using `throw new Error("message")`.
2. The `try` block is used to wrap the code that may generate an exception. Here, we call `validateAge(20)`, which is a valid age.
3. If an exception is thrown inside the `try` block, the `catch` block captures the exception and executes specific handling for it, printing an error message with `print("Caught error: " , error.message)`.
4. The `finally` block is optional and is always executed, regardless of whether an exception occurs or not, printing "Finally block executed.".

Example of using `return` in MelScript


function calculateRectangleArea(base, height) {
    area = base * height;
    return area;
}

width = 5;
height = 3;
calculatedArea = calculateRectangleArea(width, height);
print("The area of the rectangle with width " , width , " and height " , height , " is: " , calculatedArea);

Explanation:
1. The `calculateRectangleArea(base, height)` function receives two parameters: `base` and `height`.
2. Inside the function, the `area` variable is calculated by multiplying `base` by `height`.
3. The `return` keyword is used to return the value of `area` to where the function was called.
4. Outside the function, the variables `width` and `height` are defined as 5 and 3, respectively.
5. We call the `calculateRectangleArea(width, height)` function passing `width` and `height` as arguments. The result is stored in the `calculatedArea` variable.
6. Finally, we use `print()` to display the message containing the calculated area of the rectangle.

Example of using prototype in MelScript


function Person(name, age) {
    this.name = name;
    this.age = age;
}

// Adding a method to the Person prototype
Person.prototype.introduce = function() {
    print("Hello, I'm " , this.name , " and I'm " , this.age , " years old.");
}

// Creating an Employee object that inherits from Person
Employee = new Person("John", 30);

// Adding specific properties to Employee
Employee.position = "Developer";
Employee.salary = 5000;

// Adding specific methods to Employee
Employee.work = function() {
    print(this.name , " is working as a " , this.position);
}

// Using methods inherited from the Person prototype
Employee.introduce();

// Using specific Employee methods
Employee.work();

Explanation:
1. `Person` is defined as a prototype using a constructor function that accepts `name` and `age` as parameters. Inside the constructor function, `this` refers to the current object being created.
2. An `introduce` method is added to the `Person` prototype, which prints a message with the person's name and age.
3. `Employee` is created using `new Person("John", 30)`, thus inheriting the `name` and `age` properties from `Person`.
4. Additional properties like `position` and `salary` are directly assigned to `Employee`.
5. A specific `Employee` method, `work`, is defined to print the employee's name and position.
6. `Employee.introduce()` invokes the `introduce` method inherited from `Person`, which prints a message with the `Employee`'s name and age.
7. `Employee.work()` invokes the `work` method specific to `Employee`, which prints a message indicating that `Employee` is working.

Example of using `true` and `false` in MelScript


// Example 1: Using true and false in a condition
age = 25;

if(age >= 18){
        print("You are an adult.");
    }
    else{
        print("You are a minor.");
    }

// Example 2: Assigning boolean values
canDrive = true;
needsAuthorization = false;

// Example 3: Returning boolean values from functions
function checkAge(age) {
    return age >= 18;
}

isAdult = checkAge(20);
print("Is an adult? ", isAdult);

Explanation:
1. In MelScript, `true` and `false` are used mainly in conditional structures (`if`) to evaluate boolean expressions. In example 1, `true` is used to check if the age is greater than or equal to 18 years, while `false` is used in the `else` block.
2. In the second part of the example, `true` and `false` are directly assigned to the variables `canDrive` and `needsAuthorization`, respectively. This is common when defining logical states or flags.
3. In example 3, a `checkAge` function is defined to return `true` if the age passed as an argument is greater than or equal to 18, otherwise it returns `false`. The result of the function is then printed to show whether the age is considered an adult.

Example of using evaluate in MelScript


expression = "5 + 3 * 2";
result = evaluate(expression);
print("Result of the expression '" , expression , "': " , result);

Explanation:
1. `expression` is a string containing the mathematical expression "5 + 3 * 2".
2. `evaluate(expression)` is used to calculate the result of the expression.
3. The result is stored in the `result` variable.
4. `print("Result of the expression '" + expression + "': " + result)` displays the calculated result in the output.

Example of using the replace function in MelScript


text = "Hello, world!";
newText = replace(text, "world", "friend");
print("Original text: " + text);
print("New text: " + newText);

Explanation:
1. `text` is initialized with the string `"Hello, world!"`.
2. `replace(text, "world", "friend")` is used to replace the word `"world"` with `"friend"` in the `text` string.
3. The result of the replacement is stored in the `newText` variable.
4. `print("Original text: " + text)` displays the original string.
5. `print("New text: " + newText)` displays the string after the replacement.

Using TimeLimit and Loop

Example of using the `TimeLimit` and `loop` functions.



// Function to be executed after the time limit
function showMessage() {
    print("Time limit reached!");
}

// Calls the showMessage function after 3 seconds (3000 milliseconds)
TimeLimit(3000, showMessage);

// Function to be executed in the loop
function performAction() {
    print("Action performed in the loop!");
}

// Creates a loop that executes the performAction function every 2 seconds (2000 milliseconds)
myLoop = loop(performAction, 2000);

// Starts the loop
myLoop.start();

// Pauses the loop after 5 seconds
TimeLimit(5000, function() {
    print("Loop paused!");
    myLoop.pause();
});

// Resumes the loop after another 5 seconds
TimeLimit(10000, function() {
    print("Loop resumed!");
    myLoop.resume();
});

// Changes the loop execution time to 1 second after another 5 seconds
TimeLimit(15000, function() {
    print("Loop time changed to 1 second!");
    myLoop.changeTime(1000);
});    

Explanation:

Using obt.Day, obt.Hour, obt.Month, obt.Seconds, obt.Minute, obt.Browser.Version, and obt.Browser.Name

Example of using the functions `oby.Day`, `obt.Hour`, `obt.Month`, `obt.Seconds`, `obt.Minute`, `obt.Browser.Version`, and `obt.Browser.Name`.



function showInformation() {
    info = `
        Hour: ${obt.Hour}:${obt.Minute}:${obt.Seconds}
        Date: ${obt.Day}/${obt.Month}/${obt.Year}
        Browser: ${obt.Browser.Name}
        Browser Version: ${obt.Browser.Version}
    `;
    print(info);
}
showInformation()

Explanation:

Using analyzeInteger and analyzeFloat

Example of using the `analyzeInteger` and `analyzeFloat` functions.



stringNumber1 = "42";
integerNumber = analyzeInteger(stringNumber1);
print(integerNumber);

stringNumber2 = "3.14";
floatNumber = analyzeFloat(stringNumber2);
print(floatNumber);           

Explanation:

Example of using `fetchId()`

Example of using the `fetchId()` function to search for an element by its ID.


create.doc.fetchId("parent");

Explanation: The `getElementById()` function is used to search for an element by its ID in the document. In this example, it searches for the element with the ID "parent".

Example of using `forEach()`

Example of using the `forEach()` function to iterate over a list of numbers.


numbers = [1, 2, 3, 4, 5];

numbers.forEach(function(number, index, array) {
    print(`Number: ${number}, Index: ${index}`);
});

Explanation: The `forEach()` function is used to iterate over each element of a list. In this example, it traverses the list of numbers and prints each number along with its index.

Example of using `alert()`

Example of using the `alert()` function to display an alert message.


alert("This is an alert message!");

Explanation: The `alert()` function is used to display an alert message to the user. In this example, it displays "This is an alert message!".

Here is the English translation:

Example of Using Typing

Example of using the typing syntax to define variables with types and values.


// Defining variables with typing
Tip Name = string:"João";     // String Type
Tip Age = number:30;         // Number Type
Tip Height = number:1.75;    // Decimal Type
Tip Active = boolean:true;   // Boolean Type
Tip Config = object:{ key: "value" }; // Object Type
Tip Items = array:[1, 2, 3];  // Array Type
Tip Unknown = unknown;       // Undefined Type
Tip Symbol = symbol;         // Symbol Type
Tip BigNumber = bigint:123456789012345678901234567890; // BigInt Type

Explanation: The syntax `Tip Name = type:value;` is used to define variables with a specific type and an initial value. In this example:

These types help ensure that variables are used correctly and help prevent errors during development.

Example of Using global

Example of using the global keyword to define global variables.

// Use the global variable before declaring it
print(nome2);

// Declare the global variable
global nome2 = "ravy";
print(nome2);

// Another example: declare a global variable and assign a value
global age;
age = 30;
print(age);

Explanation: The global keyword is used to declare global variables that can be accessed anywhere in the script. In the example above, nome2 is used before being declared globally, and then it is assigned the value "ravy". Next, age is declared globally and assigned the value 30. This demonstrates that global variables can be used anywhere in the code, even before their actual declaration.

Mathematical Functions

Below are some mathematical functions provided by the `Mat` library, with examples of use and descriptions.


// Generates a random
Mat.rnd(); 

// Rounds 4.7 to the nearest integer (5)
Mat.rd(4.7); 

// Rounds 4.7 down (4)
Mat.ch(4.7);   

// Rounds 4.2 up (5)
Mat.tp(4.2);    

// Calculates the sine of 30 degrees (0.5)
Mat.sin(Mat.PI / 6); 

// Calculates the cosine of 60 degrees (0.5)
Mat.cos(Mat.PI / 3); 

// Calculates the tangent of 45 degrees (1)
Mat.tan(Mat.PI / 4); 

// Calculates the square root of 16 (4)
Mat.sqrt(16); 

// Calculates 2 raised to the power of 3 (8)
Mat.pow(2, 3); 

// Calculates the natural logarithm of 10 (approximately 2.3026)
Mat.logNL(10); 

// Calculates the absolute value of -5 (5)
Mat.abs(-5); 

// Returns the largest number (7)
Mat.max(1, 3, 5, 7); 

// Returns the smallest number (1)
Mat.min(1, 3, 5, 7); 

// Returns the value of π (approximately 3.14159)
Mat.Pi; 

Explanation: The `Mat` library provides various useful mathematical functions:

Functions for Resource Handling and Error Handling

Function fetch()

The `fetch()` function is used to fetch resources, such as API URLs, and returns an object that allows chaining operations like `toUse` and `handleError`.


// Assume you have an API URL that returns JSON
url = 'https://api.example.com/data';

// Call the fetch function with the URL
fetch(url)
  .toUse(data => {
    print('Received data:', data);
    // Do something with the received data
  })
  .handleError(error => {
    print('An error occurred:', error);
    // Handle the error
  });

Function toUse()

The `toUse()` function is used to process the data received from an opened resource, such as an API response. It is called after `fetch` and allows you to manipulate the received data.


toUse(data => {
  print('Received data:', data);
  // Do something with the received data
});

Function handleError()

The `handleError()` function is used to handle errors that occur during the execution of asynchronous operations. It is called after `fetch` and `use` to capture and handle errors.


handleError(error => {
  print('An error occurred:', error);
  // Handle the error
});

Explanation: These functions are designed to handle resources safely and efficiently handle errors:

Example of Using importar()

Example of using the importar() function to load and process a code file.


import("path/to/the/file.mel");

Explanation: The importar() function is used to load and process a MelScript code file. In this example, it loads the file located at "path/to/the/file.mel".

Example of Using Event()

Example of using the Event() function to add an event listener to an HTML element.


Event("click", "#myButton", ()=>{
    print("Button clicked!");
});

Explanation: The Event() function is used to associate a specific event with an HTML element. In this example, the function registers a listener for the click event on a button identified by the selector #myButton. When the button is clicked, the callback function is executed and a message is displayed in the console.

Supported Event Types:

To use the Event() function, you need to specify the event type, the HTML element selector (if applicable), and a callback function that will be executed when the event occurs.

Example of Using the value Property

Example of using the value property to access the value of an HTML element.


create.input("text", "myInput");
input = create.doc.fetchId("myInput");
print(input.value);

Explanation: Use input.value to access the value of an element identified by fetchId. In the example above, the value of the input field is printed.

Example of Using the create.input() Function

Example of how to use the create.input() function to create and style an HTML input field.


create.input("text", "myInput", "Initial value", "Type here...");

Explanation: The create.input() function creates an HTML input field with the specified type, an optional ID, an initial value, and a placeholder. It applies basic styles and adds the field to the page body.

Supported Input Types:

Example of Using the convertType Function

Example of how to use the convertType function to convert the type of a value.


value = "123";
print(value.convertType("number")); // Displays 123 as a number

value = "true";
print(value.convertType("boolean")); // Displays true as a boolean

value = "2024-08-16";
print(value.convertType("date")); // Displays the corresponding date

Explanation: The convertType function allows you to convert the value of an object to a specific type, such as string, number, boolean, object, array, or date. The desired type is passed as an argument to the function.

Supported Types:

Example of using reduce()

The reduce() method is used to reduce an array to a single value by applying an accumulator function to each element. In the example below, we sum all the values in an array and calculate the average.


numbers = [10, 20, 30, 40, 50];

// Reduces the array by summing all the values
sum = numbers.reduce((accumulator, currentValue) => {
    return accumulator + currentValue; // Adds the current value to the accumulator
}, 0);

average = sum / numbers.length; // Calculates the average

print(average); // Prints the average

Example of using map()

The map() method creates a new array with the results of calling a function on every element in the calling array. The example below calculates the square of each number.


numbers = [1, 2, 3, 4, 5];

// Maps the numbers to their squares
squaredNumbers = numbers.map(num => num * num);

print(squaredNumbers); // Prints the array with the squared numbers

Example of using filter()

The filter() method returns a new array containing only the elements that pass the test implemented by the provided function. In the example below, we select the even numbers.


numbers = [1, 2, 3, 4, 5];

// Filters the numbers to get only the even ones
evenNumbers = numbers.filter(num => num % 2 === 0);

print(evenNumbers); // Prints the even numbers

Example of using push()

The push() method adds one or more elements to the end of an array and returns the new length of the array. The example below adds "kiwi" to the end of the fruits array.


fruits = ['apple', 'banana', 'orange'];

// Adds "kiwi" to the end of the array
length = fruits.push("kiwi");

print(fruits); // Prints the array with the new element
print(length); // Prints the new length of the array

Example of using find()

The find() method returns the value of the first element in the array that satisfies the provided testing function. The example below finds the first number greater than 3.


numbers = [1, 2, 3, 4, 5];

// Finds the first number greater than 3
found = numbers.find(x => x > 3);

print(found); // Prints the found number

Example of using pop()

The pop() method removes the last element from an array and returns that element. In the example below, we remove the last element from the fruits array.


fruits = ['apple', 'banana', 'orange'];

// Removes the last element from the array
removed = fruits.pop(); 

print(removed); // Prints the removed element
print(fruits);  // Prints the updated array

Example of using join()

The join() method converts an array into a string, joining the elements with the specified separator. In the example below, the elements are joined with ' - '.


fruits = ['apple', 'banana', 'orange'];

// Joins the array elements with ' - ' as the separator
result = fruits.join(' - ');

print(result); // Prints the resulting string

Example of using unshift()

The unshift() method adds one or more elements to the beginning of an array and returns the new length of the array. The example below adds "apple" and "kiwi" to the beginning of the fruits array.


fruits = ['banana', 'orange'];

// Inserts "apple" and "kiwi" at the beginning of the array
length = fruits.unshift('apple', 'kiwi');

print(fruits); // Prints the array with the new elements
print(length); // Prints the new length of the array

Example of using shift()

The shift() method removes the first element from an array and returns that element. In the example below, we remove the first element from the fruits array.


fruits = ['apple', 'banana', 'orange'];

// Removes the first element from the array
removed = fruits.shift();

print(removed); // Prints the removed element
print(fruits);  // Prints the updated array

Example of using slice()

The slice() method extracts a section of an array and returns a new array. In the example below, we obtain a slice of the fruits array from index 1 to 3 (exclusive).


fruits = ['apple', 'banana', 'orange'];

// Extracts a slice of the array from index 1 to 3
part = fruits.slice(1, 3);

print(part); // Prints the sliced array

Example of using concat()

The concat() method is used to merge two or more arrays and/or values. In the example below, we concatenate an additional array to the fruits array.


fruits = ['apple', 'banana'];
moreFruits = fruits.concat('orange', ['kiwi']);

print(moreFruits); // Prints the concatenated array

Example of using splice()

The splice() method inserts elements at a specific position in an array, and can also remove elements. In the example below, we insert "kiwi" and "mango" at position 1.


fruits = ['apple', 'banana', 'orange'];

// Inserts "kiwi" and "mango" at position 1
removed = fruits.splice(1, 0, 'kiwi', 'mango');

print(removed); // Prints the removed elements
print(fruits);  // Prints the updated array

Example of using sort()

The sort() method sorts the elements of an array according to the provided comparison function. In the example below, we sort an array of numbers in ascending order.


numbers = [5, 3, 8, 1, 2];

// Sorts the array in ascending order
numbers.sort((a, b) => a - b);

print(numbers); // Prints the sorted array

Example of using JSON.stringify()

The JSON.stringify() method converts a MelScript object into a JSON string, which is a standard text format for representing structured data. In the example below, we convert an object with various properties and nesting into a JSON string.


obj = {
    name: "Alice",
    age: 25,
    hobbies: ["reading", "traveling"],
    active: true,
    address: {
        city: "Rio de Janeiro",
        state: "RJ"
    }
};

// Converts the object to a JSON string
jsonString = JSON.stringify(obj);

print(jsonString); // Prints the resulting JSON string

Explanation: The JSON.stringify() function is used to convert a MelScript object into a JSON string. This is useful for sending data to a server or storing data in a text format. In the example above, the obj object is transformed into a JSON string, which is then printed.

Example of using the toUpperCase() method

Example of using the toUpperCase() method to convert a string to uppercase.


text = "hello, world!";
print(text.toUpperCase()); // Output: "HELLO, WORLD!"

Explanation: The toUpperCase() method converts all the characters in the string to uppercase. In this example, the string "hello, world!" is transformed into "HELLO, WORLD!".

Example of using the toLowerCase() method

Example of using the toLowerCase() method to convert a string to lowercase.


text = "HELLO, WORLD!";
print(text.toLowerCase()); // Output: "hello, world!"

Explanation: The toLowerCase() method converts all the characters in the string to lowercase. In this example, the string "HELLO, WORLD!" is transformed into "hello, world!".

Example of using the toString() method

Example of using the toString() method to convert numbers and other types to strings.


number = 123456.789;
print(number.toString()); // Output: "123456.789"

boolean = true;
print(boolean.toString()); // Output: "true"

object = { key: "value", number: 42 };
print(object.toString()); // Output: '{"key":"value","number":42}'

Explanation: The toString() method converts different data types to a string representation. In this example, a number, a boolean value, and an object are converted to strings. The number 123456.789 is converted to "123456.789", the boolean true is converted to "true", and the object is converted to its JSON representation.

Example of using the toFixed() method

Example of using the toFixed() method to format a number with a specific number of decimal places.


number = 123456.789;
print(number.toFixed(2)); // Output: "123456.79"

Explanation: The toFixed() method formats the number with the specified number of decimal places. In this example, the number 123456.789 is formatted with 2 decimal places, resulting in "123456.79".

Example of using the toExponential() method

Example of using the toExponential() method to convert a number to exponential notation.


number = 123456.789;
print(number.toExponential(2)); // Output: "1.23e+5"

Explanation: The toExponential() method converts the number to exponential notation with the specified number of decimal places. In this example, the number 123456.789 is converted to "1.23e+5" with 2 decimal places.

Example of using the toPrecision() method

Example of using the toPrecision() method to adjust the number to a specified precision of digits.


number = 123456.789;
print(number.toPrecision(6)); // Output: "123456.8"

Explanation: The toPrecision() method adjusts the number to the specified precision of digits. In this example, the number 123456.789 is rounded to "123456.8" with a precision of 6 digits.

Example of using the toLocaleString() method

Example of using the toLocaleString() method to format numbers and dates according to local conventions.


number = 123456.789;
print(number.toLocaleString('pt-BR')); // Output: "123.456,789"

date = new Date('2024-08-17T10:00:00Z');
print(date.toLocaleString('pt-BR')); // Output: "17/08/2024 07:00:00"

array = [123456.789, 98765.432];
print(array.toLocaleString('en-US')); // Output: "123,456.789,98,765.432"

Explanation: The toLocaleString() method formats numbers and dates according to the specified local conventions. In the example, the number 123456.789 is formatted for the Brazilian locale, resulting in "123.456,789". The date is formatted for the Brazilian locale, resulting in "17/08/2024 07:00:00". The array is formatted for the US locale, resulting in "123,456.789,98,765.432".

Example of using obt.Battery.Level()

Example of using the obt.Battery.Level() function to obtain the battery level.


obt.Battery.Level((error, value) => {
    if (error) =>
        print("Error getting battery level:", error);    
    else =>
        print("Battery level:", value , "%");    
});

Explanation: The obt.Battery.Level() function is used to obtain the current battery level. In this example, it calls a callback function that processes the result, displaying the battery level or an error if one occurs.

Example of using create.doc.fetchSelector()

Example of using the create.doc.fetchSelector() function to select and manipulate an HTML element.


element = create.doc.fetchSelector("#myElement");

if (element) =>
    element.textContent = "Text updated with fetchSelector()";
else =>
    print("Element not found!");

Explanation: The create.doc.fetchSelector() function is used to select an HTML element by its CSS selector. In this example, it selects the element with the ID "myElement" and updates its text content. If the element is not found, an error message is printed to the console.

Example of using obt.Browser.LocalIP()

Example of using the obt.Browser.LocalIP() function to obtain the local IP address.


obt.Browser.LocalIP((ip) => {
    print("Local IP Address:", ip);   
});

Explanation: The obt.Browser.LocalIP() function is used to obtain the local IP address of the browser. In this example, it calls a callback function that processes the result, displaying the obtained local IP.

Example of using the textContent property

Example of using the textContent property to set or get the text content of an HTML element.


element = create.doc.fetchSelector("#myElement");

if (element) =>
    element.textContent = "Text updated with fetchSelector()";
else =>
    print("Element not found!");

Explanation: The textContent property is used to set or get the text content of an HTML element. In this example, the text content of the selected element is updated to "Text updated with fetchSelector()". If the element is not found, an error message is printed to the console.

Example Usage of the Browser Object

The Browser object provides methods for handling navigation and page scrolling. See how to use each of these methods:


// Redirects to a new URL
Browser.redirect("https://example.com");

// Goes back to the previous page
Browser.back();

// Moves forward to the next page
Browser.forward();

// Reloads the current page
Browser.reload();

// Closes the current window
Browser.close();

// Scrolls the page to the position (x, y)
Browser.scrollTo(0, 500);

// Scrolls the page by an offset (dx, dy)
Browser.scrollBy(0, 100);

Explanation:

Example of Using the create.textArea Function

The textArea function is used to create a customizable text area on a web page. Below are the parameters that the function accepts:


// Example of calling the textArea function
create.textArea('myText', 'Initial text', 'Enter here...', 5, 30);

Parameters of the create.textArea function:

Explanation: The create.textArea function creates a text area with the provided parameters to customize the behavior and appearance of the textarea element on the web page.

Example of Using the CopyText Function

The CopyText(text) function is used to copy the text content to the clipboard. See how to use the function together with other interface elements:


// Creates a text area with the ID 'ent' and initial text
create.textArea('ent', null, "Text to be copied");

// Creates a button with the ID 'btn' and text 'COPY'
create.button('btn', "COPY")
    .backgroundColor("blue");

// Defines a click event for the button
EventClick('btn', () => {
    CopyText(ent.value);
});

Explanation:

Note: The CopyText(text) function must be defined to perform the action of copying the provided text to the clipboard.

Explanation of the GraphicStyle Function

The GraphicStyle function allows you to configure graphical styles for an HTML element based on a configuration object. See the explanation of the parameters and how the function applies the styles:


// Example of using the GraphicStyle function

create.button('btn', "Button")

btn.GraphicStyle({
    Color: 'red',
    BackgroundColor: 'blue',
    Size: [200, 100],
    Position: [50, 50]
});

Parameters of the GraphicStyle function:

Explanation: The GraphicStyle function configures the visual style of the HTML element, allowing customization of text color, background color, size, and position based on the provided parameters.

Example of Using obt.Lantern.On() and obt.Lantern.Turnoff()

These methods allow you to turn the device's flashlight on and off, providing direct control over the flashlight hardware. See the examples below to understand the functionality.


// Example of using the obt.Lantern.On() function
obt.Lantern.On(); // Turns the device's flashlight on

// Example of using the obt.Lantern.Turnoff() function
obt.Lantern.Turnoff(); // Turns the device's flashlight off

Explanation:

Context: These methods are useful for apps that need to directly control the device's flashlight, such as flashlight apps or others that require using the device's flash as a light source.

Update to version 1.0.3 RFZ

In the new version 1.0.3 RFZ of MelScript, "RFZ" means "Rewritten From Scratch". This version was necessary due to the discovery of significant bugs in the previous code. Additionally, there was the complication that MelScript was being developed in a single editor that crashed, resulting in the complete loss of the code and leaving it with flaws. Therefore, the RFZ version was a complete rewrite to fix these issues and ensure a more stable and reliable operation of MelScript.

The 1.0.3 RFZ version of MelScript was released on July 14, 2024, at 4:15 PM.

Conclusion

MelScript is a web programming language that honors the memory of Mel, Ravy Novais Sales' dog. Since its inception on June 13, 2024, MelScript has stood out for its simplicity and power, allowing developers of all levels to create interactive and dynamic web applications. With its 73 keywords, MelScript offers a wide range of features, making it easier to create customized and efficient user interfaces. Through MelScript, Ravy Novais Sales aims to make web programming more accessible and intuitive, perpetuating the legacy of his beloved dog Mel.


numbers = [10, 20, 30, 40, 50];

// Reduces the array by summing all the values
sum = numbers.reduce((accumulator, currentValue) => {
    return accumulator + currentValue; // Adds the current value to the accumulator
}, 0);

average = sum / numbers.length; // Calculates the average

print(average); // Prints the average

Example of using map()

The map() method creates a new array with the results of calling a function on every element in the calling array. The example below calculates the square of each number.


numbers = [1, 2, 3, 4, 5];

// Maps the numbers to their squares
squaredNumbers = numbers.map(num => num * num);

print(squaredNumbers); // Prints the array with the squared numbers

Example of using filter()

The filter() method returns a new array containing only the elements that pass the test implemented by the provided function. In the example below, we select the even numbers.


numbers = [1, 2, 3, 4, 5];

// Filters the numbers to get only the even ones
evenNumbers = numbers.filter(num => num % 2 === 0);

print(evenNumbers); // Prints the even numbers

Example of using push()

The push() method adds one or more elements to the end of an array and returns the new length of the array. The example below adds "kiwi" to the end of the fruits array.


fruits = ['apple', 'banana', 'orange'];

// Adds "kiwi" to the end of the array
length = fruits.push("kiwi");

print(fruits); // Prints the array with the new element
print(length); // Prints the new length of the array

Example of using find()

The find() method returns the value of the first element in the array that satisfies the provided testing function. The example below finds the first number greater than 3.


numbers = [1, 2, 3, 4, 5];

// Finds the first number greater than 3
found = numbers.find(x => x > 3);

print(found); // Prints the found number

Example of using pop()

The pop() method removes the last element from an array and returns that element. In the example below, we remove the last element from the fruits array.


fruits = ['apple', 'banana', 'orange'];

// Removes the last element from the array
removed = fruits.pop(); 

print(removed); // Prints the removed element
print(fruits);  // Prints the updated array

Example of using join()

The join() method converts an array into a string, joining the elements with the specified separator. In the example below, the elements are joined with ' - '.


fruits = ['apple', 'banana', 'orange'];

// Joins the array elements with ' - ' as the separator
result = fruits.join(' - ');

print(result); // Prints the resulting string

Example of using unshift()

The unshift() method adds one or more elements to the beginning of an array and returns the new length of the array. The example below adds "apple" and "kiwi" to the beginning of the fruits array.


fruits = ['banana', 'orange'];

// Inserts "apple" and "kiwi" at the beginning of the array
length = fruits.unshift('apple', 'kiwi');

print(fruits); // Prints the array with the new elements
print(length); // Prints the new length of the array

Example of using shift()

The shift() method removes the first element from an array and returns that element. In the example below, we remove the first element from the fruits array.


fruits = ['apple', 'banana', 'orange'];

// Removes the first element from the array
removed = fruits.shift();

print(removed); // Prints the removed element
print(fruits);  // Prints the updated array

Example of using slice()

The slice() method extracts a section of an array and returns a new array. In the example below, we obtain a slice of the fruits array from index 1 to 3 (exclusive).


fruits = ['apple', 'banana', 'orange'];

// Extracts a slice of the array from index 1 to 3
part = fruits.slice(1, 3);

print(part); // Prints the sliced array

Example of using concat()

The concat() method is used to merge two or more arrays and/or values. In the example below, we concatenate an additional array to the fruits array.


fruits = ['apple', 'banana'];
moreFruits = fruits.concat('orange', ['kiwi']);

print(moreFruits); // Prints the concatenated array

Example of using splice()

The splice() method inserts elements at a specific position in an array, and can also remove elements. In the example below, we insert "kiwi" and "mango" at position 1.


fruits = ['apple', 'banana', 'orange'];

// Inserts "kiwi" and "mango" at position 1
removed = fruits.splice(1, 0, 'kiwi', 'mango');

print(removed); // Prints the removed elements
print(fruits);  // Prints the updated array

Example of using sort()

The sort() method sorts the elements of an array according to the provided comparison function. In the example below, we sort an array of numbers in ascending order.


numbers = [5, 3, 8, 1, 2];

// Sorts the array in ascending order
numbers.sort((a, b) => a - b);

print(numbers); // Prints the sorted array

Example of using JSON.stringify()

The JSON.stringify() method converts a MelScript object into a JSON string, which is a standard text format for representing structured data. In the example below, we convert an object with various properties and nesting into a JSON string.


obj = {
    name: "Alice",
    age: 25,
    hobbies: ["reading", "traveling"],
    active: true,
    address: {
        city: "Rio de Janeiro",
        state: "RJ"
    }
};

// Converts the object to a JSON string
jsonString = JSON.stringify(obj);

print(jsonString); // Prints the resulting JSON string

Explanation: The JSON.stringify() function is used to convert a MelScript object into a JSON string. This is useful for sending data to a server or storing data in a text format. In the example above, the obj object is transformed into a JSON string, which is then printed.

Example of using the toUpperCase() method

Example of using the toUpperCase() method to convert a string to uppercase.


text = "hello, world!";
print(text.toUpperCase()); // Output: "HELLO, WORLD!"

Explanation: The toUpperCase() method converts all the characters in the string to uppercase. In this example, the string "hello, world!" is transformed into "HELLO, WORLD!".

Example of using the toLowerCase() method

Example of using the toLowerCase() method to convert a string to lowercase.


text = "HELLO, WORLD!";
print(text.toLowerCase()); // Output: "hello, world!"

Explanation: The toLowerCase() method converts all the characters in the string to lowercase. In this example, the string "HELLO, WORLD!" is transformed into "hello, world!".

Example of using the toString() method

Example of using the toString() method to convert numbers and other types to strings.


number = 123456.789;
print(number.toString()); // Output: "123456.789"

boolean = true;
print(boolean.toString()); // Output: "true"

object = { key: "value", number: 42 };
print(object.toString()); // Output: '{"key":"value","number":42}'

Explanation: The toString() method converts different data types to a string representation. In this example, a number, a boolean value, and an object are converted to strings. The number 123456.789 is converted to "123456.789", the boolean true is converted to "true", and the object is converted to its JSON representation.

Example of using the toFixed() method

Example of using the toFixed() method to format a number with a specific number of decimal places.


number = 123456.789;
print(number.toFixed(2)); // Output: "123456.79"

Explanation: The toFixed() method formats the number with the specified number of decimal places. In this example, the number 123456.789 is formatted with 2 decimal places, resulting in "123456.79".

Example of using the toExponential() method

Example of using the toExponential() method to convert a number to exponential notation.


number = 123456.789;
print(number.toExponential(2)); // Output: "1.23e+5"

Explanation: The toExponential() method converts the number to exponential notation with the specified number of decimal places. In this example, the number 123456.789 is converted to "1.23e+5" with 2 decimal places.

Example of using the toPrecision() method

Example of using the toPrecision() method to adjust the number to a specified precision of digits.


number = 123456.789;
print(number.toPrecision(6)); // Output: "123456.8"

Explanation: The toPrecision() method adjusts the number to the specified precision of digits. In this example, the number 123456.789 is rounded to "123456.8" with a precision of 6 digits.

Example of using the toLocaleString() method

Example of using the toLocaleString() method to format numbers and dates according to local conventions.


number = 123456.789;
print(number.toLocaleString('pt-BR')); // Output: "123.456,789"

date = new Date('2024-08-17T10:00:00Z');
print(date.toLocaleString('pt-BR')); // Output: "17/08/2024 07:00:00"

array = [123456.789, 98765.432];
print(array.toLocaleString('en-US')); // Output: "123,456.789,98,765.432"

Explanation: The toLocaleString() method formats numbers and dates according to the specified local conventions. In the example, the number 123456.789 is formatted for the Brazilian locale, resulting in "123.456,789". The date is formatted for the Brazilian locale, resulting in "17/08/2024 07:00:00". The array is formatted for the US locale, resulting in "123,456.789,98,765.432".

Update to version 1.0.3 RFZ

In the new version 1.0.3 RFZ of MelScript, "RFZ" means "Rewritten From Scratch". This version was necessary due to the discovery of significant bugs in the previous code. Additionally, there was the complication that MelScript was being developed in a single editor that crashed, resulting in the complete loss of the code and leaving it with flaws. Therefore, the RFZ version was a complete rewrite to fix these issues and ensure a more stable and reliable operation of MelScript.

The 1.0.3 RFZ version of MelScript was released on July 14, 2024, at 4:15 PM.

Conclusion

MelScript is a web programming language that honors the memory of Mel, Ravy Novais Sales' dog. Since its inception on June 13, 2024, MelScript has stood out for its simplicity and power, allowing developers of all levels to create interactive and dynamic web applications. With its 73 keywords, MelScript offers a wide range of features, making it easier to create customized and efficient user interfaces. Through MelScript, Ravy Novais Sales aims to make web programming more accessible and intuitive, perpetuating the legacy of his beloved dog Mel.

  • array - Converts the value to an array. If the value is already an array, returns it; otherwise, places the value in an array.
  • date - Converts the value to a date. If conversion fails, returns null.
  • Example of using reduce()

    The reduce() method is used to reduce an array to a single value by applying an accumulator function to each element. In the example below, we sum all the values in an array and calculate the average.

    
    numbers = [10, 20, 30, 40, 50];
    
    // Reduces the array by summing all the values
    sum = numbers.reduce((accumulator, currentValue) => {
        return accumulator + currentValue; // Adds the current value to the accumulator
    }, 0);
    
    average = sum / numbers.length; // Calculates the average
    
    print(average); // Prints the average
    

    Example of using map()

    The map() method creates a new array with the results of calling a function on every element in the calling array. The example below calculates the square of each number.

    
    numbers = [1, 2, 3, 4, 5];
    
    // Maps the numbers to their squares
    squaredNumbers = numbers.map(num => num * num);
    
    print(squaredNumbers); // Prints the array with the squared numbers
    

    Example of using filter()

    The filter() method returns a new array containing only the elements that pass the test implemented by the provided function. In the example below, we select the even numbers.

    
    numbers = [1, 2, 3, 4, 5];
    
    // Filters the numbers to get only the even ones
    evenNumbers = numbers.filter(num => num % 2 === 0);
    
    print(evenNumbers); // Prints the even numbers
    

    Example of using push()

    The push() method adds one or more elements to the end of an array and returns the new length of the array. The example below adds "kiwi" to the end of the fruits array.

    
    fruits = ['apple', 'banana', 'orange'];
    
    // Adds "kiwi" to the end of the array
    length = fruits.push("kiwi");
    
    print(fruits); // Prints the array with the new element
    print(length); // Prints the new length of the array
    

    Example of using find()

    The find() method returns the value of the first element in the array that satisfies the provided testing function. The example below finds the first number greater than 3.

    
    numbers = [1, 2, 3, 4, 5];
    
    // Finds the first number greater than 3
    found = numbers.find(x => x > 3);
    
    print(found); // Prints the found number
    

    Example of using pop()

    The pop() method removes the last element from an array and returns that element. In the example below, we remove the last element from the fruits array.

    
    fruits = ['apple', 'banana', 'orange'];
    
    // Removes the last element from the array
    removed = fruits.pop(); 
    
    print(removed); // Prints the removed element
    print(fruits);  // Prints the updated array
    

    Example of using join()

    The join() method converts an array into a string, joining the elements with the specified separator. In the example below, the elements are joined with ' - '.

    
    fruits = ['apple', 'banana', 'orange'];
    
    // Joins the array elements with ' - ' as the separator
    result = fruits.join(' - ');
    
    print(result); // Prints the resulting string
    

    Example of using unshift()

    The unshift() method adds one or more elements to the beginning of an array and returns the new length of the array. The example below adds "apple" and "kiwi" to the beginning of the fruits array.

    
    fruits = ['banana', 'orange'];
    
    // Inserts "apple" and "kiwi" at the beginning of the array
    length = fruits.unshift('apple', 'kiwi');
    
    print(fruits); // Prints the array with the new elements
    print(length); // Prints the new length of the array
    

    Example of using shift()

    The shift() method removes the first element from an array and returns that element. In the example below, we remove the first element from the fruits array.

    
    fruits = ['apple', 'banana', 'orange'];
    
    // Removes the first element from the array
    removed = fruits.shift();
    
    print(removed); // Prints the removed element
    print(fruits);  // Prints the updated array
    

    Example of using slice()

    The slice() method extracts a section of an array and returns a new array. In the example below, we obtain a slice of the fruits array from index 1 to 3 (exclusive).

    
    fruits = ['apple', 'banana', 'orange'];
    
    // Extracts a slice of the array from index 1 to 3
    part = fruits.slice(1, 3);
    
    print(part); // Prints the sliced array
    

    Example of using concat()

    The concat() method is used to merge two or more arrays and/or values. In the example below, we concatenate an additional array to the fruits array.

    
    fruits = ['apple', 'banana'];
    moreFruits = fruits.concat('orange', ['kiwi']);
    
    print(moreFruits); // Prints the concatenated array
    

    Example of using splice()

    The splice() method inserts elements at a specific position in an array, and can also remove elements. In the example below, we insert "kiwi" and "mango" at position 1.

    
    fruits = ['apple', 'banana', 'orange'];
    
    // Inserts "kiwi" and "mango" at position 1
    removed = fruits.splice(1, 0, 'kiwi', 'mango');
    
    print(removed); // Prints the removed elements
    print(fruits);  // Prints the updated array
    

    Example of using sort()

    The sort() method sorts the elements of an array according to the provided comparison function. In the example below, we sort an array of numbers in ascending order.

    
    numbers = [5, 3, 8, 1, 2];
    
    // Sorts the array in ascending order
    numbers.sort((a, b) => a - b);
    
    print(numbers); // Prints the sorted array
    

    Example of using JSON.stringify()

    The JSON.stringify() method converts a MelScript object into a JSON string, which is a standard text format for representing structured data. In the example below, we convert an object with various properties and nesting into a JSON string.

    
    obj = {
        name: "Alice",
        age: 25,
        hobbies: ["reading", "traveling"],
        active: true,
        address: {
            city: "Rio de Janeiro",
            state: "RJ"
        }
    };
    
    // Converts the object to a JSON string
    jsonString = JSON.stringify(obj);
    
    print(jsonString); // Prints the resulting JSON string
    

    Explanation: The JSON.stringify() function is used to convert a MelScript object into a JSON string. This is useful for sending data to a server or storing data in a text format. In the example above, the obj object is transformed into a JSON string, which is then printed.

    Example of using the toUpperCase() method

    Example of using the toUpperCase() method to convert a string to uppercase.

    
    text = "hello, world!";
    print(text.toUpperCase()); // Output: "HELLO, WORLD!"
    

    Explanation: The toUpperCase() method converts all the characters in the string to uppercase. In this example, the string "hello, world!" is transformed into "HELLO, WORLD!".

    Example of using the toLowerCase() method

    Example of using the toLowerCase() method to convert a string to lowercase.

    
    text = "HELLO, WORLD!";
    print(text.toLowerCase()); // Output: "hello, world!"
    

    Explanation: The toLowerCase() method converts all the characters in the string to lowercase. In this example, the string "HELLO, WORLD!" is transformed into "hello, world!".

    Example of using the toString() method

    Example of using the toString() method to convert numbers and other types to strings.

    
    number = 123456.789;
    print(number.toString()); // Output: "123456.789"
    
    boolean = true;
    print(boolean.toString()); // Output: "true"
    
    object = { key: "value", number: 42 };
    print(object.toString()); // Output: '{"key":"value","number":42}'
    

    Explanation: The toString() method converts different data types to a string representation. In this example, a number, a boolean value, and an object are converted to strings. The number 123456.789 is converted to "123456.789", the boolean true is converted to "true", and the object is converted to its JSON representation.

    Example of using the toFixed() method

    Example of using the toFixed() method to format a number with a specific number of decimal places.

    
    number = 123456.789;
    print(number.toFixed(2)); // Output: "123456.79"
    

    Explanation: The toFixed() method formats the number with the specified number of decimal places. In this example, the number 123456.789 is formatted with 2 decimal places, resulting in "123456.79".

    Example of using the toExponential() method

    Example of using the toExponential() method to convert a number to exponential notation.

    
    number = 123456.789;
    print(number.toExponential(2)); // Output: "1.23e+5"
    

    Explanation: The toExponential() method converts the number to exponential notation with the specified number of decimal places. In this example, the number 123456.789 is converted to "1.23e+5" with 2 decimal places.

    Example of using the toPrecision() method

    Example of using the toPrecision() method to adjust the number to a specified precision of digits.

    
    number = 123456.789;
    print(number.toPrecision(6)); // Output: "123456.8"
    

    Explanation: The toPrecision() method adjusts the number to the specified precision of digits. In this example, the number 123456.789 is rounded to "123456.8" with a precision of 6 digits.

    Example of using the toLocaleString() method

    Example of using the toLocaleString() method to format numbers and dates according to local conventions.

    
    number = 123456.789;
    print(number.toLocaleString('pt-BR')); // Output: "123.456,789"
    
    date = new Date('2024-08-17T10:00:00Z');
    print(date.toLocaleString('pt-BR')); // Output: "17/08/2024 07:00:00"
    
    array = [123456.789, 98765.432];
    print(array.toLocaleString('en-US')); // Output: "123,456.789,98,765.432"
    

    Explanation: The toLocaleString() method formats numbers and dates according to the specified local conventions. In the example, the number 123456.789 is formatted for the Brazilian locale, resulting in "123.456,789". The date is formatted for the Brazilian locale, resulting in "17/08/2024 07:00:00". The array is formatted for the US locale, resulting in "123,456.789,98,765.432".

    Update to version 1.0.3 RFZ

    In the new version 1.0.3 RFZ of MelScript, "RFZ" means "Rewritten From Scratch". This version was necessary due to the discovery of significant bugs in the previous code. Additionally, there was the complication that MelScript was being developed in a single editor that crashed, resulting in the complete loss of the code and leaving it with flaws. Therefore, the RFZ version was a complete rewrite to fix these issues and ensure a more stable and reliable operation of MelScript.

    The 1.0.3 RFZ version of MelScript was released on July 14, 2024, at 4:15 PM.

    Conclusion

    MelScript is a web programming language that honors the memory of Mel, Ravy Novais Sales' dog. Since its inception on June 13, 2024, MelScript has stood out for its simplicity and power, allowing developers of all levels to create interactive and dynamic web applications. With its 73 keywords, MelScript offers a wide range of features, making it easier to create customized and efficient user interfaces. Through MelScript, Ravy Novais Sales aims to make web programming more accessible and intuitive, perpetuating the legacy of his beloved dog Mel.

    w version 1.0.3 RFZ of MelScript, "RFZ" means "Rewritten From Scratch". This version was necessary due to the discovery of significant bugs in the previous code. Additionally, there was the complication that MelScript was being developed in a single editor that crashed, resulting in the complete loss of the code and leaving it with flaws. Therefore, the RFZ version was a complete rewrite to fix these issues and ensure a more stable and reliable operation of MelScript.

    The 1.0.3 RFZ version of MelScript was released on July 14, 2024, at 4:15 PM.

    Conclusion

    MelScript is a web programming language that honors the memory of Mel, Ravy Novais Sales' dog. Since its inception on June 13, 2024, MelScript has stood out for its simplicity and power, allowing developers of all levels to create interactive and dynamic web applications. With its 73 keywords, MelScript offers a wide range of features, making it easier to create customized and efficient user interfaces. Through MelScript, Ravy Novais Sales aims to make web programming more accessible and intuitive, perpetuating the legacy of his beloved dog Mel.