Showing preview only (321K chars total). Download the full file or copy to clipboard to get everything.
Repository: roberto-butti/some-drops-of-javascript
Branch: main
Commit: 14bf382c434f
Files: 166
Total size: 282.7 KB
Directory structure:
gitextract_291qlk5o/
├── .editorconfig
├── .github/
│ └── ISSUE_TEMPLATE/
│ └── add-new-function.md
├── .gitignore
├── .prettierrc
├── CONTRIBUTING.md
├── HACKTOBERFEST.md
├── LICENSE.txt
├── README.md
├── astro.config.mjs
├── bun.lockb
├── examples/
│ ├── 01-01_os-cpus.mjs
│ ├── 01-02_os-version.mjs
│ ├── 01-03_os-userinfo.mjs
│ ├── 01-04_os-freemem.mjs
│ ├── 01-05_process-env.mjs
│ ├── 01-06_os-totalmem.mjs
│ ├── 01-07_os-loadavg.mjs
│ ├── 01-08_os-networkinterfaces.mjs
│ ├── 01-09_process-exit.mjs
│ ├── 01-10_os-tmpdir.mjs
│ ├── 01-11_performance-now.mjs
│ ├── 02-01_array-join.mjs
│ ├── 02-02_array-includes.mjs
│ ├── 02-03_array-in.mjs
│ ├── 02-04_array-concat.mjs
│ ├── 02-05_array-merge_destructuring.mjs
│ ├── 02-06_array-set.mjs
│ ├── 02-07_array-fill.mjs
│ ├── 02-08_array-filter.mjs
│ ├── 02-09_array-every.mjs
│ ├── 02-10_array-some.mjs
│ ├── 02-11_array-map.mjs
│ ├── 02-12_array-reduce.mjs
│ ├── 02-13_array-splice.mjs
│ ├── 02-15_array-flat.mjs
│ ├── 02-16_array-findindex.mjs
│ ├── 02-17_array-at.mjs
│ ├── 02-18_array-flatmap.mjs
│ ├── 02-19_array-keys.mjs
│ ├── 02-20_array-entries.mjs
│ ├── 02-21_array-findlastindex.mjs
│ ├── 02-22_array-findlastind.mjs
│ ├── 02-23_array-copywithin.mjs
│ ├── 02-24_array-entries.mjs
│ ├── 02-25_array-values.mjs
│ ├── 02-26_array-sort.mjs
│ ├── 02-27_array-reverse.mjs
│ ├── 02-28_array-push-pop.mjs
│ ├── 02-29_array-shift-unshift.mjs
│ ├── 03-01_op-typeof.mjs
│ ├── 03-02_path-sep.mjs
│ ├── 03-03_os-eol.mjs
│ ├── 03-12_object-groupby.mjs
│ ├── 05-01_str-concat.mjs
│ ├── 05-02_str-padding.mjs
│ ├── 05-03_str-includes.mjs
│ ├── 05-04_str-slice.mjs
│ ├── 05-05_str-indexOf.mjs
│ ├── 05-06_str-repeat.mjs
│ ├── 05-07_str-split.mjs
│ ├── 05-08_str-toUppercase.mjs
│ ├── 05-09_str-toLowercase.mjs
│ ├── 05-10_str-startsWith.mjs
│ ├── 05-11_str-replaceAll.mjs
│ ├── 05-12_str-trimstart-trimend.mjs
│ ├── 05-13_str-trim.mjs
│ ├── 05-14_str-endsWith.mjs
│ ├── 05-15_str-substring.mjs
│ ├── 05-16_str-replace.mjs
│ ├── 05-17_str-lastIndexOf.mjs
│ ├── 05-18_str-match.mjs
│ └── 06-01_process-cwd.mjs
├── list-of-functions.md
├── package.json
├── src/
│ ├── components/
│ │ ├── about-block.astro
│ │ ├── arrow.astro
│ │ └── hero.astro
│ ├── content/
│ │ └── docs/
│ │ ├── 00-intro/
│ │ │ ├── 00_intro.md
│ │ │ ├── 01_contributing.md
│ │ │ ├── 01_hacktoberfest-2024.md
│ │ │ └── 02_runtime.md
│ │ ├── 01-system/
│ │ │ ├── 00_system_intro.md
│ │ │ ├── 01_os-cpus.md
│ │ │ ├── 02_os-version.md
│ │ │ ├── 03_os-userinfo.md
│ │ │ ├── 04_process-env.md
│ │ │ ├── 05_os-freemem.md
│ │ │ ├── 06_os-totalmem.md
│ │ │ ├── 07_os-loadavg.md
│ │ │ ├── 08_os-networkinterfaces.md
│ │ │ ├── 09_process-exit.md
│ │ │ ├── 10_os-tmpdir.md
│ │ │ └── 11_performance-now.md
│ │ ├── 02-array/
│ │ │ ├── 00_array.md
│ │ │ ├── 01_array-join.md
│ │ │ ├── 02_array-includes.md
│ │ │ ├── 03_array-in.md
│ │ │ ├── 04_array-concat.md
│ │ │ ├── 05_array-merge_destructuring.md
│ │ │ ├── 06_array-set.md
│ │ │ ├── 07_array-fill.md
│ │ │ ├── 08_array-filter.md
│ │ │ ├── 09_array-every.md
│ │ │ ├── 10_array-some.md
│ │ │ ├── 11_array-map.md
│ │ │ ├── 12_array-reduce.md
│ │ │ ├── 13_array-splice.md
│ │ │ ├── 14_array-slice.md
│ │ │ ├── 15_array-flat.md
│ │ │ ├── 16_array-findindex.md
│ │ │ ├── 17_array-at.md
│ │ │ ├── 18_array-flatmap.md
│ │ │ ├── 19_array-keys.md
│ │ │ ├── 20_array-entries.md
│ │ │ ├── 21_array-findlastindex.md
│ │ │ ├── 22-array-findlast.md
│ │ │ ├── 23-array-copywithin.md
│ │ │ ├── 24-array-entries.md
│ │ │ ├── 25_array-values.md
│ │ │ ├── 26_array-sort.md
│ │ │ ├── 27_array-reverse.md
│ │ │ ├── 28_array-push-pop.md
│ │ │ └── 29_array-shift-unshift.md
│ │ ├── 03-var/
│ │ │ ├── 00_var-obj-const.md
│ │ │ ├── 01_op-typeof.md
│ │ │ ├── 02_path-sep.md
│ │ │ ├── 03_os-eol.md
│ │ │ ├── 04_object-getOwnPropertyNames.md
│ │ │ ├── 05_object-keys.md
│ │ │ ├── 06_object-values.md
│ │ │ ├── 07_object-entries.md
│ │ │ ├── 08_object-freeze.md
│ │ │ ├── 09_object-seal.md
│ │ │ ├── 10_object-isFrozen.md
│ │ │ ├── 11_object-isSealed.md
│ │ │ └── 12_object-groupby.md
│ │ ├── 04-functions/
│ │ │ └── 00_functions.md
│ │ ├── 05-string/
│ │ │ ├── 00_string.md
│ │ │ ├── 01_str-concat.md
│ │ │ ├── 02_str-padding.md
│ │ │ ├── 03_str-includes.md
│ │ │ ├── 04_str-slice.md
│ │ │ ├── 05_str-indexOf.md
│ │ │ ├── 06_str-repeat.md
│ │ │ ├── 07_str-split.md
│ │ │ ├── 08_str-toUppercase.md
│ │ │ ├── 09_str-toLowercase.md
│ │ │ ├── 10_str-startsWith.md
│ │ │ ├── 11_str-replaceAll.md
│ │ │ ├── 12_str-trimstart-trimend.md
│ │ │ ├── 13_str-trim.md
│ │ │ ├── 14_str-endsWith.md
│ │ │ ├── 15_str-substring.md
│ │ │ ├── 16_str-replace.md
│ │ │ ├── 17_str-lastIndexOf.md
│ │ │ └── 18_str-match.md
│ │ ├── 06-files/
│ │ │ ├── 00_files.md
│ │ │ └── 01_files-cwd.md
│ │ └── index.mdx
│ ├── content.config.ts
│ ├── env.d.ts
│ └── styles/
│ ├── custom.css
│ └── tailwind.css
├── tailwind.config.mjs
├── tsconfig.json
└── vercel.json
================================================
FILE CONTENTS
================================================
================================================
FILE: .editorconfig
================================================
root = true
[*]
indent_style = space
indent_size = 2
end_of_line = lf
insert_final_newline = true
charset = utf-8
trim_trailing_whitespace = true
[*.json]
indent_style = space
indent_size = 2
[*.md]
trim_trailing_whitespace = false
================================================
FILE: .github/ISSUE_TEMPLATE/add-new-function.md
================================================
---
name: Add new JavaScript Function
about: Add new file for explaining a new JavaScript function
title: 'New Function: '
labels: enhancement, hacktoberfest, good+first+issue
assignees: ''
---
## What
Add new method documentation file for a new JavaScript function in `src/content/docs`.
The instructions about defining the file's name are documented in the `CONTRIBUTING.md` file.
## Description
Function name: example `os.version()`
Function description: ...
File name: example `01-system/02_os-version.md`
## Checklist
- [ ] create the file with the proper name
- [ ] create the documentation of the function
- [ ] write example in `examples` directory
- [ ] execute `bun run format-examples-bun` or `npm run format-examples`
- [ ] commit and open the PR.
Must read:
- https://github.com/roberto-butti/some-drops-of-javascript/blob/main/HACKTOBERFEST.md
- https://github.com/roberto-butti/some-drops-of-javascript/blob/main/CONTRIBUTING.md
================================================
FILE: .gitignore
================================================
# build output
dist/
# generated types
.astro/
# dependencies
node_modules/
package-lock.json
# logs
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
# environment variables
.env
.env.production
# macOS-specific files
.DS_Store
.vscode/
================================================
FILE: .prettierrc
================================================
{
"trailingComma": "es5",
"tabWidth": 2,
"useTabs": false,
"semi": false,
"singleQuote": true
}
================================================
FILE: CONTRIBUTING.md
================================================
# How to contribute
The goal is to build an open-source book about JavaScript functions for new users in the JavaScript ecosystem.
This book collects some useful, unknown, underrated JavaScript functions or stuff discovered, used, and learned during JavaScript's daily use.
Using frameworks daily (like React, Vue, and Svelte), sometimes the perception of the power of the language and the basic functionalities provided by the JavaScript core could be lost. I see that usually, I used to look at the framework documentation or look for a package in Packagist for the system, array, and string functions instead of using some core functionalities provided by the language.
The goal is to cover more and more functions, so the goal is to create new pages, and each page covers 1 specific function.
The functions are grouped into topics:
- System
- Array
- Variables and types
- String
- File
- Extra bonus chapter where I'm collecting some nice cheatsheet
Each function is explained with the description, and examples in markdown files in the `src/content/docs` directory.
## The file name convention
We have all the Markdown files in the `src/content/docs` directory where you can find the folders for each topic (`00-intro`, `01-system`, `02-array`, etc.
Each topic ( Intro, System, Array) has a specific folder with the format
- 2 digits (00 , 01) as topic identifier (progressive number)
- A "dash" separator `-`
- A slug for the topic (intro, system, array)
Following the format above you can have folders like: `00-intro`, `01-system`, `02-array`.
Each folder contains files. Each file shows a JavaScript function.
The file name has the format:
- 2 digits (00 , 01) as function identifier (progressive number);
- An "underscore" separator `_`;
- A subtopic slug (by default is the same of the topic), for example `system`, `os`, `process` etc;
- A "dash" separator `-`;
- A slug for the function (cpus, version, userinfo);
- The extension (md or mdx).
Following the format described above, you can have in the folder `01-system` files with names like `01_os-cpus.md`, `02_os-version.md` etc
For example, for the file `01-system/02_os-version.md`:
- `01`: (the first group of digits) is the progressive number for the `system` topic;
- `system`: is the slug of the topic;
- `02`: is the progress number for functions
- `os`: the subtopic slug (os is for the operating system)
- `version`: the function explained
- `md`: the extension
## Running locally the project
The rendering part of all the Markdown files is managed via Astro3 + Starlight theme and Bun.
If you want to read and browse the HTML eBook and see your changes in realtime when you are working on markdown files in the root directory of the cloned repository (where you have the `package.json`, `bun.lockb` files):
- install the packages via `bun install`;
- run the local server via `bun run dev`
If you want to build the HTML files, you can run the following command:
~~~
bun run build
~~~
If you want to see the preview of the built files you can run the following command:
~~~
bun run preview
~~~
## Submit ideas or feature requests
* Take a look if your request is already there https://github.com/roberto-butti/some-drops-of-javascript/issues
* If it is not present, you can create a new one https://github.com/roberto-butti/some-drops-of-javascript/issues/new
## Submit your changes
If you want to submit a pull request, please send a [GitHub Pull Request to Some drops of JavaScript](https://github.com/roberto-butti/some-drops-of-javascript/pull/new/main) with a clear list of what you've done (read more about [pull requests](https://help.github.com/articles/about-pull-requests)).
Please use "main" branch for pull request.
## Instructions for writing a markdown file for a JavaScript Function
Each chapter in this book focuses on a single JavaScript function or method. The goal is to provide comprehensive, well-structured, and practical documentation that helps developers understand and use the function effectively. Follow the guidelines below to structure your chapter.
### Chapter Structure
1. Frontmatter (Mandatory)
The frontmatter section should be placed at the beginning of the markdown file and enclosed between triple dashes (---). It provides essential metadata about the chapter.
Example for mandatory fields:
```
---
title: 'Modifying an Array'
description: 'Adding, removing, and replacing elements in an array with JavaScript.'
sidebar:
label: Modifying Array
---
```
Where:
- `title`: The feature implemented via the function
- `description`: A brief overview of what the function does.
- `sidebar.label`: the label used in the left menu
2. Introduction
Start with a clear and concise explanation of what the function does. Highlight its primary use cases and why it's useful.
3. Syntax and Parameters
- Provide the general syntax of the function, including its parameters and their expected types.
- Describe each parameter in detail, including whether it is optional or required and what its role is.
- Include the return type of the funtion
4. Use cases
Provide several practical use cases demonstrating how the function can be used to solve real-world problems.
Each use case should include a clear explanation of the problem being solved, a code example, and a detailed breakdown of how the function is being used.
5. Common Pitfalls
- Discuss common mistakes or misunderstandings related to the function.
- Provide guidance on how to avoid these issues.
6. Additional Resources
Include links to relevant documentation, tutorials, or other chapters in the book for further reading.
================================================
FILE: HACKTOBERFEST.md
================================================
# Hacktoberfest and "Some drops of JavaScript"

Hello amazing contributors! 👋
We are excited to invite you to join our Hacktoberfest celebration by contributing to our open-source book project. We welcome contributors with various skills and interests, so whether you're a JavaScript expert, a grammar enthusiast, a design aficionado, or just someone with a passion for learning and sharing knowledge, there's a place for you in our community.
## Ways to Contribute
Here are some of the ways you can get involved:
- **JavaScript Wizards**: Write pages for JavaScript functions, share your expertise, and help fellow developers understand some nice JavaScript functions.
- **Reviewers and Editors**: Help ensure the quality and accuracy of the content by reviewing and editing pages.
- **Grammar Enthusiasts**: Review and improve the English grammar and readability of our documentation.
- **Idea Contributors**: Suggest JavaScript functions that should be covered in the documentation. Your insights are valuable!
- **Design Gurus**: Propose design changes that can enhance the overall user experience of our book.
## How to Get Started
1. Fork the repository to your GitHub account.
2. Create a new branch for your contributions.
3. Make your changes and commit them.
4. Open a pull request to merge your changes back into the main repository.
For more detailed instructions, please check our [Contribution Guidelines](CONTRIBUTING.md).
## Join the Conversation
Have questions or want to discuss your contributions? Join us on the [repository issue section](https://github.com/roberto-butti/some-drops-of-javascript/issues), where you can create issues but also create suggestions, feature requests.
## Say Thank You!
We deeply appreciate your willingness to contribute to the open-source book "Some drops of JavaScript". Your efforts make a significant impact on the JavaScript community, and we're grateful for your support.
Happy Hacking! 🚀
================================================
FILE: LICENSE.txt
================================================
Attribution-NonCommercial-ShareAlike 4.0 International
=======================================================================
Creative Commons Corporation ("Creative Commons") is not a law firm and
does not provide legal services or legal advice. Distribution of
Creative Commons public licenses does not create a lawyer-client or
other relationship. Creative Commons makes its licenses and related
information available on an "as-is" basis. Creative Commons gives no
warranties regarding its licenses, any material licensed under their
terms and conditions, or any related information. Creative Commons
disclaims all liability for damages resulting from their use to the
fullest extent possible.
Using Creative Commons Public Licenses
Creative Commons public licenses provide a standard set of terms and
conditions that creators and other rights holders may use to share
original works of authorship and other material subject to copyright
and certain other rights specified in the public license below. The
following considerations are for informational purposes only, are not
exhaustive, and do not form part of our licenses.
Considerations for licensors: Our public licenses are
intended for use by those authorized to give the public
permission to use material in ways otherwise restricted by
copyright and certain other rights. Our licenses are
irrevocable. Licensors should read and understand the terms
and conditions of the license they choose before applying it.
Licensors should also secure all rights necessary before
applying our licenses so that the public can reuse the
material as expected. Licensors should clearly mark any
material not subject to the license. This includes other CC-
licensed material, or material used under an exception or
limitation to copyright. More considerations for licensors:
wiki.creativecommons.org/Considerations_for_licensors
Considerations for the public: By using one of our public
licenses, a licensor grants the public permission to use the
licensed material under specified terms and conditions. If
the licensor's permission is not necessary for any reason--for
example, because of any applicable exception or limitation to
copyright--then that use is not regulated by the license. Our
licenses grant only permissions under copyright and certain
other rights that a licensor has authority to grant. Use of
the licensed material may still be restricted for other
reasons, including because others have copyright or other
rights in the material. A licensor may make special requests,
such as asking that all changes be marked or described.
Although not required by our licenses, you are encouraged to
respect those requests where reasonable. More considerations
for the public:
wiki.creativecommons.org/Considerations_for_licensees
=======================================================================
Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International
Public License
By exercising the Licensed Rights (defined below), You accept and agree
to be bound by the terms and conditions of this Creative Commons
Attribution-NonCommercial-ShareAlike 4.0 International Public License
("Public License"). To the extent this Public License may be
interpreted as a contract, You are granted the Licensed Rights in
consideration of Your acceptance of these terms and conditions, and the
Licensor grants You such rights in consideration of benefits the
Licensor receives from making the Licensed Material available under
these terms and conditions.
Section 1 -- Definitions.
a. Adapted Material means material subject to Copyright and Similar
Rights that is derived from or based upon the Licensed Material
and in which the Licensed Material is translated, altered,
arranged, transformed, or otherwise modified in a manner requiring
permission under the Copyright and Similar Rights held by the
Licensor. For purposes of this Public License, where the Licensed
Material is a musical work, performance, or sound recording,
Adapted Material is always produced where the Licensed Material is
synched in timed relation with a moving image.
b. Adapter's License means the license You apply to Your Copyright
and Similar Rights in Your contributions to Adapted Material in
accordance with the terms and conditions of this Public License.
c. BY-NC-SA Compatible License means a license listed at
creativecommons.org/compatiblelicenses, approved by Creative
Commons as essentially the equivalent of this Public License.
d. Copyright and Similar Rights means copyright and/or similar rights
closely related to copyright including, without limitation,
performance, broadcast, sound recording, and Sui Generis Database
Rights, without regard to how the rights are labeled or
categorized. For purposes of this Public License, the rights
specified in Section 2(b)(1)-(2) are not Copyright and Similar
Rights.
e. Effective Technological Measures means those measures that, in the
absence of proper authority, may not be circumvented under laws
fulfilling obligations under Article 11 of the WIPO Copyright
Treaty adopted on December 20, 1996, and/or similar international
agreements.
f. Exceptions and Limitations means fair use, fair dealing, and/or
any other exception or limitation to Copyright and Similar Rights
that applies to Your use of the Licensed Material.
g. License Elements means the license attributes listed in the name
of a Creative Commons Public License. The License Elements of this
Public License are Attribution, NonCommercial, and ShareAlike.
h. Licensed Material means the artistic or literary work, database,
or other material to which the Licensor applied this Public
License.
i. Licensed Rights means the rights granted to You subject to the
terms and conditions of this Public License, which are limited to
all Copyright and Similar Rights that apply to Your use of the
Licensed Material and that the Licensor has authority to license.
j. Licensor means the individual(s) or entity(ies) granting rights
under this Public License.
k. NonCommercial means not primarily intended for or directed towards
commercial advantage or monetary compensation. For purposes of
this Public License, the exchange of the Licensed Material for
other material subject to Copyright and Similar Rights by digital
file-sharing or similar means is NonCommercial provided there is
no payment of monetary compensation in connection with the
exchange.
l. Share means to provide material to the public by any means or
process that requires permission under the Licensed Rights, such
as reproduction, public display, public performance, distribution,
dissemination, communication, or importation, and to make material
available to the public including in ways that members of the
public may access the material from a place and at a time
individually chosen by them.
m. Sui Generis Database Rights means rights other than copyright
resulting from Directive 96/9/EC of the European Parliament and of
the Council of 11 March 1996 on the legal protection of databases,
as amended and/or succeeded, as well as other essentially
equivalent rights anywhere in the world.
n. You means the individual or entity exercising the Licensed Rights
under this Public License. Your has a corresponding meaning.
Section 2 -- Scope.
a. License grant.
1. Subject to the terms and conditions of this Public License,
the Licensor hereby grants You a worldwide, royalty-free,
non-sublicensable, non-exclusive, irrevocable license to
exercise the Licensed Rights in the Licensed Material to:
a. reproduce and Share the Licensed Material, in whole or
in part, for NonCommercial purposes only; and
b. produce, reproduce, and Share Adapted Material for
NonCommercial purposes only.
2. Exceptions and Limitations. For the avoidance of doubt, where
Exceptions and Limitations apply to Your use, this Public
License does not apply, and You do not need to comply with
its terms and conditions.
3. Term. The term of this Public License is specified in Section
6(a).
4. Media and formats; technical modifications allowed. The
Licensor authorizes You to exercise the Licensed Rights in
all media and formats whether now known or hereafter created,
and to make technical modifications necessary to do so. The
Licensor waives and/or agrees not to assert any right or
authority to forbid You from making technical modifications
necessary to exercise the Licensed Rights, including
technical modifications necessary to circumvent Effective
Technological Measures. For purposes of this Public License,
simply making modifications authorized by this Section 2(a)
(4) never produces Adapted Material.
5. Downstream recipients.
a. Offer from the Licensor -- Licensed Material. Every
recipient of the Licensed Material automatically
receives an offer from the Licensor to exercise the
Licensed Rights under the terms and conditions of this
Public License.
b. Additional offer from the Licensor -- Adapted Material.
Every recipient of Adapted Material from You
automatically receives an offer from the Licensor to
exercise the Licensed Rights in the Adapted Material
under the conditions of the Adapter's License You apply.
c. No downstream restrictions. You may not offer or impose
any additional or different terms or conditions on, or
apply any Effective Technological Measures to, the
Licensed Material if doing so restricts exercise of the
Licensed Rights by any recipient of the Licensed
Material.
6. No endorsement. Nothing in this Public License constitutes or
may be construed as permission to assert or imply that You
are, or that Your use of the Licensed Material is, connected
with, or sponsored, endorsed, or granted official status by,
the Licensor or others designated to receive attribution as
provided in Section 3(a)(1)(A)(i).
b. Other rights.
1. Moral rights, such as the right of integrity, are not
licensed under this Public License, nor are publicity,
privacy, and/or other similar personality rights; however, to
the extent possible, the Licensor waives and/or agrees not to
assert any such rights held by the Licensor to the limited
extent necessary to allow You to exercise the Licensed
Rights, but not otherwise.
2. Patent and trademark rights are not licensed under this
Public License.
3. To the extent possible, the Licensor waives any right to
collect royalties from You for the exercise of the Licensed
Rights, whether directly or through a collecting society
under any voluntary or waivable statutory or compulsory
licensing scheme. In all other cases the Licensor expressly
reserves any right to collect such royalties, including when
the Licensed Material is used other than for NonCommercial
purposes.
Section 3 -- License Conditions.
Your exercise of the Licensed Rights is expressly made subject to the
following conditions.
a. Attribution.
1. If You Share the Licensed Material (including in modified
form), You must:
a. retain the following if it is supplied by the Licensor
with the Licensed Material:
i. identification of the creator(s) of the Licensed
Material and any others designated to receive
attribution, in any reasonable manner requested by
the Licensor (including by pseudonym if
designated);
ii. a copyright notice;
iii. a notice that refers to this Public License;
iv. a notice that refers to the disclaimer of
warranties;
v. a URI or hyperlink to the Licensed Material to the
extent reasonably practicable;
b. indicate if You modified the Licensed Material and
retain an indication of any previous modifications; and
c. indicate the Licensed Material is licensed under this
Public License, and include the text of, or the URI or
hyperlink to, this Public License.
2. You may satisfy the conditions in Section 3(a)(1) in any
reasonable manner based on the medium, means, and context in
which You Share the Licensed Material. For example, it may be
reasonable to satisfy the conditions by providing a URI or
hyperlink to a resource that includes the required
information.
3. If requested by the Licensor, You must remove any of the
information required by Section 3(a)(1)(A) to the extent
reasonably practicable.
b. ShareAlike.
In addition to the conditions in Section 3(a), if You Share
Adapted Material You produce, the following conditions also apply.
1. The Adapter's License You apply must be a Creative Commons
license with the same License Elements, this version or
later, or a BY-NC-SA Compatible License.
2. You must include the text of, or the URI or hyperlink to, the
Adapter's License You apply. You may satisfy this condition
in any reasonable manner based on the medium, means, and
context in which You Share Adapted Material.
3. You may not offer or impose any additional or different terms
or conditions on, or apply any Effective Technological
Measures to, Adapted Material that restrict exercise of the
rights granted under the Adapter's License You apply.
Section 4 -- Sui Generis Database Rights.
Where the Licensed Rights include Sui Generis Database Rights that
apply to Your use of the Licensed Material:
a. for the avoidance of doubt, Section 2(a)(1) grants You the right
to extract, reuse, reproduce, and Share all or a substantial
portion of the contents of the database for NonCommercial purposes
only;
b. if You include all or a substantial portion of the database
contents in a database in which You have Sui Generis Database
Rights, then the database in which You have Sui Generis Database
Rights (but not its individual contents) is Adapted Material,
including for purposes of Section 3(b); and
c. You must comply with the conditions in Section 3(a) if You Share
all or a substantial portion of the contents of the database.
For the avoidance of doubt, this Section 4 supplements and does not
replace Your obligations under this Public License where the Licensed
Rights include other Copyright and Similar Rights.
Section 5 -- Disclaimer of Warranties and Limitation of Liability.
a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE
EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS
AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF
ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS,
IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION,
WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR
PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS,
ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT
KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT
ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.
b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE
TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION,
NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT,
INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES,
COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR
USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN
ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR
DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR
IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.
c. The disclaimer of warranties and limitation of liability provided
above shall be interpreted in a manner that, to the extent
possible, most closely approximates an absolute disclaimer and
waiver of all liability.
Section 6 -- Term and Termination.
a. This Public License applies for the term of the Copyright and
Similar Rights licensed here. However, if You fail to comply with
this Public License, then Your rights under this Public License
terminate automatically.
b. Where Your right to use the Licensed Material has terminated under
Section 6(a), it reinstates:
1. automatically as of the date the violation is cured, provided
it is cured within 30 days of Your discovery of the
violation; or
2. upon express reinstatement by the Licensor.
For the avoidance of doubt, this Section 6(b) does not affect any
right the Licensor may have to seek remedies for Your violations
of this Public License.
c. For the avoidance of doubt, the Licensor may also offer the
Licensed Material under separate terms or conditions or stop
distributing the Licensed Material at any time; however, doing so
will not terminate this Public License.
d. Sections 1, 5, 6, 7, and 8 survive termination of this Public
License.
Section 7 -- Other Terms and Conditions.
a. The Licensor shall not be bound by any additional or different
terms or conditions communicated by You unless expressly agreed.
b. Any arrangements, understandings, or agreements regarding the
Licensed Material not stated herein are separate from and
independent of the terms and conditions of this Public License.
Section 8 -- Interpretation.
a. For the avoidance of doubt, this Public License does not, and
shall not be interpreted to, reduce, limit, restrict, or impose
conditions on any use of the Licensed Material that could lawfully
be made without permission under this Public License.
b. To the extent possible, if any provision of this Public License is
deemed unenforceable, it shall be automatically reformed to the
minimum extent necessary to make it enforceable. If the provision
cannot be reformed, it shall be severed from this Public License
without affecting the enforceability of the remaining terms and
conditions.
c. No term or condition of this Public License will be waived and no
failure to comply consented to unless expressly agreed to by the
Licensor.
d. Nothing in this Public License constitutes or may be interpreted
as a limitation upon, or waiver of, any privileges and immunities
that apply to the Licensor or You, including from the legal
processes of any jurisdiction or authority.
=======================================================================
Creative Commons is not a party to its public
licenses. Notwithstanding, Creative Commons may elect to apply one of
its public licenses to material it publishes and in those instances
will be considered the “Licensor.” The text of the Creative Commons
public licenses is dedicated to the public domain under the CC0 Public
Domain Dedication. Except for the limited purpose of indicating that
material is shared under a Creative Commons public license or as
otherwise permitted by the Creative Commons policies published at
creativecommons.org/policies, Creative Commons does not authorize the
use of the trademark "Creative Commons" or any other trademark or logo
of Creative Commons without its prior written consent including,
without limitation, in connection with any unauthorized modifications
to any of its public licenses or any other arrangements,
understandings, or agreements concerning use of licensed material. For
the avoidance of doubt, this paragraph does not form part of the
public licenses.
Creative Commons may be contacted at creativecommons.org.
================================================
FILE: README.md
================================================
# Welcome to Some drops of JavaScript

## The reason why
This book collects some useful, unknown, underrated JavaScript functions or stuff discovered, used, and learned during JavaScript daily use.
Using JavaScript frameworks/libraries daily (like React, Vue, Angular), sometimes the perception of the power of the language and the basic functionalities provided by the JavaScript core could be lost.
I see that usually, I used to look at the framework documentation or look for a package in Npm for the system, array, and string functions instead of using core functionalities provided by the language.
While I wrote this HTML-book, I also wrote some scripts to better understand the behavior of the functions. You can find these examples here: https://github.com/roberto-butti/some-drops-of-javascript in the _examples_ directory.
> We are excited to invite you to join our Hacktoberfest celebration by contributing to the open-source book project. More [info here](HACKTOBERFEST.md)
### Requirements
The code used in this book is tested with **Bun** and **NodeJs version 18 (LTS)**.
**Bun** is a JavaScript runtime, package manager, bundler and test runner built from scratch using the Zig programming language. It was designed by Jarred Sumner as a drop-in replacement for Node.js. Bun uses JavaScriptCore as the JavaScript engine, unlike Node.js and Deno, which both use V8. The official website is: https://bun.sh/ .
**Node.js** is an open-source, cross-platform JavaScript runtime environment, and you can obtain Node.js on the official https://nodejs.org/ website.
### Continuous release
I was thinking to print this book, but I think that is not so eco-friendly and a book about development could be improved daily in terms of spellchecking and the content and examples. So, I expect to adopt the same approach in the software with the CI/CD, with a continuous release of the book.
Releases:
- **W.I.P.** the 1.0.0 version is not yet released: writing... ;
> The book is **Work in Progress**, the list of the functions covered by the book at the moment are listed in [list-of-functions.md](list-of-functions.md) file
So, if you have any feedback, or you want to suggest some corrections, feel free to open an issue here: https://github.com/roberto-butti/some-drops-of-javascript/issues
### Where to find this book
This book is available TBD.
- Markdown files: [content/](content/);
- Example files: [examples/](examples/);
### Thanks to...
Thanks to all the Open Source community.
### License
"Some drops of JavaScript" (c) by Roberto Butti
"Some drops of JavaScript" is licensed under a
Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.
You should have received a copy of the license along with this
work. If not, see <http://creativecommons.org/licenses/by-nc-sa/4.0/>.
================================================
FILE: astro.config.mjs
================================================
import { defineConfig } from 'astro/config';
import starlight from '@astrojs/starlight';
import tailwind from '@astrojs/tailwind'
// https://astro.build/config
export default defineConfig({
site: 'https://drops-of-javascript.hi-folks.dev/',
integrations: [
starlight({
title: 'Some drops of JavaScript',
customCss: ['./src/styles/tailwind.css', './src/styles/custom.css'],
head: [
{
tag: 'meta',
attrs: {
property: 'og:image',
content:
'https://raw.githubusercontent.com/roberto-butti/some-drops-of-javascript/main/public/header.png',
},
},
{
tag: 'meta',
attrs: {
property: 'twitter:image',
content:
'https://raw.githubusercontent.com/roberto-butti/some-drops-of-javascript/main/public/header.png',
},
},
],
editLink: {
baseUrl:
'https://github.com/roberto-butti/some-drops-of-javascript/edit/main',
},
social: {
github: 'https://github.com/roberto-butti/some-drops-of-javascript',
},
sidebar: [
{
label: '📔 Intro',
autogenerate: { directory: '00-intro' },
collapsed: false,
},
{
label: '🧑💻 System',
autogenerate: { directory: '01-system' },
collapsed: true,
},
{
label: '📚 Array',
autogenerate: { directory: '02-array' },
collapsed: true,
},
{
label: '🧑🎨 Vars, Objects, Operators',
autogenerate: { directory: '03-var' },
collapsed: true,
},
{
label: '💫 Functions',
autogenerate: { directory: '04-functions' },
collapsed: true,
},
{
label: '🪕 Strings',
autogenerate: { directory: '05-string' },
collapsed: true,
},
{
label: '🗃️ Files',
autogenerate: { directory: '06-files' },
collapsed: true,
},
{
label: '[ 🧑💻 Sources ]',
items: [
// Each item here is one entry in the navigation menu.
{
label: 'Markdown',
link: 'https://github.com/roberto-butti/some-drops-of-javascript/tree/main/src/content/docs',
},
{
label: 'Examples',
link: 'https://github.com/roberto-butti/some-drops-of-javascript/tree/main/examples',
},
],
collapsed: true,
},
],
}),
tailwind({
// Disable the default base styles:
applyBaseStyles: false,
}),
],
})
================================================
FILE: examples/01-01_os-cpus.mjs
================================================
import { cpus } from 'os'
// getting the CPUs via os.cpus() and looping
cpus().forEach((cpu, index) => {
// each cpu item has: mode, speed and times
console.log(`CPU ${index + 1}:`)
console.log(` Model: ${cpu.model}`)
console.log(` Speed: ${cpu.speed} MHz`)
console.log(` Time (milliseconds) spent in`)
console.log(` User mode : ${cpu.times.user} ms.`)
console.log(` Nice mode : ${cpu.times.nice} ms.`)
console.log(` System mode : ${cpu.times.sys} ms.`)
console.log(` For interrupts : ${cpu.times.irq} ms.`)
})
console.log('*** Calculating the CPU utilization ***')
cpus().forEach((cpu, index) => {
const { user, nice, sys, idle, irq } = cpu.times
const total = user + nice + sys + idle + irq
const usage = ((total - idle) / total) * 100
console.log(`CPU ${index + 1} Usage: ${usage.toFixed(2)}%`)
})
console.log('*** Identifying the Number of Logical CPU Cores ***')
const numCpus = cpus().length
console.log(`Number of logical CPU cores: ${numCpus}`)
================================================
FILE: examples/01-02_os-version.mjs
================================================
import { version, platform, release, machine } from 'os'
const v = version()
console.log(`Version: ${v}`)
// Example
// Version: Darwin Kernel Version 22.5.0: Thu Jun 8 22:22:20 PDT 2023; root:xnu-8796.121.3~7/RELEASE_ARM64_T6000
const p = platform()
console.log(`Platform: ${p}`)
// Example
// Platform: darwin
const r = release()
console.log(`Release: ${r}`)
// Example
// Release: 22.5.0
const m = machine()
console.log(`Machine: ${m}`)
// Example
// Machine: arm64
================================================
FILE: examples/01-03_os-userinfo.mjs
================================================
import { userInfo } from 'os'
const u = userInfo()
console.log('Hi, %s here your infos:', u.username)
console.table(u)
/*
┌──────────┬──────────────────┐
│ (index) │ Values │
├──────────┼──────────────────┤
│ uid │ 501 │
│ gid │ 20 │
│ username │ 'roberto' │
│ homedir │ '/Users/roberto' │
│ shell │ '/bin/zsh' │
└──────────┴──────────────────┘
*/
================================================
FILE: examples/01-04_os-freemem.mjs
================================================
import { freemem } from 'os'
const m = freemem()
console.log('Hi, the free memory is %d bytes', m)
console.log('Hi, the free memory is %d kilobytes', m / 1024)
console.log('Hi, the free memory is %d megabytes', m / 1024 / 1024)
================================================
FILE: examples/01-05_process-env.mjs
================================================
console.log(process.env)
console.log(process.env.PATH)
const envVarName = 'PATH'
if (envVarName in process.env) {
console.log(process.env[envVarName])
} else {
console.log('no %s defined', envVarName)
}
Object.keys(process.env).forEach(function (key, index) {
console.log(key, index, process.env[key])
})
================================================
FILE: examples/01-06_os-totalmem.mjs
================================================
import { totalmem } from 'os'
const m = totalmem()
console.log('Hi, the total memory is %d bytes', m)
console.log('Hi, the total memory is %d kilobytes', m / 1024)
console.log('Hi, the total memory is %d megabytes', m / 1024 / 1024)
console.log('Hi, the total memory is %d gigabytes', m / 1024 / 1024 / 1024)
================================================
FILE: examples/01-07_os-loadavg.mjs
================================================
import { loadavg } from 'os'
const la = loadavg()
console.log(la[0], la[1], la[2])
================================================
FILE: examples/01-08_os-networkinterfaces.mjs
================================================
import { networkInterfaces } from 'os'
const ni = networkInterfaces()
Object.keys(ni).forEach(function (key, index) {
// each interfaces has an array
ni[key].forEach(function (element, index) {
// selecting only family === 4 (ipv4 interfaces)
if (element.family === 4) {
console.log('IP ADDRESS: ' + element.address) // IP address
}
})
// console.log(key, index, ni[key])
})
================================================
FILE: examples/01-09_process-exit.mjs
================================================
console.log('Executing ...')
process.exit(99)
console.log('Never executed')
================================================
FILE: examples/01-10_os-tmpdir.mjs
================================================
import { tmpdir } from 'os'
console.log('Temporary directory: %s', tmpdir())
================================================
FILE: examples/01-11_performance-now.mjs
================================================
let startTime = performance.now()
console.log('Starting')
console.log(performance.now() - startTime, startTime)
startTime = performance.now()
console.log('Again')
console.log(performance.now() - startTime, startTime)
startTime = performance.now()
console.log('Again and again')
console.log(performance.now() - startTime, startTime)
================================================
FILE: examples/02-01_array-join.mjs
================================================
const elements = ['🥝', '🍓', '🍋']
console.log(elements.join())
// expected output: "🥝,🍓,🍋"
console.log(elements.join('-'))
// expected output: "🥝-🍓-🍋"
================================================
FILE: examples/02-02_array-includes.mjs
================================================
const elements = ['🥝', '🍓', '🍋']
console.log(elements.includes('🍓'))
// Does the array include the 🍓?
// expected output: true
console.log(elements.includes('🍓', 2))
// Does the array (from index 2) include the 🍓?
// expected output: false
console.log(elements.includes('🍋', 2))
// Does the array (from index 2) include the 🍋?
// expected output: true
console.log(elements.includes('🧃'))
// Does the array include the 🧃?
// expected output: false
================================================
FILE: examples/02-03_array-in.mjs
================================================
const fruits = {
strawberry: 'Strawberry',
kiwi: 'Kiwi',
lemon: 'Lemon',
}
console.table(fruits)
if ('kiwi' in fruits) {
console.log('Kiwi is present')
}
console.log('kiwi' in fruits ? 'Yes! Kiwi' : 'ther is no kiwi here')
// checking if the attribute is not defined can fails in this specific case:
fruits.something = undefined
if (fruits.somethingelse === undefined) {
console.log('Somethingelse attribute does not exist')
}
if (fruits.something === undefined) {
console.log('Something attribute exists but the value is undefined')
}
const fruitsObject = {}
fruitsObject.strawberry = 'Strawberry'
fruitsObject.kiwi = 'Kiwi'
fruitsObject.lemon = 'Lemon'
console.dir(fruitsObject)
console.log('kiwi' in fruitsObject) // true
console.log('something' in fruitsObject) // false
const fruitsArray = []
fruitsArray.push('Strawberry')
fruitsArray.push('Kiwi')
fruitsArray.push('Lemon')
console.dir(fruitsArray)
console.log(2 in fruitsArray) // true
console.log(3 in fruitsArray) // false
================================================
FILE: examples/02-04_array-concat.mjs
================================================
const array1 = ['a', 'b', 'c']
const array2 = ['d', 'e', 'f']
console.dir(array1.concat(array2))
const array3 = ['g', 'h']
console.dir(array1.concat(array2, array3))
//
console.dir([].concat(array1, array2, array3))
console.dir(array1 + array2 + array3)
================================================
FILE: examples/02-05_array-merge_destructuring.mjs
================================================
const array1 = ['a', 'b', 'c']
const array2 = ['d', 'e', 'f']
console.dir([...array1, ...array2])
// [ 'a', 'b', 'c', 'd', 'e', 'f' ]
const array3 = ['g', 'h']
console.dir([...array1, ...array2, ...array3])
console.dir([...array3, ...array2, ...array1])
================================================
FILE: examples/02-06_array-set.mjs
================================================
const array = ['a', 'b', 'c', 'b', 'd', 'e', 'a']
const unique = [...new Set(array)]
console.dir(unique)
================================================
FILE: examples/02-07_array-fill.mjs
================================================
const array = ['a', 'b', 'c', 'b', 'd', 'e', 'a']
array.fill(0)
console.dir(array)
// [ 0, 0, 0, 0, 0, 0, 0 ]
const array2 = ['a', 'b', 'c', 'b', 'd', 'e', 'a']
array2.fill(0, 1)
console.dir(array2)
// [ 'a', 0, 0, 0, 0, 0, 0 ]
const array3 = ['a', 'b', 'c', 'b', 'd', 'e', 'a']
array3.fill(0, 1, 3)
console.dir(array3)
// [ 'a', 0, 0, 'b', 'd', 'e', 'a' ]
const array4 = ['a', 'b', 'c', 'b', 'd', 'e', 'a']
array4.fill(0, -1) // last element
console.dir(array4)
// [ 'a', 'b', 'c', 'b', 'd', 'e', 0 ]
array4.fill(0, -2) // last 2 elements
console.dir(array4)
// [ 'a', 'b', 'c', 'b', 'd', 0, 0 ]
================================================
FILE: examples/02-08_array-filter.mjs
================================================
const numbers = [3, 75, 42, 13, 69]
const resultNumbers = numbers.filter((number) => number >= 50)
console.dir(resultNumbers)
// output: Array [ 75, 69 ]
const elements = [
{ product: 'Desk', price: 200, active: true },
{ product: 'Chair', price: 100, active: true },
{ product: 'Door', price: 300, active: false },
{ product: 'Bookcase', price: 150, active: true },
{ product: 'Door', price: 100, active: true },
]
const resultElements = elements.filter((element) => element.price >= 150)
console.dir(resultElements)
/*
output:
Array [
{ product: 'Desk', price: 200, active: true },
{ product: 'Door', price: 300, active: false },
{ product: 'Bookcase', price: 150, active: true }
]
*/
const resultActiveElements = elements.filter(
(element) => element.active && element.price >= 150
)
console.dir(resultActiveElements)
/*
output:
Array [
{ product: 'Desk', price: 200, active: true },
{ product: 'Bookcase', price: 150, active: true }
]
*/
================================================
FILE: examples/02-09_array-every.mjs
================================================
const array = [32, 30, 39, 29, 100, 43]
console.log(array.every((currentValue) => currentValue > 25))
================================================
FILE: examples/02-10_array-some.mjs
================================================
const array = [32, 30, 39, 29, 100, 43]
console.log(array.some((currentValue) => currentValue > 90))
================================================
FILE: examples/02-11_array-map.mjs
================================================
const numbers = [1, 2, 3, 4, 5]
// Using map() method to create a new array by doubling each number
const doubledNumbers = numbers.map((number) => number * 2)
console.log('Original Array:', numbers)
console.log('Doubled Array:', doubledNumbers)
================================================
FILE: examples/02-12_array-reduce.mjs
================================================
const numbers = [1, 2, 3, 4, 5]
const sumWithInitialValue = numbers.reduce((accumulator, currentValue) => {
return accumulator + currentValue
}, 0) //Here 0 is an initial value to the accumulator
/* Here if we do not mention initialValue '0', then initial value of accumulator will be first array value
and the currentValue will be second value of Array. */
const sumWithoutInitialValue = numbers.reduce((acc, curr) => {
return acc + curr
})
console.log('SumWithInitialValue:', sumWithInitialValue)
console.log('SumWithoutInitialValue:', sumWithoutInitialValue)
//Counting the number of occurrences of elements in an array using reduce():
const fruits = ['apple', 'banana', 'orange', 'apple', 'banana', 'apple']
const fruitCounter = fruits.reduce((accumulator, currentFruit) => {
accumulator[currentFruit] = (accumulator[currentFruit] || 0) + 1
return accumulator
}, {})
console.log('Occurrences:', fruitCounter)
// Output: Occurrences: { apple: 3, banana: 2, orange: 1 }
//Finding the Maximum and Minimum Values using reduce():
const numbersArray = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
const max = numbersArray.reduce((accumulator, currentValue) => {
return Math.max(accumulator, currentValue)
})
const min = numbersArray.reduce((accumulator, currentValue) => {
return Math.min(accumulator, currentValue)
})
console.log('Maximum value:', max) // Output: Maximum value: 9
console.log('Minimum value:', min) // Output: Minimum value: 1
//Transforming an Array into a Different Data Structure using reduce():
const data = [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' },
{ id: 3, name: 'Charlie' },
]
const transformedData = data.reduce((accumulator, currentValue) => {
accumulator[currentValue.id] = currentValue.name
return accumulator
}, {})
console.log('Transformed Data:', transformedData)
// Output: Transformed Data: { 1: 'Alice', 2: 'Bob', 3: 'Charlie' }
================================================
FILE: examples/02-13_array-splice.mjs
================================================
// Using splice() method to modify an array by removing, adding, and replacing elements:
const fruits = ['Apple', 'Banana', 'Cherry', 'Date']
// Removing elements
const removedFruits = fruits.splice(1, 2) // Removes 2 elements starting from index 1
console.log('Modified array:', fruits) // Output: ['Apple', 'Date']
console.log('Removed elements:', removedFruits) // Output: ['Banana', 'Cherry']
// Adding elements
fruits.splice(1, 0, 'Blueberry', 'Coconut') // Adds two elements at index 1
console.log('Array after adding:', fruits) // Output: ['Apple', 'Blueberry', 'Coconut', 'Date']
// Replacing elements
fruits.splice(2, 1, 'Dragonfruit') // Replaces 1 element at index 2
console.log('Array after replacing:', fruits) // Output: ['Apple', 'Blueberry', 'Dragonfruit', 'Date']
// Using splice() method to shuffle an array:
const numbers = [1, 2, 3, 4, 5]
for (let i = numbers.length - 1; i > 0; i--) {
// Generate a random index 'j' between 0 and 'i' (inclusive)
const j = Math.floor(Math.random() * (i + 1))
// Remove the element at index 'j' from the array
const [removed] = numbers.splice(j, 1)
// Insert the removed element back into the array at index 'i'
numbers.splice(i, 0, removed)
}
console.log('Shuffled array:', numbers)
// Using splice() method to swap elements:
const arr = ['a', 'b', 'c', 'd']
function swap(arr, index1, index2) {
const [elem1] = arr.splice(index1, 1)
const [elem2] = arr.splice(index2 - 1, 1) // '-1' adjusts for the earlier removal of 'elem1'
arr.splice(index1, 0, elem2)
arr.splice(index2, 0, elem1)
}
swap(arr, 1, 3)
console.log('Swapped array:', arr) // Output: ['a', 'd', 'c', 'b']
================================================
FILE: examples/02-15_array-flat.mjs
================================================
const arr = [[1, 2, 3], [4, 5, 6], 7, 8]
console.log(arr.flat()) // Output: [1, 2, 3, 4, 5, 6, 7, 8]
const arr2 = [1, 2, [3, 4, [5, 6]]]
console.log(arr2.flat()) // Output: [1, 2, 3, 4, [5, 6]]
console.log(arr2.flat(2)) // Output: [1, 2, 3, 4, 5, 6]
const arr5 = [1, 2, , 4, 5]
console.log(arr5.flat()) // Output: [1, 2, 4, 5]
================================================
FILE: examples/02-16_array-findindex.mjs
================================================
// using findIndex() method to get the first index of the element that passes the test
const ages = [3, 10, 18, 20]
// storing the index value in index variable
let index = ages.findIndex(checkAge)
// printing the index value (3)
console.log(index)
// testing function, passed as a callback to findIndex() method
function checkAge(age) {
return age > 18
}
// findIndex() returns -1 when no element match is found
const newAges = [3, 10, 13, 15]
// storing the index value in index variable
index = newAges.findIndex(checkAge)
// printing the index value (-1)
console.log(index)
================================================
FILE: examples/02-17_array-at.mjs
================================================
const fruit = ['banana', 'mango', 'orange', 'apple']
console.log(fruit.at(0)) // Output: "banana"
const item = fruit.at(2)
console.log(item) // Output: "orange"
// Using a negative index
console.log(fruit.at(-1)) // Output: "apple"
const item2 = fruit.at(-3)
console.log(item2) // Output: "mango"
================================================
FILE: examples/02-18_array-flatmap.mjs
================================================
const arr = [
[1, 2],
[3, 4],
[5, 6],
]
console.log(arr.flatMap((x) => x)) // Output: [1, 2, 3, 4, 5, 6]
const arr2 = [
[1, 2],
[3, 4],
[5, 6],
]
console.log(arr2.flatMap((x) => x.map((n) => n * 2))) // Output: [2, 4, 6, 8, 10, 12]
const arr3 = [[1, 2], , [3, 4], [5, 6]]
console.log(arr3.flatMap((x) => x)) // Output: [1, 2, 3, 4, 5, 6]
const arr4 = [
['hello', 'world'],
['foo', 'bar'],
]
console.log(arr4.flatMap((x) => x.join(' '))) // Output: ["hello world", "foo bar"]
================================================
FILE: examples/02-19_array-keys.mjs
================================================
const fruit = ['watermelon', 'pineapple', 'pear', 'mango']
const fruitKeys = fruit.keys()
for (let key of fruitKeys) {
console.log(key)
}
// Output:
// 0
// 1
// 2
// 3
// with sparse arrays
const animal = ['dog', , 'cat']
for (let key of animal.keys()) {
console.log(`Animal at index ${key} is ${animal[key]}`)
}
// Output:
// Animal at index 0 is dog
// Animal at index 1 is undefined
// Animal at index 2 is cat
================================================
FILE: examples/02-20_array-entries.mjs
================================================
// Examples for Array.entries()
// Basic usage
const fruits = ['Apple', 'Banana', 'Orange']
console.log('Original array:', fruits)
console.log('\nIterating over entries:')
const iterator = fruits.entries()
for (const entry of iterator) {
console.log(entry)
}
// Output:
// [0, "Apple"]
// [1, "Banana"]
// [2, "Orange"]
// Destructuring in loop
const colors = ['red', 'green', 'blue']
console.log('\nOriginal array:', colors)
console.log('Destructuring entries in loop:')
const iterator2 = colors.entries()
for (const [index, value] of iterator2) {
console.log(`${index}: ${value}`)
}
// Output:
// "0: red"
// "1: green"
// "2: blue"
// Converting iterator to array
const numbers = [1, 2, 3, 4, 5]
console.log('\nOriginal array:', numbers)
const iterator3 = numbers.entries()
const entriesArray = [...iterator3]
console.log('Entries as array:', entriesArray)
// Output: [[0, 1], [1, 2], [2, 3], [3, 4], [4, 5]]
// Using with iterator methods
const letters = ['a', 'b', 'c']
console.log('\nOriginal array:', letters)
const iterator4 = letters.entries()
console.log('First entry:', iterator4.next().value)
console.log('Second entry:', iterator4.next().value)
console.log('Third entry:', iterator4.next().value)
console.log('Is iteration complete?', iterator4.next().done)
// Output:
// [0, "a"]
// [1, "b"]
// [2, "c"]
// true
// Creating a Map from an array
function arrayToMap(array) {
const map = new Map()
for (const [index, value] of array.entries()) {
map.set(index, value)
}
return map
}
const fruitsMap = arrayToMap(fruits)
console.log('\nCreating a Map from array:')
console.log('Map.get(1):', fruitsMap.get(1)) // Output: "Banana"
console.log('Map has 0:', fruitsMap.has(0)) // Output: true
console.log('Map has 3:', fruitsMap.has(3)) // Output: false
// Filtering with index awareness
function filterWithIndex(array, callback) {
const result = []
for (const [index, value] of array.entries()) {
if (callback(value, index)) {
result.push(value)
}
}
return result
}
const nums = [10, 20, 30, 40, 50]
console.log('\nOriginal array:', nums)
const filteredNumbers = filterWithIndex(nums, (value, index) => index % 2 === 0)
console.log('Elements at even indices:', filteredNumbers) // Output: [10, 30, 50]
// Creating an object with array indices as keys
function arrayToObject(array) {
return Object.fromEntries(array.entries())
}
const fruitsObject = arrayToObject(fruits)
console.log('\nCreating an object from array:')
console.log(fruitsObject)
// Output: { 0: "Apple", 1: "Banana", 2: "Orange" }
// Comparison with other array iterator methods
const arr = ['a', 'b', 'c']
console.log('\nOriginal array:', arr)
console.log('\nDifferent iterator methods:')
// entries() - returns [index, value] pairs
console.log('entries():')
const entryIterator = arr.entries()
for (const entry of entryIterator) {
console.log(entry)
}
// Output: [0, "a"], [1, "b"], [2, "c"]
// keys() - returns indices
console.log('\nkeys():')
const keyIterator = arr.keys()
for (const key of keyIterator) {
console.log(key)
}
// Output: 0, 1, 2
// values() - returns values
console.log('\nvalues():')
const valueIterator = arr.values()
for (const value of valueIterator) {
console.log(value)
}
// Output: "a", "b", "c"
================================================
FILE: examples/02-21_array-findlastindex.mjs
================================================
// using findLastIndex() method to get the last index of the element that passes the test
const numbers = [5, 12, 8, 130, 44]
// storing the last index value in lastIndex variable
let lastIndex = numbers.findLastIndex(checkLargeNumber)
// printing last index value
console.log(lastIndex)
// testing function, passed as a callback to findLastIndex() method
function checkLargeNumber(num) {
return num > 10
}
// findLastIndex() returns -1 when no element match is found
const new_numbers = [1, 2, 3, 4, 5]
// storing the last index value in lastIndex variable
lastIndex = new_numbers.findLastIndex(checkLargeNumber)
// printing the lastIndex variable value (-1)
console.log(lastIndex)
================================================
FILE: examples/02-22_array-findlastind.mjs
================================================
const numbers = [5, 12, 8, 130, 44]
const lastLargeNumber = numbers.findLast((element) => element > 10)
console.log('Last number larger than 10:', lastLargeNumber)
// Expected output: 44
const fruits = ['apple', 'banana', 'cherry', 'date', 'elderberry']
const lastLongFruit = fruits.findLast((fruit) => fruit.length > 5)
console.log('Last fruit with more than 5 characters:', lastLongFruit)
// Expected output: elderberry
const people = [
{ name: 'Tom', age: 25 },
{ name: 'Bill', age: 30 },
{ name: 'Kate', age: 28 },
{ name: 'Pete', age: 32 },
]
const lastAdult = people.findLast((person) => person.age >= 30)
console.log('Last person aged 30 or older:', lastAdult)
// Expected output: { name: 'Pete', age: 32 }
// When no element satisfies the condition
const noMatch = numbers.findLast((num) => num > 1000)
console.log('No number larger than 1000:', noMatch)
// Expected output: undefined
================================================
FILE: examples/02-23_array-copywithin.mjs
================================================
const numbers = [1, 2, 3, 4, 5]
console.log('Original Array:', numbers) //expected output: [1, 2, 3, 4, 5]
// Using copyWithin() method to create a new array where method copies to index 1 all elements from index 3 to the end
console.log('New Array:', numbers.copyWithin(1, 3)) //expected output: [1, 4, 5, 4, 5]
// In this case, the method copies to index 1 all elements from index 0 to index 3
console.log('New Array:', numbers.copyWithin(1, 0, 3)) //expected output: [1, 1, 2, 3, 5]
// It's possible use negative values
console.log('New Array:', numbers.copyWithin(-2, -3, -1)) //expected output: [1, 2, 3, 3, 4]
// copyWithin() will propagate empty slots
const halfBlankArray = [1, , 3]
console.log('New Array:', halfBlankArray.copyWithin(2, 1, 2)) //expected output: [1,,]
// The method reads the length property of 'obj' and then manipulates the integer indices involved.
const obj = {
length: 5,
3: 1,
}
console.log(Array.prototype.copyWithin.call(obj, 0, 3)) // expected output: { '0': 1, '3': 1, length: 5 }
================================================
FILE: examples/02-24_array-entries.mjs
================================================
const fruits = ['Banana', 'Apple', 'Mango']
const fruitsEntries = fruits.entries()
for (const [index, fruit] of fruits.entries()) {
console.log(index, fruit)
}
for (const fruit of fruitsEntries) {
console.log(fruit)
}
// 0 'Banana'
// 1 'Apple'
// 2 'Mango'
for (const fruit of [, "Banana"].entries()) {
console.log(fruit)
}
// [0, undefined]
// [1, 'Banana']
console.log(fruitsEntries.next().value + " " + fruitsEntries.next().value);
// "0,Banana 1,Apple"
const user = {
name: 'John',
age: 30
}
console.log(Object.entries(user)); // [['name', 'John'], ['age', 30]]
const mapping = new Map();
mapping.set("0", "Peach");
mapping.set(1, "Mango");
mapping.set({}, "Banana");
const mapIter = mapping.entries();
console.log(mapIter.next().value); // ["0", "Peach"]
console.log(mapIter.next().value); // [1, "Mango"]
console.log(mapIter.next().value); // [Object, "Banana"]
================================================
FILE: examples/02-25_array-values.mjs
================================================
// Examples for Array.values()
// Basic usage
const fruits = ['Apple', 'Banana', 'Orange']
console.log('Original array:', fruits)
console.log('\nIterating over values:')
const iterator = fruits.values()
for (const value of iterator) {
console.log(value)
}
// Output:
// Apple
// Banana
// Orange
// Converting iterator to array
const numbers = [1, 2, 3, 4, 5]
console.log('\nOriginal array:', numbers)
const iterator2 = numbers.values()
const valuesArray = [...iterator2]
console.log('Values as array:', valuesArray)
// Output: [1, 2, 3, 4, 5]
// Using with iterator methods
const colors = ['red', 'green', 'blue']
console.log('\nOriginal array:', colors)
const iterator3 = colors.values()
console.log('First value:', iterator3.next().value)
console.log('Second value:', iterator3.next().value)
console.log('Third value:', iterator3.next().value)
console.log('Is iteration complete?', iterator3.next().done)
// Output:
// red
// green
// blue
// true
// Iterating over sparse arrays
const sparseArray = [1, , 3, , 5]
console.log('\nSparse array:', sparseArray)
console.log('Iterating over sparse array values:')
const iterator4 = sparseArray.values()
for (const value of iterator4) {
console.log(value)
}
// Output:
// 1
// undefined
// 3
// undefined
// 5
// Iterating over array values
function processArrayValues(array) {
console.log('\nProcessing array values:')
const iterator = array.values()
for (const value of iterator) {
console.log(`Processing: ${value}`)
}
}
processArrayValues(['a', 'b', 'c'])
// Output:
// Processing: a
// Processing: b
// Processing: c
// Creating multiple independent iterators
const data = [10, 20, 30]
console.log('\nOriginal array:', data)
const iterator5 = data.values()
const iterator6 = data.values()
console.log('First iterator - first value:', iterator5.next().value)
console.log('First iterator - second value:', iterator5.next().value)
console.log('Second iterator - first value:', iterator6.next().value)
// Output:
// 10
// 20
// 10 (independent iterator)
// Working with other iteration methods
const items = ['item1', 'item2', 'item3']
console.log('\nOriginal array:', items)
const iterator7 = items.values()
// Convert to array and apply array methods
const upperCaseItems = [...iterator7].map(item => item.toUpperCase())
console.log('Uppercase items:', upperCaseItems)
// Output: ["ITEM1", "ITEM2", "ITEM3"]
// Comparison with other array iterator methods
const arr = ['a', 'b', 'c']
console.log('\nOriginal array:', arr)
console.log('\nDifferent iterator methods:')
// values() - returns values
console.log('values():')
const valueIterator = arr.values()
for (const val of valueIterator) {
console.log(val)
}
// Output: "a", "b", "c"
// keys() - returns indices
console.log('\nkeys():')
const keyIterator = arr.keys()
for (const key of keyIterator) {
console.log(key)
}
// Output: 0, 1, 2
// entries() - returns [index, value] pairs
console.log('\nentries():')
const entryIterator = arr.entries()
for (const entry of entryIterator) {
console.log(entry)
}
// Output: [0, "a"], [1, "b"], [2, "c"]
================================================
FILE: examples/02-26_array-sort.mjs
================================================
// Examples for Array.sort()
// Basic usage - sorting strings
const fruits = ['Banana', 'Orange', 'Apple', 'Mango']
console.log('Original array:', fruits)
fruits.sort()
console.log('Sorted array:', fruits)
// Output: ["Apple", "Banana", "Mango", "Orange"]
// Sorting numbers - default behavior
const numbers = [40, 100, 1, 5, 25, 10]
console.log('\nOriginal numbers:', numbers)
numbers.sort()
console.log('Sorted numbers (default):', numbers)
// Output: [1, 10, 100, 25, 40, 5] - not what you might expect!
// Using a compare function for numbers - ascending order
const numbers2 = [40, 100, 1, 5, 25, 10]
console.log('\nOriginal numbers:', numbers2)
numbers2.sort((a, b) => a - b)
console.log('Sorted numbers (ascending):', numbers2)
// Output: [1, 5, 10, 25, 40, 100]
// Sorting in descending order
const numbers3 = [40, 100, 1, 5, 25, 10]
console.log('\nOriginal numbers:', numbers3)
numbers3.sort((a, b) => b - a)
console.log('Sorted numbers (descending):', numbers3)
// Output: [100, 40, 25, 10, 5, 1]
// Sorting objects by property
const people = [
{ name: 'John', age: 30 },
{ name: 'Alice', age: 25 },
{ name: 'Bob', age: 35 }
]
console.log('\nOriginal people array:')
console.log(people)
// Sort by age
people.sort((a, b) => a.age - b.age)
console.log('\nPeople sorted by age:')
console.log(people)
// Output: [{ name: 'Alice', age: 25 }, { name: 'John', age: 30 }, { name: 'Bob', age: 35 }]
// Sort by name
people.sort((a, b) => a.name.localeCompare(b.name))
console.log('\nPeople sorted by name:')
console.log(people)
// Output: [{ name: 'Alice', age: 25 }, { name: 'Bob', age: 35 }, { name: 'John', age: 30 }]
// Case-insensitive sorting
const cities = ['Vienna', 'berlin', 'Amsterdam', 'paris']
console.log('\nOriginal cities array:', cities)
cities.sort((a, b) => a.toLowerCase().localeCompare(b.toLowerCase()))
console.log('Cities sorted case-insensitive:', cities)
// Output: ["Amsterdam", "berlin", "paris", "Vienna"]
// Custom sorting logic
const items = [
{ name: 'Edward', value: 21 },
{ name: 'Sharpe', value: 37 },
{ name: 'And', value: 45 },
{ name: 'The', value: -12 },
{ name: 'Magnetic', value: 13 },
{ name: 'Zeros', value: 37 }
]
console.log('\nOriginal items array:')
console.log(items)
// Sort by value, then by name if values are equal
items.sort((a, b) => {
if (a.value !== b.value) {
return a.value - b.value
}
return a.name.localeCompare(b.name)
})
console.log('\nItems sorted by value, then by name:')
console.log(items)
// Sorting with internationalization
const names = ['Österreich', 'Andorra', 'Vietnam', 'Zaire', 'Åland']
console.log('\nOriginal names array:', names)
const collator = new Intl.Collator('en')
names.sort((a, b) => collator.compare(a, b))
console.log('Names sorted with Intl.Collator:', names)
// Output: ["Åland", "Andorra", "Österreich", "Vietnam", "Zaire"]
// Demonstrating stability of sort
const data = [
{ id: 1, value: 'a' },
{ id: 2, value: 'b' },
{ id: 3, value: 'a' },
{ id: 4, value: 'c' }
]
console.log('\nOriginal data array:')
console.log(data)
// Sort by value
data.sort((a, b) => a.value.localeCompare(b.value))
console.log('\nData sorted by value (stable sort):')
console.log(data)
// Output: The elements with value 'a' maintain their relative order (id 1 before id 3)
================================================
FILE: examples/02-27_array-reverse.mjs
================================================
// Examples for Array.reverse()
// Basic usage
const fruits = ['Apple', 'Banana', 'Orange', 'Mango']
console.log('Original array:', fruits)
fruits.reverse()
console.log('Reversed array:', fruits)
// Output: ["Mango", "Orange", "Banana", "Apple"]
// Reversing a numeric array
const numbers = [1, 2, 3, 4, 5]
console.log('\nOriginal numbers:', numbers)
numbers.reverse()
console.log('Reversed numbers:', numbers)
// Output: [5, 4, 3, 2, 1]
// Chaining with other array methods
const originalNumbers = [1, 2, 3, 4, 5]
console.log('\nOriginal array:', originalNumbers)
const reversed = [...originalNumbers].reverse()
console.log('Original array (unchanged):', originalNumbers)
console.log('New reversed array:', reversed)
// Output:
// Original: [1, 2, 3, 4, 5]
// Reversed: [5, 4, 3, 2, 1]
// Reversing a string using array methods
const str = 'Hello World'
console.log('\nOriginal string:', str)
const reversedStr = str.split('').reverse().join('')
console.log('Reversed string:', reversedStr)
// Output: "dlroW olleH"
// Reversing a copy of an array
function reverseArrayCopy(array) {
return [...array].reverse()
}
const original = [1, 2, 3, 4, 5]
console.log('\nOriginal array:', original)
const reversedCopy = reverseArrayCopy(original)
console.log('Original array (unchanged):', original)
console.log('Reversed copy:', reversedCopy)
// Output:
// Original: [1, 2, 3, 4, 5]
// Reversed: [5, 4, 3, 2, 1]
// Implementing a palindrome check
function isPalindrome(str) {
// Remove non-alphanumeric characters and convert to lowercase
const cleanStr = str.toLowerCase().replace(/[^a-z0-9]/g, '')
// Compare with its reverse
return cleanStr === cleanStr.split('').reverse().join('')
}
console.log('\nPalindrome checks:')
console.log('Is "A man, a plan, a canal: Panama" a palindrome?',
isPalindrome('A man, a plan, a canal: Panama')) // Output: true
console.log('Is "race a car" a palindrome?',
isPalindrome('race a car')) // Output: false
// Creating a reverse iterator
function* reverseIterator(array) {
for (let i = array.length - 1; i >= 0; i--) {
yield array[i]
}
}
const letters = ['a', 'b', 'c', 'd']
console.log('\nOriginal array:', letters)
console.log('Using reverse iterator:')
for (const item of reverseIterator(letters)) {
console.log(item)
}
// Output:
// "d"
// "c"
// "b"
// "a"
// Reversing nested arrays
const nestedArray = [[1, 2], [3, 4], [5, 6]]
console.log('\nOriginal nested array:', nestedArray)
nestedArray.reverse()
console.log('Top-level reversed:', nestedArray)
// Output: [[5, 6], [3, 4], [1, 2]]
// Deep reversing nested arrays
const nestedArray2 = [[1, 2], [3, 4], [5, 6]]
console.log('\nOriginal nested array:', nestedArray2)
const deepReversed = nestedArray2.map(subArray => subArray.reverse()).reverse()
console.log('Deep reversed:', deepReversed)
// Output: [[6, 5], [4, 3], [2, 1]]
================================================
FILE: examples/02-28_array-push-pop.mjs
================================================
// Examples for Array.push() and Array.pop()
// Basic usage of push()
const fruits = ['Apple', 'Banana']
console.log('Original array:', fruits)
const newLength = fruits.push('Orange')
console.log('After push():', fruits)
console.log('New length:', newLength)
// Output:
// ["Apple", "Banana", "Orange"]
// 3
// Adding multiple elements with push()
const numbers = [1, 2]
console.log('\nOriginal array:', numbers)
const multiPushLength = numbers.push(3, 4, 5)
console.log('After push() with multiple elements:', numbers)
console.log('New length:', multiPushLength)
// Output:
// [1, 2, 3, 4, 5]
// 5
// Basic usage of pop()
const vegetables = ['Carrot', 'Broccoli', 'Spinach']
console.log('\nOriginal array:', vegetables)
const removedItem = vegetables.pop()
console.log('After pop():', vegetables)
console.log('Removed item:', removedItem)
// Output:
// ["Carrot", "Broccoli"]
// "Spinach"
// Popping from an empty array
const emptyArray = []
console.log('\nEmpty array:', emptyArray)
const removedFromEmpty = emptyArray.pop()
console.log('After pop() on empty array:', emptyArray)
console.log('Removed item (undefined):', removedFromEmpty)
// Output:
// []
// undefined
// Implementing a Stack data structure
console.log('\n--- Stack Implementation ---')
class Stack {
constructor() {
this.items = []
}
push(element) {
return this.items.push(element)
}
pop() {
if (this.items.length === 0) {
return 'Underflow'
}
return this.items.pop()
}
peek() {
return this.items[this.items.length - 1]
}
isEmpty() {
return this.items.length === 0
}
size() {
return this.items.length
}
clear() {
this.items = []
}
}
const stack = new Stack()
console.log('Is stack empty?', stack.isEmpty()) // true
stack.push(10)
stack.push(20)
stack.push(30)
console.log('Stack after pushes:', stack.items)
console.log('Stack size:', stack.size()) // 3
console.log('Top element:', stack.peek()) // 30
console.log('Popped element:', stack.pop()) // 30
console.log('Stack after pop:', stack.items)
console.log('Stack size after pop:', stack.size()) // 2
stack.clear()
console.log('Stack after clear:', stack.items)
console.log('Is stack empty after clear?', stack.isEmpty()) // true
// Building and managing a task queue
console.log('\n--- Task Queue Example ---')
const taskQueue = []
// Add tasks to the queue
taskQueue.push('Task 1')
taskQueue.push('Task 2')
taskQueue.push('Task 3')
console.log('Current queue:', taskQueue) // ["Task 1", "Task 2", "Task 3"]
// Process tasks in a LIFO (Last In, First Out) order
console.log('Processing tasks:')
while (taskQueue.length > 0) {
const currentTask = taskQueue.pop()
console.log('Processing:', currentTask)
}
console.log('Queue after processing:', taskQueue) // []
// Manipulating a history stack
console.log('\n--- Browser History Example ---')
const browserHistory = []
// Navigate to pages
function navigateTo(page) {
browserHistory.push(page)
console.log(`Navigated to ${page}`)
}
// Go back one page
function goBack() {
if (browserHistory.length > 1) {
browserHistory.pop() // Remove current page
const previousPage = browserHistory[browserHistory.length - 1]
console.log(`Navigated back to ${previousPage}`)
return previousPage
} else {
console.log('No previous page to navigate to')
return null
}
}
navigateTo('Home')
navigateTo('Products')
navigateTo('Product Details')
console.log('Current history stack:', browserHistory)
console.log('Current page:', browserHistory[browserHistory.length - 1])
goBack() // Back to Products
console.log('History stack after going back:', browserHistory)
goBack() // Back to Home
console.log('History stack after going back again:', browserHistory)
================================================
FILE: examples/02-29_array-shift-unshift.mjs
================================================
// Examples for Array.shift() and Array.unshift()
// Basic usage of shift()
const fruits = ['Apple', 'Banana', 'Orange']
console.log('Original array:', fruits)
const removedItem = fruits.shift()
console.log('After shift():', fruits)
console.log('Removed item:', removedItem)
// Output:
// ["Banana", "Orange"]
// "Apple"
// Shifting from an empty array
const emptyArray = []
console.log('\nEmpty array:', emptyArray)
const removedFromEmpty = emptyArray.shift()
console.log('After shift() on empty array:', emptyArray)
console.log('Removed item (undefined):', removedFromEmpty)
// Output:
// []
// undefined
// Basic usage of unshift()
const vegetables = ['Broccoli', 'Spinach']
console.log('\nOriginal array:', vegetables)
const newLength = vegetables.unshift('Carrot')
console.log('After unshift():', vegetables)
console.log('New length:', newLength)
// Output:
// ["Carrot", "Broccoli", "Spinach"]
// 3
// Adding multiple elements with unshift()
const numbers = [3, 4, 5]
console.log('\nOriginal array:', numbers)
const multiUnshiftLength = numbers.unshift(1, 2)
console.log('After unshift() with multiple elements:', numbers)
console.log('New length:', multiUnshiftLength)
// Output:
// [1, 2, 3, 4, 5]
// 5
// Implementing a Queue data structure
console.log('\n--- Queue Implementation ---')
class Queue {
constructor() {
this.items = []
}
enqueue(element) {
return this.items.push(element)
}
dequeue() {
if (this.items.length === 0) {
return 'Underflow'
}
return this.items.shift()
}
front() {
if (this.items.length === 0) {
return 'No elements in Queue'
}
return this.items[0]
}
isEmpty() {
return this.items.length === 0
}
size() {
return this.items.length
}
clear() {
this.items = []
}
}
const queue = new Queue()
console.log('Is queue empty?', queue.isEmpty()) // true
queue.enqueue(10)
queue.enqueue(20)
queue.enqueue(30)
console.log('Queue after enqueues:', queue.items)
console.log('Queue size:', queue.size()) // 3
console.log('Front element:', queue.front()) // 10
console.log('Dequeued element:', queue.dequeue()) // 10
console.log('Queue after dequeue:', queue.items)
console.log('Queue size after dequeue:', queue.size()) // 2
console.log('New front element:', queue.front()) // 20
queue.clear()
console.log('Queue after clear:', queue.items)
console.log('Is queue empty after clear?', queue.isEmpty()) // true
// Processing tasks in order
console.log('\n--- Task Processing Example ---')
const taskQueue = []
// Add tasks to the queue
taskQueue.push('Task 1')
taskQueue.push('Task 2')
taskQueue.push('Task 3')
console.log('Current queue:', taskQueue) // ["Task 1", "Task 2", "Task 3"]
// Process tasks in a FIFO (First In, First Out) order
console.log('Processing tasks:')
while (taskQueue.length > 0) {
const currentTask = taskQueue.shift()
console.log('Processing:', currentTask)
}
console.log('Queue after processing:', taskQueue) // []
// Maintaining a sliding window
console.log('\n--- Sliding Window Example ---')
function slidingWindow(arr, windowSize) {
const result = []
const window = []
for (let i = 0; i < arr.length; i++) {
window.push(arr[i]) // Add new element
// If window is full, process it
if (window.length === windowSize) {
result.push([...window]) // Store current window
window.shift() // Remove oldest element
}
}
return result
}
const data = [1, 2, 3, 4, 5, 6, 7]
console.log('Original data:', data)
console.log('Sliding windows of size 3:', slidingWindow(data, 3))
// Output: [[1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6], [5, 6, 7]]
// Performance comparison between shift and pop
console.log('\n--- Performance Note ---')
console.log('For large arrays, shift() and unshift() are slower than pop() and push()')
console.log('This is because all elements need to be reindexed when adding/removing from the beginning')
console.log('Consider using specialized data structures for frequent operations on large arrays')
================================================
FILE: examples/03-01_op-typeof.mjs
================================================
console.log(typeof 12) // "number"
console.log(typeof 'open source') //"string"
console.log(typeof true) // "boolean"
================================================
FILE: examples/03-02_path-sep.mjs
================================================
const path = require('path')
const folderName = 'documents'
const fileName = 'file.txt'
const filePath = `user${path.sep}${folderName}${path.sep}${fileName}`
console.log(`File Path: ${filePath}`)
//Linux: File Path: user/documents/file.txt
//Windows: File Path: user\documents\file.txt
//Another example of creating filePath using path.sep along with join function
console.log(['user', folderName, fileName].join(path.sep))
================================================
FILE: examples/03-03_os-eol.mjs
================================================
const os = require('os')
const text = 'This is the first line' + os.EOL + 'This is the second line'
console.log(text)
================================================
FILE: examples/03-12_object-groupby.mjs
================================================
// Sample inventory data
const inventory = [
{ name: 'asparagus', type: 'vegetables', quantity: 5 },
{ name: 'bananas', type: 'fruit', quantity: 0 },
{ name: 'goat', type: 'meat', quantity: 23 },
{ name: 'cherries', type: 'fruit', quantity: 5 },
{ name: 'fish', type: 'meat', quantity: 22 },
];
// Example 1: Grouping by item type
const groupedByType = Object.groupBy(inventory, ({ type }) => type);
console.log("Grouped by type:");
console.log(JSON.stringify(groupedByType, null, 2));
/* Expected output:
{
"vegetables": [
{ "name": "asparagus", "type": "vegetables", "quantity": 5 }
],
"fruit": [
{ "name": "bananas", "type": "fruit", "quantity": 0 },
{ "name": "cherries", "type": "fruit", "quantity": 5 }
],
"meat": [
{ "name": "goat", "type": "meat", "quantity": 23 },
{ "name": "fish", "type": "meat", "quantity": 22 }
]
}
*/
// Example 2: Grouping by stock status
const groupedByStock = Object.groupBy(inventory,
({ quantity }) => quantity > 5 ? 'in stock' : 'restock'
);
console.log("\nGrouped by stock status:");
console.log(JSON.stringify(groupedByStock, null, 2));
/* Expected output:
{
"restock": [
{ "name": "asparagus", "type": "vegetables", "quantity": 5 },
{ "name": "bananas", "type": "fruit", "quantity": 0 },
{ "name": "cherries", "type": "fruit", "quantity": 5 }
],
"in stock": [
{ "name": "goat", "type": "meat", "quantity": 23 },
{ "name": "fish", "type": "meat", "quantity": 22 }
]
}
*/
// Demonstration of using the grouped results
console.log("\nItems to restock:");
groupedByStock.restock?.forEach(item =>
console.log(`- ${item.name} (Quantity: ${item.quantity})`)
);
/* Expected output:
Items to restock:
- asparagus (Quantity: 5)
- bananas (Quantity: 0)
- cherries (Quantity: 5)
*/
// Grouping fruits by type
const fruits = [
{ name: 'Apple', type: 'Citrus', quantity: 15 },
{ name: 'Banana', type: 'Tropical', quantity: 10 },
{ name: 'Orange', type: 'Citrus', quantity: 8 },
{ name: 'Mango', type: 'Tropical', quantity: 5 },
{ name: 'Lemon', type: 'Citrus', quantity: 12 }
];
const groupedFruitByType = Object.groupBy(fruits, fruit => fruit.type);
console.log(groupedFruitByType)
/*
{
Citrus: [
{ name: 'Apple', type: 'Citrus', quantity: 15 },
{ name: 'Orange', type: 'Citrus', quantity: 8 },
{ name: 'Lemon', type: 'Citrus', quantity: 12 }
],
Tropical: [
{ name: 'Banana', type: 'Tropical', quantity: 10 },
{ name: 'Mango', type: 'Tropical', quantity: 5 }
]
}
*/
// Group fruits by quantity range
const groupedByQuantityRange = Object.groupBy(fruits, fruit => {
if (fruit.quantity < 10) return 'Low';
if (fruit.quantity < 15) return 'Medium';
return 'High';
});
console.log(groupedByQuantityRange);
/*
{
Low: [
{ name: 'Orange', type: 'Citrus', quantity: 8 },
{ name: 'Mango', type: 'Tropical', quantity: 5 }
],
Medium: [
{ name: 'Banana', type: 'Tropical', quantity: 10 },
{ name: 'Lemon', type: 'Citrus', quantity: 12 }
],
High: [
{ name: 'Apple', type: 'Citrus', quantity: 15 }
]
}
*/
// Grouping fruits by the length of the name
const groupedByNameLength = Object.groupBy(fruits, fruit => fruit.name.length);
console.log(groupedByNameLength);
/*
{
5: [
{ name: 'Apple', type: 'Citrus', quantity: 15 },
{ name: 'Mango', type: 'Tropical', quantity: 5 },
{ name: 'Lemon', type: 'Citrus', quantity: 12 }
],
6: [
{ name: 'Banana', type: 'Tropical', quantity: 10 },
{ name: 'Orange', type: 'Citrus', quantity: 8 }
]
}
*/
================================================
FILE: examples/05-01_str-concat.mjs
================================================
// Examples for String.concat()
// Concatenating two strings
const str1 = 'Hello, '
const str2 = 'world'
const result1 = str1.concat(str2)
console.log(result1) // Output: "Hello, world"
// Concatenating multiple strings
const str3 = 'This'
const str4 = ' is'
const str5 = ' an'
const str6 = ' example.'
const result2 = str3.concat(str4, str5, str6)
console.log(result2) // Output: "This is an example."
// Combining strings with different delimiters
const str7 = 'Concatenate'
const str8 = 'these'
const str9 = 'strings'
const delimiter = ' - '
const result3 = str7.concat(delimiter, str8, delimiter, str9)
console.log(result3) // Output: "Concatenate - these - strings"
================================================
FILE: examples/05-02_str-padding.mjs
================================================
//Examples for padStart()
const text = 'Hello'
const paddedText = text.padStart(10)
console.log(paddedText) // " Hello"
const text1 = 'Worlds'
const paddedText1 = text1.padStart(10, '-*')
console.log(paddedText) // "-*-*Worlds"
const text2 = 'World'
const paddedText2 = text2.padStart(10, '0')
console.log(paddedText) // "00000World"
const text3 = 'JavaScript'
const paddedText3 = text3.padStart(5)
console.log(paddedText) // "JavaScript"
const text4 = 'OpenAI'
const paddedText4 = text4.padStart(10, 'Knowledge ')
console.log(paddedText) // "Knowledge OpenAI"
// Examples for padEnd()
const text5 = 'Hello'
const paddedText5 = text5.padEnd(10)
console.log(paddedText) // "Hello "
const text6 = 'World'
const paddedText6 = text6.padEnd(10, '*')
console.log(paddedText) // "World*****"
const text7 = 'JavaScript'
const paddedText7 = text7.padEnd(5)
console.log(paddedText) // "JavaScript"
const num4 = 42
const paddedNum4 = num4.toString().padEnd(6, '0')
console.log(paddedNum) // "420000"
================================================
FILE: examples/05-03_str-includes.mjs
================================================
const str = 'Hello, world!'
// Examples of includes() with one parameter
const isWorldPresent = str.includes('world')
console.log(isWorldPresent) // Output: true
const isUniversePresent = str.includes('universe')
console.log(isUniversePresent) // Output: false
// Examples of includes() with two parameter
const isWorldPresentFromIndex = str.includes('world', 7)
console.log(isWorldPresentFromIndex) // Output: false
================================================
FILE: examples/05-04_str-slice.mjs
================================================
const str = 'Hello, world!'
// Using only the start parameter
const slicedString1 = str.slice(7)
console.log(slicedString1) // Output: "world!"
// Using both start and end parameters
const slicedString2 = str.slice(1, 4)
console.log(slicedString2) // Output: "ell"
// Using negative indices with only start parameter
const slicedString3 = str.slice(-6)
console.log(slicedString3) // Output: "world!"
// Using negative indices with both start and end parameter
const slicedString4 = str.slice(-6, -3)
console.log(slicedString4) // Output: "wor"
================================================
FILE: examples/05-05_str-indexOf.mjs
================================================
const str = 'Hello, world!'
// Finding the index of a substring
const index1 = str.indexOf('world')
console.log(index1) // Output: 7
// Finding the index of a substring with a specified start index
const index2 = str.indexOf('o', 5)
console.log(index2) // Output: 8
// Finding the index of a substring that is not present
const index3 = str.indexOf('universe')
console.log(index3) // Output: -1
================================================
FILE: examples/05-06_str-repeat.mjs
================================================
const str = 'Hello, '
// Repeating a string multiple times
const repeatedString1 = str.repeat(3)
console.log(repeatedString1)
// Output: "Hello, Hello, Hello, "
// Repeating a string zero times
const repeatedString2 = str.repeat(0)
console.log(repeatedString2)
// Output: ""
// Repeating a string with a non-integer count
const repeatedString = str.repeat(2.5)
console.log(repeatedString)
// Output: "Hello, Hello, "
================================================
FILE: examples/05-07_str-split.mjs
================================================
// Splitting a string based on a space separator
const str1 = 'Hello, world!'
const splitArray1 = str1.split(' ')
console.log(splitArray1)
// Output: ["Hello,", "world!"]
// Splitting a string based on a comma separator with a specified limit
const str2 = 'apple,orange,banana,grape'
const splitArray2 = str2.split(',', 2)
console.log(splitArray2)
// Output: ["apple", "orange"]
// Splitting a string into individual characters
const str3 = 'Hello'
const splitArray3 = str3.split('')
console.log(splitArray3)
// Output: ["H", "e", "l", "l", "o"]
================================================
FILE: examples/05-08_str-toUppercase.mjs
================================================
const str = 'Hello, world!'
// Converting a string to uppercase
const upperCasedString = str.toUpperCase()
console.log(upperCasedString) // Output: "HELLO, WORLD!"
================================================
FILE: examples/05-09_str-toLowercase.mjs
================================================
const str = 'Hello, World!'
// Converting a string to lowercase
const lowercasedString = str.toLowerCase()
console.log(lowercasedString) // Output: "hello, world!"
================================================
FILE: examples/05-10_str-startsWith.mjs
================================================
const str = 'Hello, world!'
// Checking if a string starts with a specific substring
const startsWithHello = str.startsWith('Hello')
console.log(startsWithHello) // Output: true
// Checking if a string starts with a substring at a specific position
const startsWithWorld = str.startsWith('world', 7)
console.log(startsWithWorld) // Output: true
const startsWithHelloWithPosition = str.startsWith('hello', 7)
console.log(startsWithHelloWithPosition) // Output: false
// Checking if a string starts with a substring at a position beyond the string length
const startsWithBeyondLength = str.startsWith('world', 15)
console.log(startsWithBeyondLength) // Output: false
// Checking if a string starts with a substring using a negative position
const startsWithUniverseNegative = str.startsWith('universe', -20)
console.log(startsWithUniverseNegative) // Output: false
const startsWithHelloNegative = str.startsWith('Hello', -20)
console.log(startsWithHelloNegative) // Output: true
================================================
FILE: examples/05-11_str-replaceAll.mjs
================================================
const str = 'Hello, world! Hello again, world!'
// Replacing all occurrences of a substring
const replacedHello = str.replaceAll('Hello', 'Hi')
console.log(replacedHello) // Output: "Hi, world! Hi again, world!"
// Replacing all occurrences of a substring that's not found
const replacedUniverse = str.replaceAll('universe', 'galaxy')
console.log(replacedUniverse) // Output: "Hello, world! Hello again, world!"
// Replacing using a regular expression
const replacedWorldWithRegex = str.replaceAll(/world/g, 'earth')
console.log(replacedWorldWithRegex) // Output: "Hello, earth! Hello again, earth!"
// Replacing case-sensitive strings (no match due to case sensitivity)
const replacedCaseSensitive = str.replaceAll('hello', 'Hi')
console.log(replacedCaseSensitive) // Output: "Hello, world! Hello again, world!"
// Replacing special characters
const strWithSymbols = 'This is a $test$ string with $symbols$'
const replacedSymbols = strWithSymbols.replaceAll('$', '#')
console.log(replacedSymbols) // Output: "This is a #test# string with #symbols#"
// Replacing a string with an empty string (removal)
const removedWorld = str.replaceAll('world', '')
console.log(removedWorld) // Output: "Hello, ! Hello again, !"
// Trying to replace a substring in an empty string
const emptyString = ''
const replacedInEmpty = emptyString.replaceAll('world', 'earth')
console.log(replacedInEmpty) // Output: ""
================================================
FILE: examples/05-12_str-trimstart-trimend.mjs
================================================
// Trimming Whitespace from the Start and End of a String
// Removing Whitespace from the Start: trimStart()
// Example 1: Using trimStart() to remove leading whitespace
const str1 = " Hello, World! ";
let trimmedStr1 = str1.trimStart();
console.log(trimmedStr1);
// Output: "Hello, World! "
// Removing Whitespace from the End: trimEnd()
// Example 1: Using trimEnd() to remove trailing whitespace
const str3 = " Hello, World! ";
let trimmedStr3 = str3.trimEnd();
console.log(trimmedStr3);
// Output: " Hello, World!"
================================================
FILE: examples/05-13_str-trim.mjs
================================================
// Examples for String.trim()
// Basic usage - removing spaces from both ends
const greeting = ' Hello world! '
console.log(`Original: "${greeting}"`)
console.log(`Trimmed: "${greeting.trim()}"`)
// Output: Trimmed: "Hello world!"
// Removing various whitespace characters
const text = '\t\n JavaScript is awesome! \n\r'
console.log(`Original: "${text.replace(/\n/g, '\\n').replace(/\t/g, '\\t').replace(/\r/g, '\\r')}"`)
console.log(`Trimmed: "${text.trim()}"`)
// Output: Trimmed: "JavaScript is awesome!"
// Chaining with other string methods
const userInput = ' heLLo@eXampLe.com '
const normalizedEmail = userInput.trim().toLowerCase()
console.log(`Original: "${userInput}"`)
console.log(`Normalized: "${normalizedEmail}"`)
// Output: Normalized: "hello@example.com"
// Form validation example
function validateUsername(username) {
const trimmedUsername = username.trim()
return trimmedUsername.length >= 3
}
console.log(`Validating ' user ': ${validateUsername(' user ')}`) // true
console.log(`Validating ' ab ': ${validateUsername(' ab ')}`) // false
// Data cleaning example
const csvData = [' name ', ' age ', ' city ']
const cleanData = csvData.map(item => item.trim())
console.log('Original CSV data:', csvData)
console.log('Cleaned data:', cleanData)
// Output: Cleaned data: ["name", "age", "city"]
================================================
FILE: examples/05-14_str-endsWith.mjs
================================================
// Examples for String.endsWith()
// Basic usage
const sentence = 'This is a complete sentence.'
console.log(`"${sentence}" ends with "sentence.": ${sentence.endsWith('sentence.')}`)
// Output: true
console.log(`"${sentence}" ends with "question.": ${sentence.endsWith('question.')}`)
// Output: false
// Using the length parameter
const filename = 'document.pdf'
console.log(`"${filename}" ends with "pdf": ${filename.endsWith('pdf')}`)
// Output: true
// Check if the first 8 characters end with 'doc'
console.log(`First 8 chars of "${filename}" end with "doc": ${filename.endsWith('doc', 8)}`)
// Output: true
// Case sensitivity
const text = 'JavaScript is awesome!'
console.log(`"${text}" ends with "awesome!": ${text.endsWith('awesome!')}`)
// Output: true
console.log(`"${text}" ends with "AWESOME!": ${text.endsWith('AWESOME!')}`)
// Output: false
// File extension validation
function isImageFile(filename) {
const imageExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.webp']
return imageExtensions.some(ext => filename.toLowerCase().endsWith(ext))
}
console.log(`"vacation.jpg" is an image file: ${isImageFile('vacation.jpg')}`)
// Output: true
console.log(`"document.pdf" is an image file: ${isImageFile('document.pdf')}`)
// Output: false
// URL validation
function isSecureGoogleUrl(url) {
return url.toLowerCase().endsWith('.google.com') && url.startsWith('https://')
}
console.log(`"https://www.google.com" is a secure Google URL: ${isSecureGoogleUrl('https://www.google.com')}`)
// Output: true
console.log(`"http://www.google.com" is a secure Google URL: ${isSecureGoogleUrl('http://www.google.com')}`)
// Output: false
// String formatting validation
function endsWithPunctuation(text) {
const punctuation = ['.', '!', '?']
return punctuation.some(p => text.endsWith(p))
}
console.log(`"Hello world!" ends with punctuation: ${endsWithPunctuation('Hello world!')}`)
// Output: true
console.log(`"Hello world" ends with punctuation: ${endsWithPunctuation('Hello world')}`)
// Output: false
================================================
FILE: examples/05-15_str-substring.mjs
================================================
// Examples for String.substring()
// Basic usage
const text = 'JavaScript'
console.log('Original text:', text)
console.log('text.substring(0, 4):', text.substring(0, 4)) // Output: "Java"
console.log('text.substring(4):', text.substring(4)) // Output: "Script"
// Handling out-of-range indices
const shortText = 'Hello'
console.log('\nOriginal text:', shortText)
console.log('shortText.substring(-3, 2):', shortText.substring(-3, 2)) // Output: "He" (negative treated as 0)
console.log('shortText.substring(2, 10):', shortText.substring(2, 10)) // Output: "llo" (out of range)
// Swapping parameters
console.log('\nDemonstrating parameter swapping:')
console.log('text.substring(4, 0):', text.substring(4, 0)) // Output: "Java" (swaps indices)
console.log('text.substring(0, 4):', text.substring(0, 4)) // Output: "Java" (for comparison)
// Comparison with slice()
console.log('\nComparing substring() with slice():')
console.log('text.substring(-3):', text.substring(-3)) // Output: "JavaScript" (treats -3 as 0)
console.log('text.slice(-3):', text.slice(-3)) // Output: "ipt" (counts from the end)
// Extracting a portion of text
function truncateText(text, maxLength) {
if (text.length <= maxLength) {
return text
}
return text.substring(0, maxLength) + '...'
}
const longText = 'This is a very long text that needs to be truncated'
console.log('\nTruncating text:')
console.log('Original:', longText)
console.log('Truncated to 20 chars:', truncateText(longText, 20)) // Output: "This is a very long..."
// Parsing URL components
function getDomainFromUrl(url) {
// Remove protocol
let domain = url
if (url.indexOf('://') > -1) {
domain = url.substring(url.indexOf('://') + 3)
}
// Remove path
if (domain.indexOf('/') > -1) {
domain = domain.substring(0, domain.indexOf('/'))
}
return domain
}
console.log('\nExtracting domain from URL:')
console.log('URL: https://example.com/path')
console.log('Domain:', getDomainFromUrl('https://example.com/path')) // Output: "example.com"
// Removing specific characters
function removeFirstAndLastChar(text) {
return text.substring(1, text.length - 1)
}
console.log('\nRemoving first and last characters:')
console.log('Original: "quoted"')
console.log('Result:', removeFirstAndLastChar('"quoted"')) // Output: "quoted"
================================================
FILE: examples/05-16_str-replace.mjs
================================================
// Examples for String.replace()
// Basic usage with string pattern
const text = 'Hello, world!'
console.log('Original text:', text)
const newText = text.replace('world', 'JavaScript')
console.log('After replace:', newText) // Output: "Hello, JavaScript!"
// Using regular expression
const text2 = 'The quick brown fox jumps over the lazy dog.'
console.log('\nOriginal text:', text2)
const newText2 = text2.replace(/fox|dog/g, 'animal')
console.log('After replace with regex:', newText2)
// Output: "The quick brown animal jumps over the lazy animal."
// Case-insensitive replacement
const text3 = 'JavaScript is awesome. javascript is fun.'
console.log('\nOriginal text:', text3)
const newText3 = text3.replace(/javascript/i, 'TypeScript')
console.log('After case-insensitive replace:', newText3)
// Output: "TypeScript is awesome. javascript is fun."
// Using function as replacement
const text4 = 'apple orange banana'
console.log('\nOriginal text:', text4)
const newText4 = text4.replace(/apple|orange|banana/g, match => match.toUpperCase())
console.log('After replace with function:', newText4)
// Output: "APPLE ORANGE BANANA"
// Text formatting - Phone number
function formatPhoneNumber(phoneNumber) {
// Format: XXX-XXX-XXXX
return phoneNumber.replace(/(\d{3})(\d{3})(\d{4})/, '$1-$2-$3')
}
console.log('\nFormatting phone number:')
console.log('1234567890 ->', formatPhoneNumber('1234567890'))
// Output: "123-456-7890"
// Sanitizing user input
function sanitizeHTML(text) {
const map = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": '''
}
return text.replace(/[&<>"']/g, m => map[m])
}
console.log('\nSanitizing HTML:')
console.log('<script>alert("XSS")</script> ->', sanitizeHTML('<script>alert("XSS")</script>'))
// Output: "<script>alert("XSS")</script>"
// URL slug creation
function createSlug(title) {
return title
.toLowerCase()
.replace(/\s+/g, '-') // Replace spaces with -
.replace(/[^\w-]+/g, '') // Remove all non-word chars
.replace(/--+/g, '-') // Replace multiple - with single -
.replace(/^-+/, '') // Trim - from start of text
.replace(/-+$/, '') // Trim - from end of text
}
console.log('\nCreating URL slug:')
console.log('Hello World! This is a Title ->', createSlug('Hello World! This is a Title'))
// Output: "hello-world-this-is-a-title"
================================================
FILE: examples/05-17_str-lastIndexOf.mjs
================================================
// Examples for String.lastIndexOf()
// Basic usage
const text = 'JavaScript is amazing. JavaScript is fun.'
console.log('Original text:', text)
const lastIndex = text.lastIndexOf('JavaScript')
console.log('Last index of "JavaScript":', lastIndex) // Output: 25
// Using fromIndex parameter
console.log('\nSearching with fromIndex:')
const lastIndex2 = text.lastIndexOf('JavaScript', 20)
console.log('Last index of "JavaScript" before position 20:', lastIndex2) // Output: 0
// Searching for a character
const text2 = 'Hello, world!'
console.log('\nOriginal text:', text2)
const lastIndex3 = text2.lastIndexOf('o')
console.log('Last index of "o":', lastIndex3) // Output: 8
// Not found case
const lastIndex4 = text2.lastIndexOf('z')
console.log('Last index of "z" (not found):', lastIndex4) // Output: -1
// File extension extraction
function getFileExtension(filename) {
const dotIndex = filename.lastIndexOf('.')
return dotIndex === -1 ? '' : filename.substring(dotIndex + 1)
}
console.log('\nExtracting file extensions:')
console.log('document.pdf ->', getFileExtension('document.pdf')) // Output: "pdf"
console.log('image.large.jpg ->', getFileExtension('image.large.jpg')) // Output: "jpg"
console.log('noextension ->', getFileExtension('noextension')) // Output: ""
// Finding the last word in a sentence
function getLastWord(sentence) {
const lastSpaceIndex = sentence.lastIndexOf(' ')
return lastSpaceIndex === -1 ? sentence : sentence.substring(lastSpaceIndex + 1)
}
console.log('\nFinding the last word:')
console.log('Hello, world! ->', getLastWord('Hello, world!')) // Output: "world!"
console.log('JavaScript ->', getLastWord('JavaScript')) // Output: "JavaScript"
// Checking if a string ends with a specific substring
function endsWith(str, suffix) {
const position = str.lastIndexOf(suffix)
return position !== -1 && position === str.length - suffix.length
}
console.log('\nChecking if string ends with substring:')
console.log('Does "Hello, world!" end with "world!"?', endsWith('Hello, world!', 'world!')) // Output: true
console.log('Does "Hello, world!" end with "Hello"?', endsWith('Hello, world!', 'Hello')) // Output: false
// Compare with built-in endsWith method
console.log('\nComparing with built-in endsWith method:')
console.log('Using built-in: "Hello, world!".endsWith("world!") =', 'Hello, world!'.endsWith('world!'))
console.log('Using built-in: "Hello, world!".endsWith("Hello") =', 'Hello, world!'.endsWith('Hello'))
================================================
FILE: examples/05-18_str-match.mjs
================================================
// Examples for String.match()
// Basic usage with global flag
const text = 'The rain in Spain stays mainly in the plain'
console.log('Original text:', text)
const matches = text.match(/ain/g)
console.log('Matches for /ain/g:', matches) // Output: ["ain", "ain", "ain"]
// Without global flag
console.log('\nWithout global flag:')
const match = text.match(/ain/)
console.log('Match for /ain/:', match)
// Output includes the match, index, input string, and groups
// Using capturing groups
const text2 = 'JavaScript was created in 1995'
console.log('\nOriginal text:', text2)
const matchWithGroups = text2.match(/(\w+) was created in (\d+)/)
console.log('Match with capturing groups:')
console.log('Full match:', matchWithGroups[0])
console.log('Group 1 (language):', matchWithGroups[1])
console.log('Group 2 (year):', matchWithGroups[2])
// No match case
const text3 = 'Hello, world!'
console.log('\nOriginal text:', text3)
const noMatch = text3.match(/xyz/)
console.log('Match for /xyz/:', noMatch) // Output: null
// Extracting information from text
function extractEmails(text) {
const emailRegex = /[\w.-]+@[\w.-]+\.\w+/g
return text.match(emailRegex) || []
}
const content = 'Contact us at support@example.com or sales@example.com for assistance.'
console.log('\nExtracting emails:')
console.log('Original text:', content)
console.log('Extracted emails:', extractEmails(content))
// Output: ["support@example.com", "sales@example.com"]
// Parsing data from formatted text
function parseCSVLine(line) {
return line.match(/(".*?"|[^,]+)(?=,|$)/g)
.map(item => item.replace(/^"|"$/g, ''))
}
const csvLine = 'John,"Doe,Jr",42,"New York, NY"'
console.log('\nParsing CSV line:')
console.log('Original CSV:', csvLine)
console.log('Parsed values:', parseCSVLine(csvLine))
// Output: ["John", "Doe,Jr", "42", "New York, NY"]
// Validating input format
function isValidUsername(username) {
// Alphanumeric, 3-16 characters
const match = username.match(/^[a-z0-9]{3,16}$/i)
return match !== null
}
console.log('\nValidating usernames:')
console.log('Is "user123" valid?', isValidUsername('user123')) // Output: true
console.log('Is "us" valid?', isValidUsername('us')) // Output: false (too short)
console.log('Is "user@123" valid?', isValidUsername('user@123')) // Output: false (invalid character)
// Counting words
function countWords(text) {
const words = text.toLowerCase().match(/\b\w+\b/g) || []
return words.length
}
const paragraph = 'The quick brown fox jumps over the lazy dog.'
console.log('\nCounting words:')
console.log('Text:', paragraph)
console.log('Word count:', countWords(paragraph)) // Output: 9
================================================
FILE: examples/06-01_process-cwd.mjs
================================================
// Simple example of using process.cwd()
// 1. Get and display the current working directory
console.log('Current working directory:')
console.log(process.cwd())
// 2. Use process.cwd() to create a file path
const path = require('path')
const filePath = path.join(process.cwd(), 'example.txt')
console.log('\nFile path using current working directory:')
console.log(filePath)
// 3. Display the components of the file path
console.log('\nComponents of the file path:')
console.log('Directory:', path.dirname(filePath))
console.log('File name:', path.basename(filePath))
// Note: This example doesn't create or modify any files
================================================
FILE: list-of-functions.md
================================================
- [x] 01-00 **System**
- [x] 01-01 Info from CPU: `os.cpus()`
- [x] 01-02 Info from Operating System: `os.version()` and `os.platform()`
- [x] 01-03 Info from current user: `os.userInfo()`
- [x] 01-04 Access to environment variables: `process.env`
- [x] 01-05 Get the amount of free memory in bytes (as integer): `os.freemem()`
- [x] 01-06 Get the amount of total memory available in bytes (as integer): `os.totalmem()`
- [x] 01-07 The load average of CPU: `os.loadavg()`
- [x] 01-08 Network interfaces information: `os.networkInterfaces()`
- [x] 01-09 Stop the execution with a proper status code: `process.exit()`
- [x] 01-10 Get temporary directory: `os.tmpdir()`
- [x] 01-11 Get monotonic time: `performance.now()`
- [x] 02-00 **Array**
- [x] 02-01 Create a string from an array: `join()`
- [x] 02-02 Check if the array includes a certain value: `includes()`
- [x] 02-03 Check if a key exists in the array: `in`
- [x] 02-04 Concat arrays: `concat()`
- [x] 02-05 Concat arrays via destructuring
- [x] 02-06 Remove duplicate values in an array via `Set(`)`
- [x] 02-07 Generate and fill a new array `fill()`
- [x] 02-08 Filtering elements: `filter()`
- [x] 02-09 Testing all elements: `every()`
- [x] 02-10 Testing at least one element: `some()`
- [x] 02-11 Mapping new array: `map()`
- [x] 02-12 Reduce array: `reduce()`
- [x] 02-13 Modify array: `splice()`
- [x] 02-14 Extracting elements: `slice()`
- [x] 02-15 Flat nested array: `flat()`
- [x] 02-16 Find the index of an element that matches a condition `findIndex()`
- [x] 02-17 Allows accessing elements using positive or negative indices `at()`
- [x] 02-18 First maps each element using a mapping function, then flattens the result into a new array `flatMap()`
- [x] 02-19 Returns a new Array Iterator object that contains the keys (indices) for each index in the array `keys()`
- [x] 02-20 Returns a new Array Iterator object that contains key/value pairs for each index in the array `entries()`
- [x] 02-21 returns the last index of the element in the array that satisfies the provided testing function `findLastIndex()`
- [x] 02-22 returns the last element in the array that satisfies the provided testing function `findLast()`
- [x] 02-23 Shallow copies part of an array to another location in the same array `copyWithin()`
- [x] 02-25 returns a new Array Iterator object that contains the values for each index in the array `values()`
- [x] 02-26 Sorts the elements of an array in place `sort()`
- [x] 02-27 Reverses the order of elements in an array in place `reverse()`
- [x] 02-28 Adding and removing elements from the end of an array `push()` and `pop()`
- [x] 02-29 Adding and removing elements from the beginning of an array `shift()` and `unshift()`
- [x] 03-00 **Variables, constants, Object**
- [x] 03-01 Get variable type: `typeof`
- [x] 03-02 Portable directory separator: `path.sep`
- [x] 03-03 Portable end of line: `os.EOL`
- [x] 03-04 Gets the properties of the given object: `getOwnPropertyNames()`
- [x] 03-05 Getting all the Object properties/attributes: `keys()`
- [x] 03-06 Object values: `values()`
- [x] 03-07 Object entries: `entries()`
- [x] 03-08 Object freeze: `freeze()`
- [x] 03-09 Object seal: `seal()`
- [x] 03-10 Object is frozen: `isFrozen()`
- [x] 03-11 Object is sealed: `isSealed()`
- [ ] 03-12 Groups elements of an array based on a function, either returning an object `groupBy()` https://github.com/roberto-butti/some-drops-of-javascript/issues/64
- [ ] 03-13 Transforms a list of key-value pairs into an object: `fromEntries()`
- [x] 04-00 **Functions**
- [x] 05-00 **Strings**
- [x] 05-01 Concatenating strings: `concat()`
- [x] 05-02 Padding Strings: `padStart()` `padEnd()`
- [x] 05-03 String includes: `includes()`
- [x] 05-04 Slicing strings: `slice()`
- [x] 05-05 Finding index: `indexOf()`
- [x] 05-06 Repeating a string: `repeat()`
- [x] 05-07 Splitting a String into an Array: `split()`
- [x] 05-08 Upper case: `toUpperCase()`
- [x] 05-09 Lower case: `toLowerCase()`
- [x] 05-10 Start with: `startWith()`
- [ ] 05-11 Replaces all occurrences of a substring in a string: `replaceAll()`
- [ ] 05-12 Removes whitespace from the beginning or end of a String `trimStart()` and `trimEnd()`
- [x] 05-13 Removes whitespace from both ends of a String: `trim()`
- [x] 05-14 Checking if a string ends with a specific substring: `endsWith()`
- [x] 05-15 Extracting parts of a string: `substring()`
- [x] 05-16 Replacing substrings in a string: `replace()`
- [x] 05-17 Finding the last occurrence of a substring: `lastIndexOf()`
- [x] 05-18 Matching strings against regular expressions: `match()`
- [x] 06-00 **Files**
- [ ] 06-01 Current directory: `process.cwd()` https://github.com/roberto-butti/some-drops-of-javascript/issues/53
================================================
FILE: package.json
================================================
{
"name": "some-drops-of-javascript",
"type": "module",
"version": "0.0.1",
"scripts": {
"dev": "astro dev",
"start": "astro dev",
"build": "astro build",
"preview": "astro preview",
"astro": "astro",
"format-examples": "npx prettier ./examples/ --write",
"format-examples-bun": "bunx prettier ./examples/ --write"
},
"dependencies": {
"@astrojs/starlight": "0.31.0",
"@astrojs/starlight-tailwind": "3.0.0",
"@astrojs/tailwind": "^5.1.5",
"astro": "5.1.6",
"sharp": "^0.33.5"
},
"devDependencies": {
"bun-types": "^1.2.16",
"daisyui": "^4.12.24"
},
"trustedDependencies": [
"esbuild",
"sharp"
]
}
================================================
FILE: src/components/about-block.astro
================================================
---
interface Props {
title: string
}
const { title } = Astro.props
---
<article class="sl-flex" aria-labelledby="about-astro-heading">
<small id="about-astro-heading">
{title}
<span class="sr-only">Some Drops of JavaScript</span>
</small>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 630 630">
<rect width="630" height="630" fill="#f7df1e"/>
<path d="m423.2 492.19c12.69 20.72 29.2 35.95 58.4 35.95 24.53 0 40.2-12.26 40.2-29.2 0-20.3-16.1-27.49-43.1-39.3l-14.8-6.35c-42.72-18.2-71.1-41-71.1-89.2 0-44.4 33.83-78.2 86.7-78.2 37.64 0 64.7 13.1 84.2 47.4l-46.1 29.6c-10.15-18.2-21.1-25.37-38.1-25.37-17.34 0-28.33 11-28.33 25.37 0 17.76 11 24.95 36.4 35.95l14.8 6.34c50.3 21.57 78.7 43.56 78.7 93 0 53.3-41.87 82.5-98.1 82.5-54.98 0-90.5-26.2-107.88-60.54zm-209.13 5.13c9.3 16.5 17.76 30.45 38.1 30.45 19.45 0 31.72-7.61 31.72-37.2v-201.3h59.2v202.1c0 61.3-35.94 89.2-88.4 89.2-47.4 0-74.85-24.53-88.81-54.075z"/>
</svg> <slot />
</article>
<style>
article {
max-width: 40rem;
margin-inline: auto;
padding-block: 5rem;
flex-direction: column;
align-items: center;
text-align: center;
gap: 0.5rem;
}
article > :global(*) {
max-width: 50ch;
margin-top: 0 !important;
}
small {
color: var(--sl-color-gray-3);
}
svg {
width: 15rem;
}
</style>
================================================
FILE: src/components/arrow.astro
================================================
<svg
class="w-5 h-5 ml-2 -mr-1"
fill="currentColor"
viewBox="0 0 20 20"
xmlns="http://www.w3.org/2000/svg"
><path
fill-rule="evenodd"
d="M10.293 3.293a1 1 0 011.414 0l6 6a1 1 0 010 1.414l-6 6a1 1 0 01-1.414-1.414L14.586 11H3a1 1 0 110-2h11.586l-4.293-4.293a1 1 0 010-1.414z"
clip-rule="evenodd"></path></svg
>
================================================
FILE: src/components/hero.astro
================================================
---
interface Props {
title: string
}
const { title } = Astro.props
import Arrow from './arrow.astro'
import { Image } from 'astro:assets'
import coverImage from '../assets/some-drops-of-javascript-cover-square.png'
---
<section class="bg-base-100">
<div
class="grid max-w-screen-xl px-4 py-8 mx-auto lg:gap-8 xl:gap-0 lg:py-16 lg:grid-cols-12"
>
<div class="mr-auto place-self-center lg:col-span-7">
<h1
class="base-content max-w-2xl mb-4 text-4xl font-extrabold tracking-tight leading-none md:text-5xl xl:text-6xl"
>
Some drops of JavaScript is an open source e-book.
</h1>
<p
class="max-w-2xl mb-6 font-light base-content lg:mb-8 md:text-lg lg:text-xl"
>
This book compiles a collection of useful, lesser-known, and underrated
JavaScript functions and techniques. These discoveries have been made,
utilized, and refined through daily JavaScript programming practice.
</p>
<a
href="/00-intro/01_contributing/"
class="inline-flex items-center justify-center px-5 py-3 mr-3 text-base font-medium text-center text-white rounded-lg bg-primary-700 hover:base-300 focus:ring-4 focus:ring-primary-300 dark:focus:ring-primary-900"
>
Contribute
<Arrow />
</a>
<a
href="/00-intro/00_intro"
class="inline-flex items-center justify-center px-5 py-3 text-base font-medium text-center text-gray-900 border border-gray-300 rounded-lg hover:base-300 focus:ring-4 focus:ring-gray-100 dark:focus:ring-gray-800"
>
Read the Book
<Arrow />
</a>
</div>
<div class="hidden lg:mt-0 lg:col-span-5 lg:flex">
<Image
src={coverImage}
alt="Some Drops of JavaScript is an open source e-book."
/>
</div>
</div>
</section>
================================================
FILE: src/content/docs/00-intro/00_intro.md
================================================
---
title: Some drops of JavaScript
description: This HTML eBook collects some useful, unknown, underrated JavaScript functions or stuff discovered, used, and learned during JavaScript daily use.
sidebar:
label: About the eBook
---
## The reason why
This book collects practical, unknown, or underrated JavaScript functions or things discovered, used, and learned during daily JavaScript use.
When using JavaScript frameworks/libraries daily (like React, Vue, Angular, and Svelte), sometimes one needs to catch up on the language's power and the basic functionalities the JavaScript core provides.
I notice that I usually look at the framework documentation or find a package in NPM for the system, array, and string functions instead of using the core functionalities provided by the language.
While I wrote this HTML book, I also wrote some scripts to better understand the functions' behavior. You can find these examples in the examples directory at https://github.com/roberto-butti/some-drops-of-javascript.
### Requirements
The code used in this book is tested with **Bun (latest)** and **Node.js (LTS)**.
**Bun** is a JavaScript runtime, package manager, bundler, and test runner built from scratch using the Zig programming language. Jarred Sumner designed it as a drop-in replacement for Node.js. Bun uses JavaScriptCore as the JavaScript engine, unlike Node.js and Deno, which both use V8. The official website is: https://bun.sh/ .
**Node.js** is an open-source, cross-platform JavaScript runtime environment. You can obtain it on the official https://nodejs.org/ website.
### Continuous release
I was thinking of printing this book, but I think it is not eco-friendly, and a book about development could be improved daily regarding spellchecking, content, and examples. I expect to adopt the same approach in the software with the CI/CD, with a continuous release of the book.
Releases:
- **W.I.P.** the 1.0.0 version has not yet been released: writing... ;
> The book is a Work in Progress, and the list of currently covered functions is in the [list-of-functions.md](list-of-functions.md) file
So, if you have any feedback or you want to suggest some corrections, feel free to open an issue here: https://github.com/roberto-butti/some-drops-of-javascript/issues
### Where to find this book
This book is available for download for free here: https://github.com/roberto-butti/some-drops-of-javascript/
### Thanks to...
Thanks to all the Open Source community.
### License
"Some drops of JavaScript" (c) by Roberto Butti.
"Some drops of JavaScript" is licensed under a
Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.
You should have received a copy of the license along with this
work. If not, see <http://creativecommons.org/licenses/by-nc-sa/4.0/>.
================================================
FILE: src/content/docs/00-intro/01_contributing.md
================================================
---
title: The Open Source eBook
description: We are excited to invite you to join our repository and contribute to the open-source book project. We welcome contributors with various skills and interests, so whether you're a JavaScript expert, a grammar enthusiast, a design aficionado, or just someone with a passion for learning and sharing knowledge, there's a place for you in our open-source book project.
sidebar:
label: How to contribute
badge:
text: New
variant: tip
banner:
content: |
The open-source eBook,
<a href="https://github.com/roberto-butti/some-drops-of-javascript">feel free to contribute adding or reviewing content</a>
---
Hello, amazing contributors! 👋
We are excited to invite you to join our [repository](https://github.com/roberto-butti/some-drops-of-javascript) and contribute to the open-source book project. We welcome contributors with various skills and interests, so whether you're a JavaScript expert, a grammar enthusiast, a design aficionado, or just someone with a passion for learning and sharing knowledge, there's a place for you in our open-source book project.
## Ways to Contribute
Here are some of the ways you can get involved:
- **JavaScript Wizards**: Write pages for JavaScript functions, share your expertise, and help fellow developers understand some nice JavaScript functions.
- **Reviewers and Editors**: Help ensure the quality and accuracy of the content by reviewing and editing pages.
- **Grammar Enthusiasts**: Review and improve our documentation's English grammar and readability.
- **Idea Contributors**: Suggest JavaScript functions that should be covered in the documentation. Your insights are valuable!
- **Design Gurus**: Propose design changes that can enhance the overall user experience of our book.
## How to Get Started
1. Fork the repository to your GitHub account.
2. Create a new branch for your contributions.
3. Make your changes and commit them.
4. Open a pull request to merge your changes back into the main repository.
For more detailed instructions, please check our [Contribution Guidelines](https://github.com/roberto-butti/some-drops-of-javascript/blob/main/CONTRIBUTING.md).
## Join the Conversation
Have questions or want to discuss your contributions? Join us in the [repository](https://github.com/roberto-butti/some-drops-of-javascript/issues) issue section](https://github.com/roberto-butti/some-drops-of-javascript/issues), where you can create issues but also create suggestions, and feature requests.
## Thank You!
We deeply appreciate your willingness to contribute to the open-source book "Some Drops of JavaScript". Your efforts significantly impact the JavaScript community, and we're grateful for your support.
:::tip[Thank you to all the contributors]
I want to say a special thank you to all the [contributors](https://github.com/roberto-butti/some-drops-of-javascript/graphs/contributors).
:::
Thank you! 🚀
================================================
FILE: src/content/docs/00-intro/01_hacktoberfest-2024.md
================================================
---
title: Hacktoberfest and "Some drops of JavaScript"
description: How to contribute for Hacktoberfest.
sidebar:
label: Hacktoberfest 2024
badge:
text: Contribute
variant: tip
banner:
content: |
The open-source eBook,
<a href="https://github.com/roberto-butti/some-drops-of-javascript">feel free to contribute adding or reviewing content for Hacktoberfest</a>
draft: true
---

Hello amazing contributors! 👋
We are excited to invite you to join our Hacktoberfest celebration by contributing to our open-source book project. We welcome contributors with various skills and interests, so whether you're a JavaScript expert, a grammar enthusiast, a design aficionado, or just someone with a passion for learning and sharing knowledge, there's a place for you in our community.
## Ways to Contribute
Here are some of the ways you can get involved:
- **JavaScript Wizards**: Write pages for JavaScript functions, share your expertise, and help fellow developers understand some nice JavaScript functions.
- **Reviewers and Editors**: Help ensure the quality and accuracy of the content by reviewing and editing pages.
- **Grammar Enthusiasts**: Review and improve our documentation's English grammar and readability.
- **Idea Contributors**: Suggest JavaScript functions that should be covered in the documentation. Your insights are valuable!
- **Design Gurus**: Propose design changes that can enhance the overall user experience of our book.
## How to Get Started
1. Fork the repository to your GitHub account.
2. Create a new branch for your contributions.
3. Make your changes and commit them.
4. Open a pull request to merge your changes back into the main repository.
For more detailed instructions, please check our [Contribution Guidelines](https://github.com/roberto-butti/some-drops-of-javascript/blob/main/CONTRIBUTING.md).
## Join the Conversation
Have questions or want to discuss your contributions? Join us in the repository issue section, where you can create issues, suggestions, and feature requests.
## Say Thank You!
We deeply appreciate your willingness to contribute to the open-source book "Some Drops of JavaScript". Your efforts significantly impact the JavaScript community, and we're grateful for your support.
Happy Hacking! 🚀
================================================
FILE: src/content/docs/00-intro/02_runtime.md
================================================
---
title: What is JavaScript?
description: JavaScript, the language, the engine, and the runtime.
sidebar:
label: What is JavaScript?
---
## Javascript Langauge
JavaScript is a high-level, versatile, and widely used programming language. Originally created for web development to make web pages interactive, JavaScript has since expanded its scope and can now be used in various environments, including server-side development, mobile app development, and even desktop application building.
JavaScript is a dynamically typed language, meaning that variable types are determined at runtime.
JavaScript is an interpreted language that allows developers to execute code without requiring a compilation step.
JavaScript relies on the ECMAScript standard as its foundation, ensuring a standardized set of rules and features that promote consistency and compatibility across various JavaScript implementations.
## JavaScript Engine
A JavaScript engine interprets and executes the code.
JavaScript engines play a crucial role by converting JavaScript code into machine code, facilitating efficient execution and performance optimization.
JavaScript engines use Just-In-Time (JIT) compilation to execute the code.
Just-In-Time (JIT) compilation is a key technique employed by JavaScript engines to boost performance. Instead of interpreting the entire JavaScript code at once, JIT compilation dynamically translates specific portions of the code into machine code during runtime. This on-the-fly translation allows the engine to optimize the execution of frequently used code, resulting in faster and more efficient JavaScript programs.
There is more than one engine; the most common are:
- **V8** is an open-source JavaScript and WebAssembly engine developed by Google. It is written in C++ and used in the Google Chrome web browser and the Node.js runtime. V8 is designed to execute JavaScript code at high speeds and has become a crucial component for improving the performance of web applications.
- **SpiderMonkey** is the JavaScript engine developed by Mozilla, the organization behind the Firefox web browser. It is an open-source engine written in C++ that interprets and executes JavaScript code within the Firefox browser.
- **JavaScriptCore** is the open-source JavaScript engine part of the WebKit project. WebKit is a browser engine primarily developed by Apple and used in Safari and other browsers on Apple platforms. JavaScriptCore, known as Nitro, is responsible for interpreting and executing JavaScript code within the WebKit browser engine. JavaScriptCore is used also by the Bun runtime.
## JavaScript Runtime
A JavaScript runtime uses the JavaScript engine to execute the JavaScript code. Additionally, a JavaScript runtime provides some APIs or functionalities to interact with the hosting environment. For example, a JavaScript runtime can provide API for interaction with the Browser (for the Brower Javascript runtimes) or can provide API for interacting with the filesystem (for non-browser JavaSCript runtimes like Node.js and Bun.js).
For example, the most common JavaScript runtimes are:
- **Bun** runtime is a fast JavaScript runtime is designed as a drop-in replacement for Node.js. It's written in Zig and powered by JavaScriptCore under the hood, dramatically reducing startup times and memory usage.
- **Node.js** is an open-source, cross-platform JavaScript runtime built on the V8 JavaScript engine. It allows developers to run JavaScript code on the server side, enabling the development of server-side and network applications. Node.js is event-driven and non-blocking, efficiently handling many concurrent connections.
- **Browser** is a runtime environment within a web browser where JavaScript client-side code is executed. It provides APIs for interacting with the browser the Fetch API for making network requests, the Web Storage API for local data storage, and the Geolocation API for location-based services.
================================================
FILE: src/content/docs/01-system/00_system_intro.md
================================================
---
title: System functions
description: The chapter covers functions about "system" functionalities (for example how to retrieve the operating system version, environment variables, memory usage, CPU usage, user information etc.).
sidebar:
label: System functions
---
# System
In this chapter, we will explore how to interact with system-level functionalities using JavaScript. While JavaScript is often associated with front-end development, it can also be a powerful tool for retrieving and managing system information, especially in server-side environments. JavaScript provides several built-in modules that allow us to access vital details about the underlying system, offering a deeper understanding of the environment where the code is running.
This chapter will introduce key functions and techniques to help you access critical system information, such as:
- **Operating System Information:** Learn how to retrieve details like the operating system version, platform type, architecture, and uptime. This is useful for cross-platform applications where behavior may vary depending on the environment.
- **Environment Variables:** Discover how to access and manipulate environment variables, which are often used for configuration purposes in development, staging, and production environments.
- **Memory and CPU Usage:** We'll look into monitoring system resource consumption, including memory and CPU usage, to help optimize performance and detect potential bottlenecks or issues.
- **User and Process Information:** Find out how to gather data about the current user, home directory, system processes, and more. This is particularly valuable in user-centric or process-driven applications.
By the end of this chapter, you'll have the tools to write JavaScript code that effectively interacts with the system, enhancing your ability to monitor, debug, and optimize your applications. Whether you are building a desktop tool, a server-side script, or need to gain insights into your deployment environment, this chapter will give you a solid foundation for handling system-related tasks using JavaScript.
================================================
FILE: src/content/docs/01-system/01_os-cpus.md
================================================
---
title: "CPUs information"
description: "Retrieving the list of the available CPUs"
sidebar:
label: CPUs information
---
## Info from CPU: `os.cpus()`
The `os` module allows you to retrieve relevant information about the environment used for running your _Node.js_ script or application.
```javascript
import { cpus } from 'os'
const c = cpus()
```
The `os` module provides you with some methods. One is the `cpus()` that returns the list of CPUs available in your environment. For each element of the list (each element is one CPU), you have the `model` attribute that has the CPU model name (for example, "Apple M1 Pro") and the `speed` attribute, an integer for showing the speed of the CPU.
Then you have also `times` attribute for the times (in milliseconds) that the CPU has spent in these modes: `user`, `nice` (valid only for Posix systems, in Windows this value is always 0), `sys`, `idle`, `irq`.
It returns:
An array of objects, where each object represents a **logical** CPU core and contains the following properties:
- `model` (string): The model of the CPU.
- `speed` (number): The speed of the CPU in MHz.
- `times` (object): An object containing the number of milliseconds the CPU has spent in different modes:
- `user` (number): Time spent in user mode.
- `nice` (number): Time spent in nice mode.
- `sys` (number): Time spent in system mode.
- `idle` (number): Time spent in idle mode.
- `irq` (number): Time spent servicing interrupts.
So, you can walk through the list of CPUs:
```js
import { cpus } from 'os'
cpus().forEach(cpu => {
console.info(cpu.model + ' speed: ' + cpu.speed)
console.table(cpu.times)
})
```
### Calculating the CPU utilization
You can use the `os.cpus()` function to calculate the utilization of each CPU core, which is helpful for performance monitoring and workload analysis.
```javascript
import { cpus } from 'os'
console.log("*** Calculating the CPU utilization ***")
cpus().forEach((cpu, index) => {
const { user, nice, sys, idle, irq } = cpu.times;
const total = user + nice + sys + idle + irq;
const usage = ((total - idle) / total) * 100;
console.log(`CPU ${index + 1} Usage: ${usage.toFixed(2)}%`);
});
```
### Identifying the Number of Logical CPU Cores
In scenarios where you need to determine the number of **logical CPU cores** available for parallel processing, you can use `os.cpus()` as follows:
```javascript
import { cpus } from 'os'
const numCpus = cpus().length;
console.log(`Number of logical CPU cores: ${numCpus}`);
```
The `os.cpus()` function returns an array where each element represents a logical CPU core. The length of this array gives the number of logical CPU cores available.
This is particularly useful when creating worker threads or child processes to maximize CPU utilization.
### Common Pitfalls
- Misunderstanding Logical vs. Physical Cores: The `os.cpus()` function returns the number of logical cores, not physical cores. In systems with hyper-threading, the number of logical cores will be higher than that of physical cores.
- Platform-Specific Behavior: The data returned by `os.cpus()` may vary slightly depending on the operating system. If your application needs to run on multiple OS types, ensure compatibility and testing across different platforms.
### Resources
- Node.js Documentation: [os.cpus](https://nodejs.org/api/os.html#oscpus)
- Chapter: Get the amount of total memory available in bytes [os.totalmem()](/01-system/06_os-totalmem/)
- Chapter: Get the amount of free memory in bytes [os.freemem()](/01-system/05_os-freemem/)
================================================
FILE: src/content/docs/01-system/02_os-version.md
================================================
---
title: "OS information"
sidebar:
label: OS information
---
If you need to retrieve information about the Operating System, like the version, the release, the platform, the release, you can use some functions implemented by the `os` module.
## The Operating System version: `os.version()`
The `os` module has the `version()` method to return the version of the Operating System in use.
~~~javascript
import { version } from 'os'
const version = version()
console.log(v)
~~~
The `version()` method returns a string with the full name of the Operating System version, like this:
~~~
Darwin Kernel Version 21.6.0: Wed Aug 10 14:28:23 PDT 2022; root:xnu-8020.141.5~2/RELEASE_ARM64_T6000
~~~
## The Operating System platform: `os.platform()`
The `os` module has the `platform()` function to return the name of the platform of the Operating System in use.
~~~javascript
import { platform } from 'os'
const platform = platform()
console.log(platform)
~~~
The `platform()` method returns a string with the name of the platform Operating System version, like for example: `aix`, `android`, `darwin`, `freebsd`,`linux`, `openbsd`, `sunos`, or `win32`.
If you are running Node on a Mac OS machine, you will obtain `darwin`.
================================================
FILE: src/content/docs/01-system/03_os-userinfo.md
================================================
---
title: "Getting user information"
sidebar:
label: User information
---
When you launch a Node script, you will launch it with a specific operating system user. The user used for launcing the script determines the permission of the script.
If you need to retrieve the information related to the current user you can use `userInfo()` function.
## Info for the current user: `os.userInfo()`
The `os` module has the `userInfo`()` method to return information on the current system user.
```javascript
import { userInfo } from 'os'
const u = userInfo()
```
The `userInfo()` method returns an object with attributes:
- `uid`: the user identifier (integer)
- `gid`: the group identifier (integer)
- `username`: the username (string)
- `homedir`: the user's home directory (string)
- `shell`: the user's shell (string)
================================================
FILE: src/content/docs/01-system/04_process-env.md
================================================
---
title: "Access to environment variables: process.env"
sidebar:
label: Environment Vars
---
## Access to environment variables: process.env
The `process` global module has the `env` attribute to return information on the environment variable.
The `process.env` attribute contains an object and it represents the list of environment variables. Each attribute is an environment variable.
The `process` module is a global module, which means that you don't have to import the process module manually, but it is automatically available in your code.
For retrieving the environment variables object:
```javascript
console.log(process.env)
```
If you want to access a specific environment variable via the name (for example to the `PATH` environment variable):
```javascript
console.log(process.env.PATH)
```
If you have to access dynamically to an environment variable, you can use the square brackets:
```javascript
const envVarName = 'PATH'
if (envVarName in process.env) {
console.log(process.env[envVarName])
} else {
console.log('no %s defined', envVarName)
}
```
If you want to walk through all the environment variables you can iterate on the object attributes via `Object.keys()` method:
```javascript
Object.keys(process.env).forEach(function (key, index) {
console.log(key, index, process.env[key])
})
```
================================================
FILE: src/content/docs/01-system/05_os-freemem.md
================================================
---
title: "Get the amount of free memory in bytes (as integer): `os.freemem()`"
sidebar:
label: Free memory
---
## Get the amount of free memory in bytes (as integer): `os.freemem()`
The `os` module has the `freemem()` method to return information on the free memory available in the system.
The `freemem()` function returns an integer and it represents the bytes. If you need megabytes or kilobytes you have to convert it.
```javascript
import { freemem } from 'os'
const mem = freemem()
console.log('The amount of free memory is %d bytes', mem)
```
================================================
FILE: src/content/docs/01-system/06_os-totalmem.md
================================================
---
title: "Get the amount of total memory available in bytes"
sidebar:
label: Available memory
---
## Get the amount of total memory available in bytes (as integer): `os.totalmem()`
The `os` module has the `totalmem()` method to return information on the total memory available in the system.
The `totalmem()` function returns an integer and it represents the bytes. If you need megabytes or kilobytes you have to convert it.
```javascript
import { totalmem } from 'os'
const mem = totalmem()
console.log(
'Hi, the total memory is %d gigabytes',
mem / 1024 / 1024 / 1024
)
```
================================================
FILE: src/content/docs/01-system/07_os-loadavg.md
================================================
---
title: "Getting the load average of CPU"
sidebar:
label: CPU load
---
## The load average of CPU: `os.loadavg()`
The `os` module has the `loadavg()` method to return the "load" measurement information about the CPU usage of the system.
The "load" measurement is calculated by the number of processes that are being executed by the CPU or in a 'waiting' state.
The `loadavg()` function returns an array with 3 float numbers. These three numbers represents the average system load calculated over a given period of 1, 5 and 15 minutes
```javascript
import { loadavg } from 'os'
const la = loadavg()
console.log(
la[0], // last minute
la[1], // last 5 minutes
la[2] // last 15 minutes
)
// it returns: 1.59619140625 2.42822265625 2.60400390625
```
>{quote} On Windows machine this functionality is not available, the method returns an array with 0 values, like `[0, 0, 0]`
================================================
FILE: src/content/docs/01-system/08_os-networkinterfaces.md
================================================
---
title: "Getting the network interfaces information"
sidebar:
label: Network interfaces
---
## Network interfaces information: `os.networkInterfaces()`
The `os` module has the `networkInterfaces()` method to return the object that shows the information about the network interfaces available on the system.
The object has multiple interfaces.
Each interface has an identifier used as an object key attribute like `lo0`, `en0`, `utun0`, `utun1` ... etc.
Each interface has an array of addresses.
Each address is an object like this one:
```json
{
address: '127.0.0.1',
netmask: '255.0.0.0',
family: 4,
mac: '00:00:00:00:00:00',
internal: true,
cidr: '127.0.0.1/8'
}
```
Where `address`, `netmask`, `mac`, `cidr` are the address (ip address, mac addres) and netmask.
The `family` attribute identifies the type of the ip protocol.
The `internal` attribute is a boolean value, `true` if the address is remotely accessible.
```javascript
import { networkInterfaces } from 'os'
const ni = networkInterfaces()
Object.keys(ni).forEach(function (key, index) {
// each interfaces has an array
ni[key].forEach(function (element, index) {
// selecting only family === 4 (ipv4 interfaces)
if (element.family === 4) {
console.log('IP ADDRESS: ' + element.address) // IPv4 address
}
})
})
```
================================================
FILE: src/content/docs/01-system/09_process-exit.md
================================================
---
title: "Stopping the script execution"
sidebar:
label: Stop execution
---
## Stop the script execution: `process.exit()`
The `process` global module has the `exit()` method to stop the current execution and return to the shell, or in general to the environment where the script was launched.
All the processes can return a status code to the shell. By convention, if the execution ends correctly a status code value equal to 0 is returned. In case of an error, the process can return a not 0 status code value.
So if you want to stop the execution of the script and return a status code equal to 99 you can use `process.exit(99)` like the example:
```javascript
console.log('Executing ...')
process.exit(99)
console.log('Never executed')
```
Executing this snippet, a `99` status code error will be returned to the shell.
For example, once the script execution is terminated, you can test the shell environment variable `$?` that contains the status code of the last process executed. If you execute in a shell (`bash` or `zsh` or some other shell) the node script and then try to show the last status code via `echo $?`:
```bash
node examples/01-09_process-exit.mjs
echo $?
```
You will see the `99` value will be shown in the terminal (because the JS script returns with `process.exit(99)`).
================================================
FILE: src/content/docs/01-system/10_os-tmpdir.md
================================================
---
title: "Getting the temporary directory absolute path"
sidebar:
label: Temp directory
---
## Getting the temporary directory: `os.tmpdir()`
If you need to store temporary a file in your script, you can save the temporary file in the default operating system temporary directory.
You can retrieve the current operating system temporary directory via `tmpdir()` function:
```javascript
import { tmpdir } from 'os'
console.log('Temporary directory: %s', tmpdir())
```
================================================
FILE: src/content/docs/01-system/11_performance-now.md
================================================
---
title: "Tracking the execution time getting the monotonic time"
sidebar:
label: Tracking time
---
## Getting monotonic time: `performance.now()`
If you have to track execution time or the time spent in a script or a long-running application, you have to keep in mind that while you are executing your script and your logic the date time of the operating system could change because the user adjusts the hour, or the date time is adjusted automatically by the NTP system.
So if you want to track the millisecond spent executing a logic you need a monotonic time.
In JavaScript (Node.js) you have a kind of stopwatch that is started at the beginning of the execution of the script.
This timer is used for measuring performance because is a relative metric and it isn't affected by system clock changes.
```javascript
// saving the timer in startTime
let startTime = performance.now()
console.log('Starting')
// calculating the time by difference performance.now() - startTime
console.log(performance.now() - startTime, startTime)
```
================================================
FILE: src/content/docs/02-array/00_array.md
================================================
---
title: "Array"
description: The chapter will cover functions about "array" functionalities
sidebar:
label: Introduction
---
# Handling the Array data structures
This chapter will explore one of JavaScript's most fundamental and versatile data structures: **arrays**.
Arrays are essential in any JavaScript developer’s toolkit, enabling efficient data storage and manipulation. Understanding how to work with arrays is key to writing clean, performant, and maintainable code.
This chapter will guide you through a wide range of **array manipulation techniques** and functions, helping you to harness the full power of arrays in your projects. You will learn how to perform operations such as:
- **Filtering Arrays:** We'll explore how to extract subsets of data from arrays using the `filter()` method. This method allows you to remove unwanted or irrelevant elements based on specific criteria, which is useful for tasks like filtering search results or handling large datasets.
- **Mapping Arrays:** The `map()` method transforms arrays by applying a function to each element and returning a new array with the modified values. You’ll see how this can format data, calculate new values, or manipulate objects within arrays.
- **Reducing Arrays:** Learn how to condense an entire array into a single value using the powerful `reduce()` method. Whether you need to sum a list of numbers, accumulate object properties, or process data streams, `reduce()` provides a flexible way to handle complex transformations.
- **Sorting and Reversing Arrays:** We'll cover how to sort arrays alphabetically, numerically, or based on custom logic, and how to reverse their order when needed. Sorting data efficiently is crucial for many real-world applications, such as organizing user lists, rankings, or search results.
- **Finding and Checking Values:** You'll learn to search for specific elements in an array using methods like `find()`, `findIndex()`, `includes()`, and `some()`, which enable you to locate data points or verify if certain conditions are met within your array.
- **Merging, Splitting, and Slicing Arrays:** You’ll understand how to combine arrays, extract portions of arrays, and break them into smaller parts using methods like `concat()`, `slice()`, and `splice()`. This is helpful when working with large datasets or implementing features like pagination.
Through real-world examples and use cases, this chapter will demonstrate how these array methods can be applied to solve common programming challenges, such as data manipulation, search optimization, and efficient iteration. By the end of the chapter, you’ll not only master array manipulation techniques but also understand how to use them to write more concise, expressive, and scalable JavaScript code.
================================================
FILE: src/content/docs/02-array/01_array-join.md
================================================
---
title: "Create a string from an array: `join()`"
sidebar:
label: From array to string
---
## Create a string from an array: `join()`
If you want to generate a string, joining all the array elements, you can use the `join()` method. By default, the character is used as separator. If you want to use a specific separator you can call the join('-') method with the separator needed as the first argument.
```javascript
const elements = ['kiwi', 'strawberry', 'lemon']
console.log(elements.join())
// expected output: "kiwi,strawberry,lemon"
console.log(elements.join('-'))
// expected output: "kiwi-strawberry-lemon"
```
================================================
FILE: src/content/docs/02-array/02_array-includes.md
================================================
---
title: "Check if the array includes a certain value: `includes()`"
sidebar:
label: Checking an item
---
## Check if the array includes a certain value: `includes()`
If you want to check if the array includes a specific value, you can use `includes()` method. The first mandatory input argument of `includes()` method is the value of the element you want to check.
```javascript
const elements = ['kiwi', 'strawberry', 'lemon']
console.log(elements.includes('strawberry'))
// Does the array include the 'strawberry'?
// expected output: true
```
If you want to check if the value is included starting from a specific index you can use the second input parameter for setting the index (remember to start from 0 for counting the position).
```javascript
const elements = ['kiwi', 'strawberry', 'lemon']
console.log(elements.includes('strawberry', 2))
// Does the array starting from index 2, include the 'strawberry'?
// expected output: false
```
================================================
FILE: src/content/docs/02-array/03_array-in.md
================================================
---
title: "Check if a property exists in the object or array: `in`"
sidebar:
label: Checking a property
---
## Check if a property exists in the object or array: `in`
If you have an object and you want to check if a property is present you can use the `in` operator.
```javascript
const fruits = {
strawberry: 'Strawberry',
kiwi: 'Kiwi',
lemon: 'Lemon'
}
// for checking the presence of an property you can use in operator
if ('kiwi' in fruits) {
console.log('Kiwi is present')
}
// you can use in the short form
console.log('kiwi' in fruits ? 'Yes! Kiwi' : 'ther is no kiwi here')
```
I think the `in` operator is one of the best ways to check the presence of a property because, for example, if you want to check if the value is `undefined`, you can't distinguish the cases if the property doesn't exist or the property exists and has an undefined value:
```javascript
const fruits = {
strawberry: 'Strawberry',
kiwi: 'Kiwi',
lemon: 'Lemon'
}
fruits.something = undefined
if (fruits.somethingelse === undefined) {
console.log('Somethingelse property does not exist')
}
if (fruits.something === undefined) {
console.log('Something property exists but the value is undefined')
}
```
The `in` operator works also with the arrays. With the arrays, you can check the presence of the numeric index:
```javascript
const fruitsArray = []
fruitsArray.push('Strawberry')
fruitsArray.push('Kiwi')
fruitsArray.push('Lemon')
console.dir(fruitsArray)
console.log(2 in fruitsArray) // true
console.log(3 in fruitsArray) // false
```
================================================
FILE: src/content/docs/02-array/04_array-concat.md
================================================
---
title: "Concatenate two (or more) arrays: `concat()`"
sidebar:
label: Concatenating arrays
---
## Concatenate two (or more) arrays: `concat()`
You can concatenate (append) two or more arrays with the `concat()` method.
```javascript
const array1 = ['a', 'b', 'c']
const array2 = ['d', 'e', 'f']
console.dir(array1.concat(array2)) // ['a', 'b', 'c', 'd', 'e', 'f']
```
you can concatenate more arrays:
```javascript
const array1 = ['a', 'b', 'c']
const array2 = ['d', 'e', 'f']
const array3 = ['g', 'h']
console.dir(array1.concat(array2, array3))
console.dir([].concat(array1, array2, array3))
```
================================================
FILE: src/content/docs/02-array/05_array-merge_destructuring.md
================================================
---
title: "Concat arrays via destructuring"
sidebar:
label: Concatenating arrays via destructuring
---
## Concat arrays via destructuring
For concatenating or merging two or more arrays, you can use the destructuring technique.
With this technique essentially you are going to unpack the arrays into a list of distinct variables, and use this list to recreate a new array with square brackets.
```js
const array1 = ['a', 'b', 'c']
const array2 = ['d', 'e', 'f']
console.dir([...array1, ...array2])
// [ 'a', 'b', 'c', 'd', 'e', 'f' ]
```
You can use this technique with more than 2 arrays:
```js
const array1 = ['a', 'b', 'c']
const array2 = ['d', 'e', 'f']
const array3 = ['g', 'h']
console.dir([...array1, ...array2, ...array3])
// [ 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h' ]
```
The order you are using the `[...array1, ...array2, ...array3]` is important because determines the order of the items for the new array
```js
const array1 = ['a', 'b', 'c']
const array2 = ['d', 'e', 'f']
const array3 = ['g', 'h']
console.dir([...array3, ...array2, ...array1])
// [ 'g', 'h', 'd', 'e', 'f', 'a', 'b', 'c' ]
```
================================================
FILE: src/content/docs/02-array/06_array-set.md
================================================
---
title: "Remove duplicate values in an array via `Set()`"
sidebar:
label: Removing duplicates
---
## Remove duplicate values in an array via `Set()`
If you want to remove duplicates from an array there is no specific array method for removing duplicate elements but you can achieve this using destructuring, the `Set()` function and recreating the array.
It means that the original array will not change.
```js
const array = ['a', 'b', 'c', 'b', 'd', 'e', 'a']
const unique = [...new Set(array)]
// [ 'a', 'b', 'c', 'd', 'e' ]
```
================================================
FILE: src/content/docs/02-array/07_array-fill.md
================================================
---
title: "Generate and fill a new array `fill()`"
sidebar:
label: Filling an array
---
## Generate and fill a new array `fill()`
The `fill()` method sets a specific value to the elements of the array.
If you have an array with some values:
```js
const array = ['a', 'b', 'c', 'b', 'd', 'e', 'a']
```
and you want to replace/fill the elements with the value `0`, you can call `fill()` method on the array, using `0` as a parameter:
```js
array.fill(0)
// [ 0, 0, 0, 0, 0, 0, 0 ]
```
As you can see the `fill()` method changes the content of the original array. The size of the array will be the same as the original one.
The `fill()` method has two more optional parameters about the starting index to apply the changes and the ending index.
For example, if you want to replace values starting with the second element (remember 0 index array):
```js
const array2 = ['a', 'b', 'c', 'b', 'd', 'e', 'a']
array2.fill(
0, // the value to fill
1 // the index where to start
)
console.dir(array2)
// [ 'a', 0, 0, 0, 0, 0, 0 ]
```
you can also set the last index to apply the replacement. For example, if you want to replace elements from index 1 (the second element) until index 3 (the third element included):
```js
const array3 = ['a', 'b', 'c', 'b', 'd', 'e', 'a']
array3.fill(
0, // the value to fill
1 // the index where to start
3 // the index where to end
)
console.dir(array3)
// [ 'a', 0, 0, 'b', 'd', 'e', 'a' ]
```
If you want to fill/replace the last element you can use the negative index:
```js
const array4 = ['a', 'b', 'c', 'b', 'd', 'e', 'a']
array4.fill(0, -1) // last element
console.dir(array4)
// [ 'a', 'b', 'c', 'b', 'd', 'e', 0 ]
array4.fill(0, -2) // last 2 elements
console.dir(array4)
// [ 'a', 'b', 'c', 'b', 'd', 0, 0 ]
```
================================================
FILE: src/content/docs/02-array/08_array-filter.md
================================================
---
title: "Filtering elements: `filter()`"
sidebar:
label: Filtering elements
---
## Filtering elements: `filter()`
With the arrays, you have the `filter()` method to filter the elements of the array with a specific condition. For example with an array of numbers, you want to retrieve only the element greater than 50.
The `filter()` doesn't change the original array. It returns a new array with the elements that satisfy the condition.
```js
const numbers = [3, 75, 42, 13, 69]
const resultNumbers = numbers.filter(
number => number >= 50
)
console.dir(resultNumbers)
// output: Array [ 75, 69 ]
```
If the element is an object you can filter for the attribute of the object. For example, if you have objects like this one:
```
{ product: 'Desk', price: 200, active: true }
```
and you have an array of elements, and you want to filter and retrieve the object with a price greater (or equal) than 150:
```js
const elements = [
{ product: 'Desk', price: 200, active: true },
{ product: 'Chair', price: 100, active: true },
{ product: 'Door', price: 300, active: false },
{ product: 'Bookcase', price: 150, active: true },
{ product: 'Door', price: 100, active: true }
]
const resultElements = elements.filter(
element => element.price >= 150
)
console.dir(resultElements)
```
the result is:
```
Array [
{ product: 'Desk', price: 200, active: true },
{ product: 'Door', price: 300, active: false },
{ product: 'Bookcase', price: 150, active: true }
]
```
you can create a more complex conditions like:
```js
const resultActiveElements = elements.filter(
element =>
(element.active && element.price >= 150)
)
```
where the result is:
```
Array [
{ product: 'Desk', price: 200, active: true },
{ product: 'Bookcase', price: 150, active: true }
]
```
================================================
FILE: src/content/docs/02-array/09_array-every.md
================================================
---
title: "Testing all elements: `every()`"
sidebar:
label: Checking all the elements
---
## Testing all elements: `every()`
If you have an array and you want to check if all the elements satisfy a certain condition, you can use `every()` method on Array.
For example, if you want to check that all the array elements are greater than 25, you can use this example:
```js
// the array
const array = [32, 30, 39, 29, 100, 43]
console.log(
array.every(
(currentValue) => currentValue > 25
)
)
```
================================================
FILE: src/content/docs/02-array/10_array-some.md
================================================
---
title: "Testing at least one element: `some()`"
sidebar:
label: Checking at least one element
---
## Testing at least one element: `some()`
If you have an array and you want to check if at least one of the elements satisfies a certain condition, you can use `some()` method on Array.
For example, if you want to check that at least one element of the array is greater than 90, you can use this example:
```js
const array = [32, 30, 39, 29, 100, 43]
console.log(
array.some(
(currentValue) => currentValue > 90
)
)
```
================================================
FILE: src/content/docs/02-array/11_array-map.md
================================================
---
title: 'Mapping an Array: `map()`'
sidebar:
label: Mapping Array
---
## Mapping an Array: `map()`
The `map()` method in JavaScript allows you to create a new array by applying a function to each element of an existing array. It iterates through the elements of the original array, performs a specified operation on each element, and returns a new array with the results.
### Example
Suppose you have an array of numbers and you want to create a new array where each number is doubled. You can use the `map()` method as shown in this example:
```js
const numbers = [1, 2, 3, 4, 5]
// Using map() method to create a new array by doubling each number
const doubledNumbers = numbers.map((number) => number * 2)
console.log('Original Array:', numbers)
console.log('Doubled Array:', doubledNumbers)
```
================================================
FILE: src/content/docs/02-array/12_array-reduce.md
================================================
---
title: 'Reducing an Array'
sidebar:
label: Reducing Array
---
## Reducing an Array: `reduce()`
The `reduce()` method is a powerful array method in JavaScript used to reduce an array into a single value. It iterates over each element of the array and applies a callback function to accumulate a result.
The `reduce()` function takes two main arguments: the callback function and an (_optional_) initial value.
The callback function is called for each element in the array and is responsible for accumulating the result. The result is then carried over to the next iteration. The final result is returned after iterating through all the array elements.
```js
//Syntax
reduce(callbackFn)
reduce(callbackFn, initialValue)
callbackFn(accumulator, currentValue, currentIndex, array)
```
- `callbackFn`: A function that is called for each element in the array. It takes four arguments:
- `accumulator`: The accumulated result from previous iterations or the initial value.
- `currentValue`: The current element being processed in the array.
- `currentIndex`: (Optional) The index of the current element being processed.
- `array`: (Optional) The array reduce() was called upon.
- `initialValue`: (Optional) The initial value for the accumulator. If not provided, the first element of the array is used as the initial value.
### Examples
_Example 1_, let's use the `reduce()` to find the sum of all elements in an array:
```js
const numbers = [1, 2, 3, 4, 5]
const sumWithInitialValue = numbers.reduce((accumulator, currentValue) => {
return accumulator + currentValue
}, 0) //Here 0 is an initial value to the accumulator
/* Here if we do not mention initialValue '0', then initial value of accumulator will be first array value
and the currentValue will be second value of Array. */
const sumWithoutInitialValue = numbers.reduce((acc, curr) => {
return acc + curr
})
console.log('SumWithInitialValue:', sumWithInitialValue)
console.log('SumWithoutInitialValue:', sumWithoutInitialValue)
```
_Example 2_, counting the number of occurrences of elements in an array using `reduce()`:
```js
const fruits = ['🍎', '🍓', '🍋', '🍎', '🍋', '🍎']
const fruitCounter = fruits.reduce((accumulator, currentFruit) => {
accumulator[currentFruit] = (accumulator[currentFruit] || 0) + 1
return accumulator
}, {})
console.log('Occurrences:', fruitCounter)
// Output: Occurrences: {
"🍎": 3,
"🍓": 1,
"🍋": 2
}
```
================================================
FILE: src/content/docs/02-array/13_array-splice.md
================================================
---
title: 'Modifying an Array'
description: 'Adding, removing, and replacing elements in an array with JavaScript.'
sidebar:
label: Modifying Array
---
## Adding, removing, and replacing elements in an array: `splice()`
The `splice()` method is a versatile array method in JavaScript that allows you to modify an array by adding, removing, or replacing elements. It directly changes the original array and returns an array of the removed elements.
The `splice()` method takes three main arguments: the start index, the number of elements to remove (_optional_), and the elements to add (_optional_).
By specifying a start index, you can define where the changes should occur in the array. The method can then remove a specified number of elements, add new elements, or both, depending on the parameters provided. This makes `splice()` a powerful tool for modifying arrays in place.
```js
//Syntax
splice(start)
splice(start, deleteCount)
splice(start, deleteCount, item1, item2, ...)
```
- `start`: The index at which to start modifying the array.
- `deleteCount`: (Optional) Number of elements to remove from the array.
- `item1, item2`: (Optional) Elements to add starting from the _start_ index.
### Adding Elements
The `splice()` method can add new elements to an array. New elements can be inserted at the specified start index by setting the `deleteCount` parameter (the second parameter) to 0.
Let's use the `splice()` method to modify an array by adding elements:
```js
const fruits = ['Apple', 'Banana', 'Cherry', 'Date']
// Adding elements
fruits.splice(1, 0, 'Blueberry', 'Coconut') // Adds two elements at index 1
console.log('Array after adding:', fruits) // Output: ['Apple', 'Blueberry', 'Coconut', 'Banana', 'Cherry', 'Date']
```
### Removing Elements
The `splice()` method can also remove elements from an array. By specifying the `start` index and `deleteCount`, a specific number of elements can be removed starting at a given position.
Let's use the `splice()` method to modify an array by removing elements:
```js
const fruits = ['Apple', 'Banana', 'Cherry', 'Date']
// Removing elements
const removedFruits = fruits.splice(1, 2) // Removes 2 elements starting from index 1
console.log('Modified array:', fruits) // Output: ['Apple', 'Date']
console.log('Removed elements:', removedFruits) // Output: ['Banana', 'Cherry']
```
### Replacing Elements
The `splice()` method can replace existing elements by removing some and adding others at the same index.
Let's use the `splice()` method to modify an array by replacing elements:
```js
const fruits = ['Apple', 'Blueberry', 'Coconut', 'Date']
// Replacing elements
fruits.splice(2, 1, 'Dragonfruit') // Replaces 1 element at index 2
console.log('Array after replacing:', fruits) // Output: ['Apple', 'Blueberry', 'Dragonfruit', 'Date']
```
### Swap elements in an array
Another useful application of the `splice()` function is to swap elements within an array.
This can be particularly handy when rearranging elements without using additional variables or temporary arrays. Here's how you can do it:
1. Identify the indices of the two elements you want to swap.
2. Use `splice()` to remove the element at one index and store it temporarily.
3. Use `splice()` again to insert the removed element at the position of the other element and vice versa.
Here is an example of using the `splice()` function to swap elements in an array:
```js
const arr = ['a', 'b', 'c', 'd']
function swap(arr, index1, index2) {
const [elem1] = arr.splice(index1, 1)
const [elem2] = arr.splice(index2 - 1, 1) // '-1' adjusts for the earlier removal of 'elem1'
arr.splice(index1, 0, elem2)
arr.splice(index2, 0, elem1)
}
swap(arr, 1, 3)
console.log('Swapped array:', arr) // Output: ['a', 'd', 'c', 'b']
```
================================================
FILE: src/content/docs/02-array/14_array-slice.md
================================================
---
title: 'Extracting Part of an Array'
sidebar:
label: Extracting Array
---
## Extracting part of an Array: `slice()`
The `slice()` method in JavaScript extracts a section of an array and returns it as a new array without modifying the original array. This method is helpful when working with a portion of an array without affecting the original one.
The `slice()` function takes two arguments: the start index (inclusive) and the end index (exclusive). The range defined by these indices is used to select elements from the array.
```js
//Syntax
slice(start)
slice(start, end)
`start`: The index at which to start extracting elements (inclusive). If not provided, `slice()` starts from index `0`.
`end`: (Optional) The index at which to stop extracting elements (exclusive). If not provided, `slice()` extracts up to the end of the array.
```
### Examples
_Example 1_, using `slice()` to extract a subarray:
```js
const animals = ['dog', 'cat', 'elephant', 'giraffe', 'lion']
const subArray = animals.slice(1, 4)
console.log(subArray) // Output: ['cat', 'elephant', 'giraffe']
```
In this example:
- The start index is `1` (which is "cat"), and the end index is `4` (which is "lion", but since the end index is exclusive, it's not included).
- The extracted subarray includes the elements from index `1` to `3`.
_Example 2_, using `slice()` with only the start index:
```js
const fruits = ['apple', 'banana', 'cherry', 'date', 'elderberry']
const subArrayFromIndex = fruits.slice(2)
console.log(subArrayFromIndex) // Output: ['cherry', 'date', 'elderberry']
```
- In this case, by providing only the start index (2), `slice()` extracts all elements from index 2 to the end of the array.
_Example 3_, using `slice()` with negative indices:
```js
const colors = ['red', 'blue', 'green', 'yellow', 'purple']
const lastTwo = colors.slice(-2)
console.log(lastTwo) // Output: ['yellow', 'purple']
```
- Negative indices can be used with `slice()`. A negative start index counts from the end of the array, so `-2` refers to the second-to-last element, and the extraction continues to the end.
### Notes
- Non-destructive: The `slice()` method does not modify the original array.
- Empty array: If the start index is greater than or equal to the array length, or if the start index is greater than the end index, `slice()` returns an empty array.
- Omitting arguments: If both start and end are omitted, `slice()` returns a shallow copy of the entire array.
- The `slice()` method returns a shallow copy of a portion of an array into a new array object.
- The `slice()` method can take no arguments: the start index is 0 and the end index is the length of the array.
================================================
FILE: src/content/docs/02-array/15_array-flat.md
================================================
---
title: 'Flattening an Array'
description: 'Flattening an Array with the flat() method'
sidebar:
label: Flattening an Array
---
## Flattening an Array: `flat()`
The `flat()` method in Javascript is used to flatten an array, meaning it merges nested sub-arrays into a single array up to a specified depth. This method is helpful when working with multidimentional arrays and merging arrays with nested elements.
The `flat()` method takes `depth` as an optional argument. By default, the depth is set to 1.
The option argument `depth` is the depth level specifying how deep a nested array structure should be flattened. Defaults to 1.
### Examples
_Example 1_, using `flat()` to flatten an array:
```javascript
const arr = [[1, 2, 3], [4, 5, 6], 7, 8];
console.log(arr.flat()); // Output: [1, 2, 3, 4, 5, 6, 7, 8]
```
In this example, the flat by default takes the depth as 1 and flattens the array to one level deep.
_Example 2_, using `flat()` with a depth argument:
```javascript
const arr2 = [1, 2, [3, 4, [5, 6]]];
console.log(arr2.flat()); // Output: [1, 2, 3, 4, [5, 6]]
console.log(arr2.flat(2)); // Output: [1, 2, 3, 4, 5, 6]
```
In this example, using the flat method without the depth argument flattens the array to only one level deep. Calling `flat()` without specifying a depth will flatten only the first level of nested arrays. This means it unpacks [3, 4] from the array, but leaves [5, 6] untouched, as it's inside another nested array.
Hence the result [1, 2, 3, 4, [5, 6]] – where [5, 6] is still nested.
But with the depth argument set to 2, `flat(2)` will flatten the array up to two levels deep. This means it will flatten both the first level ([3, 4]) and the second level ([5, 6]) of nesting, resulting in a completely flattened array in this case.
Hence the result [1, 2, 3, 4, 5, 6] – where all elements are at the top level.
_Example 3_, using `flat()` in an array which has empty slots (Sparse Array):
```javascript
const arr5 = [1, 2, , 4, 5];
console.log(arr5.flat()); // Output: [1, 2, 4, 5]
```
Using `flat()` method on a sparse array not only flattens nested arrays but also removes empty slots from sparse arrays. This behavior is particularly useful when you want to ensure that your array contains only defined values.
### Notes
- Setting the depth argument to `Infinity`, allows you to completely flatten an array. It ensures that no matter how deeply nested the elements are, they will all be accessible at the top level of the resulting array.
================================================
FILE: src/content/docs/02-array/16_array-findindex.md
================================================
---
title: 'Finding the Index'
description: 'Finding the index of the first element that passes a test'
sidebar:
label: Finding the Index
---
## Finding the index of the first element that passes a test: `findIndex()`
The `findIndex()` method in JavaScript searches through an array and returns the index of the first element that satisfies a provided testing function. If no such element is found, it returns -1. This method is useful for locating an element based on a specific condition without altering the original array.
The `findIndex()` function accepts a single argument: a callback function that tests each element in the array. This callback function can be customized to define the condition that the elements must meet to be considered.
```js
//Syntax
findIndex(callbackFn(currentVal, index, arr))
findIndex(callbackFn(currentVal, index, arr), thisArg)
```
- `callbackFn()`: A function to execute for each element in the array. It should return a truthy value to indicate a matching element has been found, and a falsy value otherwise. The function is called with the following arguments: currentVal, index and arr
- `currentVal`: (Required) The current element being processed in the array.
- `index`: (Optional) The index of the current element being processed in the array.
- `arr`: (Optional) The array findIndex() was called upon.
- `thisArg`: (Optional) The value to use as `this` when executing the callback function. By default it is undefined.
### Examples
_Example 1_, using `findIndex()` to get the index of the first element that passes the test:
```js
const ages = [3, 10, 18, 20];
let index = ages.findIndex(checkAge);
function checkAge(age) {
return age > 18;
}
```
In this example:
- A function checkAge() is passed as a callback to `findIndex()` function
- `findIndex()` function will execute checkAge() callback function for each element of ages array
- The condition age > 18 holds true for element value 20 at index 3 in ages array, therefore `findIndex()` will return 3
_Example 2_, `findIndex()` returns -1 when no element matches the callback function condition:
```js
const ages = [3, 10, 13, 15];
let index = ages.findIndex(checkAge);
function checkAge(age) {
return age > 18;
}
```
- In this case, no element of ages satisfies the age > 18 condition so the `findIndex()` function will return -1.
### Notes
- Executes a function on each array element
- Returns the index (position) of the first element that passes the test
- Returns -1 if no match is found
- Does not executes the function for empty array elements
- Does not change the original array
================================================
FILE: src/content/docs/02-array/17_array-at.md
================================================
---
title: 'Access an element at a specific index with `at()`'
sidebar:
label: Accessing a specific element
---
## Access an element at a specific index with `at()`
The `at()` method in Javascript allows you to access an element of an array at a specific index.
The `at()` method takes one argument, which is the index of the element that you want to retrieve. You can use positive or negative integers. Positive integers access elements from the start of the array, while negative integers count from the end.
### Examples
_Example 1_, using `at()` to access an element counting from the start of the array:
```js
const fruit = ["banana", "mango", "orange", "apple"]
console.log(fruit.at(0)) // Output: "banana"
const item = fruit.at(2)
console.log(item) // Output: "orange"
```
In this example we used positive integers to access elements, counting from the start of the array. When we used `0` as the index, the first element was returned.
_Example 2_, using `at()` to access an element counting back from the end of the array:
```js
const fruit = ["banana", "mango", "orange", "apple"]
console.log(fruit.at(-1)) // Output: "apple"
const item = fruit.at(-3)
console.log(item) // Output: "mango"
```
In this example we used negative integers to access elements, counting back from the end of the array. When we used `-1` as the index, the last element was returned.
### Notes
- When accessing an element with a negative index (for example `-2`), the `at()` function is accessing `index + array.length`.
- If the index is out of range, it will return `undefined`.
================================================
FILE: src/content/docs/02-array/18_array-flatmap.md
================================================
---
title: 'Flattening and Mapping a Nested Array'
description: 'Flattening and Mapping a Nested Array with the flatMap() method'
sidebar:
label: Flattening and Mapping a Nested Array
---
## Flattening and Mapping a Nested Array: `flatMap()`
The `flatMap()` method in JavaScript combines the functionality of `map()` and `flat()` into one. It maps each element using a mapping function and then flattens the result into a new array. By default, it flattens the array one level deep, making it useful for dealing with nested arrays while performing a transformation.
The `flatMap()` method does not take a depth argument; it flattens the array by exactly one level.
The two arguments:
- `callback`: a function to execute on each element.
- `thisArg`: value to use as `this` when executing the callback.
### Examples
_Example 1_, using `flatMap()` to map and flatten a nested array:
```javascript
const arr = [[1, 2], [3, 4], [5, 6]];
console.log(arr.flatMap(x => x)); // Output: [1, 2, 3, 4, 5, 6]
```
In this example, the `flatMap()` method is used to flatten each sub-array in arr by one level. The callback simply returns the elements as they are, and flatMap() flattens the resulting nested arrays.
_Example 2_, using `flatMap()` to handle nested arrays and sparse arrays:
```javascript
const arr3 = [[1, 2], , [3, 4], [5, 6]];
console.log(arr3.flatMap(x => x)); // Output: [1, 2, 3, 4, 5, 6]
```
In this example, `flatMap()` flattens the nested arrays while automatically removing empty slots from sparse arrays.
_Example 3_, using `flatMap()` to concatenate and flatten strings in a nested array:
```javascript
const arr4 = [["hello", "world"], ["foo", "bar"]];
console.log(arr4.flatMap(x => x.join(' '))); // Output: ["hello world", "foo bar"]
```
Here, each nested array is joined into a single string using `join()`, and `flatMap()` flattens the resulting array of strings into a single-level array.
### Notes
- The `flatMap()` method is a combination of `map()` followed by `flat(1)`.
- It's important to note that `flatMap()` only flattens by one level. If you need to flatten more deeply nested arrays, you should use `map()` followed by `flat()` with the required depth.
================================================
FILE: src/content/docs/02-array/19_array-keys.md
================================================
---
title: 'Iterating over Array Indexes'
sidebar:
label: Iterating over Array Indexes
---
## Iterating over Array Indexes with `keys()`
In JavaScript, the `keys()` method allows you to create an iterator object that contains the indexes (or keys) of the elements in an array.
The `keys()` method does not change the original array.
### Examples
_Example 1_, using `keys()` to iterate over an array:
```js
const fruit = ['watermelon', 'pineapple', 'pear', 'mango']
const fruitKeys = fruit.keys()
for (let key of fruitKeys) {
console.log(key)
}
// Output:
// 0
// 1
// 2
// 3
```
_Example 2_, using `keys()` with a sparse array:
If an array has "holes" (i.e. missing elements), the `keys()` method still iterates over all possible indexes.
```js
const animal = ['dog', , 'cat']
for (let key of animal.keys()) {
console.log(`Animal at index ${key} is ${animal[key]}`)
}
// Output:
// Animal at index 0 is dog
// Animal at index 1 is undefined
// Animal at index 2 is cat
```
================================================
FILE: src/content/docs/02-array/20_array-entries.md
================================================
---
title: "Getting key-value pairs from an array"
sidebar:
label: Array entries
---
## Array entries: `Array.entries()`
The **entries()** method in JavaScript returns a new Array Iterator object that contains key-value pairs for each index in the array. Each key-value pair is an array where the first element is the index and the second element is the value.
Syntax:
```javascript
array.entries()
```
### Parameters:
The `entries()` method doesn't take any parameters.
### Return Value:
The `entries()` method returns a new Array Iterator object that contains key-value pairs for each index in the array.
### Examples:
#### Basic Usage:
```javascript
const fruits = ['Apple', 'Banana', 'Orange'];
const iterator = fruits.entries();
for (const entry of iterator) {
console.log(entry);
}
// Output:
// [0, "Apple"]
// [1, "Banana"]
// [2, "Orange"]
```
In this example, the `entries()` method returns an iterator that provides key-value pairs (index-value pairs) of the array elements, which are then accessed using a for...of loop.
#### Destructuring in Loop:
```javascript
const colors = ['red', 'green', 'blue'];
const iterator = colors.entries();
for (const [index, value] of iterator) {
console.log(`${index}: ${value}`);
}
// Output:
// "0: red"
// "1: green"
// "2: blue"
```
Using array destructuring, we can directly access the index and value from each entry.
#### Converting Iterator to Array:
```javascript
const numbers = [1, 2, 3, 4, 5];
const iterator = numbers.entries();
const entriesArray = [...iterator];
console.log(entriesArray);
// Output: [[0, 1], [1, 2], [2, 3], [3, 4], [4, 5]]
```
Here, the spread operator (`...`) is used to convert the iterator returned by `entries()` into a new array of arrays.
#### Using with Iterator Methods:
```javascript
const letters = ['a', 'b', 'c'];
const iterator = letters.entries();
console.log(iterator.next().value); // Output: [0, "a"]
console.log(iterator.next().value); // Output: [1, "b"]
console.log(iterator.next().value); // Output: [2, "c"]
console.log(iterator.next().done); // Output: true
```
The iterator object has a `next()` method that returns the next value in the sequence along with a `done` property that indicates whether the iteration is complete.
### Common Use Cases:
1. **Creating a Map from an Array**:
```javascript
function arrayToMap(array) {
const map = new Map();
for (const [index, value] of array.entries()) {
map.set(index, value);
}
return map;
}
const fruits = ['Apple', 'Banana', 'Orange'];
const fruitsMap = arrayToMap(fruits);
console.log(fruitsMap.get(1)); // Output: "Banana"
```
2. **Filtering with Index Awareness**:
```javascript
function filterWithIndex(array, callback) {
const result = [];
for (const [index, value] of array.entries()) {
if (callback(value, index)) {
result.push(value);
}
}
return result;
}
const numbers = [10, 20, 30, 40, 50];
const filteredNumbers = filterWithIndex(numbers, (value, index) => index % 2 === 0);
console.log(filteredNumbers); // Output: [10, 30, 50]
```
3. **Creating an Object with Array Indices as Keys**:
```javascript
function arrayToObject(array) {
return Object.fromEntries(array.entries());
}
const fruits = ['Apple', 'Banana', 'Orange'];
const fruitsObject = arrayToObject(fruits);
console.log(fruitsObject);
// Output: { 0: "Apple", 1: "Banana", 2: "Orange" }
```
### Comparison with Other Array Iterator Methods:
JavaScript arrays provide three methods that return iterators:
```javascript
const arr = ['a', 'b', 'c'];
// entries() - returns [index, value] pairs
const entryIterator = arr.entries();
// Output when iterated: [0, "a"], [1, "b"], [2, "c"]
// keys() - returns indices
const keyIterator = arr.keys();
// Output when iterated: 0, 1, 2
// values() - returns values
const valueIterator = arr.values();
// Output when iterated: "a", "b", "c"
```
By using the `Array.entries()` method, you can efficiently iterate over both the indices and values of an array, which is particularly useful when you need to process elements while keeping track of their positions in the array.
================================================
FILE: src/content/docs/02-array/21_array-findlastindex.md
================================================
---
title: 'Finding the Last Index'
description: 'returns the last index of the element in the array that satisfies the provided testing function'
sidebar:
label: Finding the Last Index
---
## Finding the index of the last element that passes a test: `findLastIndex()`
The `findLastIndex()` method of Array instances iterates the array in reverse order and returns the index of the first element that satisfies the provided testing function. If no elements satisfy the testing function, -1 is returned.
The `findLastIndex()` function accepts a single argument: a callback function that tests each element in the array. This callback function can be customized to define the condition that elements must meet to be considered.
```js
//Syntax
findLastIndex(callbackFn(currentVal, index, arr))
findLastIndex(callbackFn(currentVal, index, arr), thisArg)
```
- `callbackFn()`: A function to execute for each element in the array. It should return a truthy value to indicate a matching element has been found, and a falsy value otherwise. The function is called with the following arguments: currentVal, index, and arr.
- `currentVal`: (Required) The current element being processed in the array.
- `index`: (Optional) The index of the current element being processed in the array.
- `arr`: (Optional) The array findLastIndex() was called upon.
`thisArg`: (Optional) The value to use as this when executing the callback function. By default, it is undefined.
### Examples
_Example 1_, using `findLastIndex()` to get the index of the last element that passes the test:
```js
const numbers = [5, 12, 8, 130, 44];
let lastIndex = numbers.findLastIndex(checkLargeNumber);
function checkLargeNumber(num) {
return num > 10;
}
```
In this example:
- A function checkLargeNumber() is passed as a callback to the findLastIndex() function.
- The findLastIndex() function will execute checkLargeNumber() for each element in the numbers array, starting from the end.
- The condition num > 10 holds true for the element 44 at index 4, so findLastIndex() returns 4.
_Example 2_, `findLastIndex()` returns -1 when no element matches the condition:
```js
const numbers = [1, 2, 3, 4, 5];
let lastIndex = numbers.findLastIndex(checkLargeNumber);
function checkLargeNumber(num) {
return num > 10;
}
```
- In this case, none of the elements in numbers satisfy the num > 10 condition, so the findLastIndex() function returns -1.
### Notes
- Executes the function on each array element, starting from the end of the array.
- Returns the index (position) of the last element that passes the test.
- Returns -1 if no match is found.
- Does not execute the function for empty array elements.
- Does not change the original array.
================================================
FILE: src/content/docs/02-array/22-array-findlast.md
================================================
---
title: 'Finding the Last Element'
description: 'Returns the last element in the array that satisfies the provided testing function'
sidebar:
label: Finding the Last Element
---
## Finding the last element that passes a test: `findLast()`
The **`findLast()`** method of Array instances allows you to search through an array from the **end to the beginning**. It returns the value of the **first element** that satisfies the provided testing function (tha callback function). If no elements meet the criteria, `undefined` is returned.
### 🔍 **Syntax**
```js
array.findLast(callbackFn(element, index, array))
array.findLast(callbackFn(element, index, array), thisArg)
```
callbackFn: A function that is executed for each element in the array. It should return a truthy value to indicate a match and a falsy value otherwise. The function is called with the following arguments:
- `element`: The current element being processed.
- `index`: The index of the current element (_optional_).
- `array`: The array `findLast()` was called upon (_optional_).
## 🌟 Examples
### Example 1: Using `findLast()` to find the last number greater than a specified value in an array:
```js
const numbers = [5, 12, 8, 130, 44];
const lastLargeNumber = numbers.findLast((element) => element > 10);
console.log(lastLargeNumber); // Expected output: 44
```
In the example above, the `findLast()` method is used to find the last number in the array that is greater than 10. It iterates through the array from right to left and returns the first element that meets the condition, which in this case is 44, the last element that is greater than 10.
#### Understanding the callback function
The callback function has one main parameter, `element`, which represents the current value being processed in the array during each iteration. Here’s how it works:
- As `findLast()` iterates over the array from the last element to the first, it passes each element of the array to the `element` parameter in the callback function.
- The condition in the callback function, `element > 10`, checks if the current element is greater than the specified value (10 in this case).
- The method stops as soon as it finds an element that satisfies the condition and returns that element. In this example, 44 is the last element in the array that is greater than 10.
#### Handling cases when no element matches the condition
If no element satisfies the condition, `findLast()` would return `undefined`.
```javascript
const numbers = [2, 4, 6, 8, 10];
const lastLargeNumber = numbers.findLast((element) => element > 20);
console.log(lastLargeNumber); // Expected output: undefined
```
In the example above, the `findLast()` method is used to find the last element in the array that is greater than 20. However, since none of the elements in the array `[2, 4, 6, 8, 10]` meet the condition `element > 20`, the method does not find any matching element.
When `findLast()` cannot find an element that satisfies the provided condition, it returns `undefined`. This is useful for safely handling cases where the array doesn't contain any values that match the specified criteria.
In real-world applications, you can use this behavior to handle scenarios where a condition might not be met, and return a fallback value or log a message if needed.
For example:
```javascript
if (lastLargeNumber === undefined) {
console.log("No element found that matches the condition.");
}
```
This additional check can help ensure your code handles edge cases gracefully, preventing errors or unexpected behavior when no elements satisfy the condition.
### Example 2: finding the last occurrence of a specific element
```js
const fruits = [
{ name: 'apple', color: 'red' },
{ name: 'lemon', color: 'yellow' },
{ name: 'kiwi', color: 'green' },
{ name: 'banana', color: 'yellow' },
{ name: 'grape', color: 'purple' }
];
const lastYelloFruit = fruits.findLast((fruit) => fruit.color === 'yellow');
console.log(lastYellowFruit);
// Expected output: { name: 'banana', color: 'yellow' }
```
In this example, we have an array of fruit objects, where each object contains two properties: `name` (the type of fruit) and `color`. We want to find the last occurrence of the fruit with `yellow` color in the array.
- The callback function checks if the `color` property of the `fruit` object is `'yellow'`.
- The `findLast()` method starts searching from the end of the array and returns the last object where the `color` is `'yellow'`.
- In this case, the last matched occurrence is `{ name: 'banana', color: 'yellow' }`.
Here, `findLast()` helps us locate the last occurrence of yellow fruit in the array, returning the expected object.
### Example 3: finding the last even number
```js
const mixedNumbers = [3, 5, 7, 10, 12, 15, 20];
const lastEvenNumber = mixedNumbers.findLast((num) => num % 2 === 0);
console.log(lastEvenNumber); // Expected output: 20
```
## ⚠️ Important Notes
1. Executes the provided function once for each element of the array, in descending order.
2. Returns undefined if no element satisfies the testing function.
3. Does not modify the original array, ensuring immutability.
4. Returns the value of the first element that satisfies the provided testing function.
## 🔗 Conclusion
The `findLast()` method is a valuable tool for efficiently locating the last matching element in an array, making your code more readable and maintainable!
================================================
FILE: src/content/docs/02-array/23-array-copywithin.md
================================================
---
title: 'Copy within an Array: `copyWithin()`'
sidebar:
label: Copy within an Array
---
## Copy within an array: `copyWithin()`
The `copyWithin()` method in JavaScript shallow copies part of an array to another location within the same array, without modifying the array’s length.
It allows for in-place modification of the array, making it a useful function for rearranging or manipulating data in arrays without creating new arrays. This method is efficient and destructive, altering the original array.
It accepts up to three parameters, but only the first parameter is mandatory. Here's how each parameter works:
```javascript
array.copyWithin(target, start, end)
```
1. `target` (required): this is the only mandatory parameter. It specifies the index where the copying will begin (the destination index). Elements from another part of the array will be copied here. If the target is negative, it will be counted from the end of the array.
2. `start` (optional): this is the index from which the copying will start (the source index). If omitted, the copying will start from the beginning of the array (index 0). If negative, it counts from the end of the array.
3. `end` (optional): this specifies the index where to stop copying (non-inclusive). If omitted, the copying continues until the end of the array. If negative, it also counts from the end of the array.
### Example: basic syntax with one parameter
When using one parameter with `copyWithin()`, this parameter indicates the target position from which the copied elements will be placed within the same array.
```javascript
const arr = [1, 2, 3, 4, 5, 6];
arr.copyWithin(3)
// arr is [ 1, 2, 3, 1, 2, 3 ]
```
In this case, the target parameter is the index (remember arrays are 0 index base), where the copied elements will start to be placed. The elements will be copied from index 0 (the start of the array) and moved to `target`.
Another example:
```javascript
const arr2 = [1, 2, 3, 4, 5, 6, 7];
arr2.copyWithin(3)
// arr2 is [ 1, 2, 3, 1, 2, 3, 4 ]
```
The initial part of the array is taken and copied from the `target` position.
An additional example, take a look at how are filled the 0s values:
```javascript
const arr3 = [1, 2, 3, 4, 0, 0, 0];
// the index 3 ^
arr3.copyWithin(3)
```
From the index 3 to the end of the array, there are 4 elements.
So `copyWithin` takes the first four elements of the array and copies them from the element at index 3
### Example: basic syntax with two parameters, `target` and `start`
Suppose you have an array of numbers, and you want to create a new array where you want to replace the elements from index 1 using items from index 3. You can use the `copyWithin()` method as shown in this example:
```js
const numbers = [1, 2, 3, 4, 5]
console.log('Original Array:', numbers)
//expected output: [1, 2, 3, 4, 5]
// Using copyWithin() method to create a new array
// where method copies to index 1 all elements from index 3 to the end
console.log('New Array:', numbers.copyWithin(1, 3))
//expected output: [1, 4, 5, 4, 5]
```
### Example about basic syntax with three parameters: `target`, `start`, and `end`
Another example, suppose you want to create a new array where you want to replace the elements from index 1 using items from 0 to index 3:
```js
const numbers = [1, 2, 3, 4, 5]
console.log('Original Array:', numbers)
//expected output: [1, 2, 3, 4, 5]
// In this case, the method copies to index 1 all elements from index 0 to index 3
console.log('New Array:', numbers.copyWithin(1, 0, 3))
//expected output: [1, 1, 2, 3, 5]
```
_Example 3_, `copyWithin()` allo
gitextract_291qlk5o/ ├── .editorconfig ├── .github/ │ └── ISSUE_TEMPLATE/ │ └── add-new-function.md ├── .gitignore ├── .prettierrc ├── CONTRIBUTING.md ├── HACKTOBERFEST.md ├── LICENSE.txt ├── README.md ├── astro.config.mjs ├── bun.lockb ├── examples/ │ ├── 01-01_os-cpus.mjs │ ├── 01-02_os-version.mjs │ ├── 01-03_os-userinfo.mjs │ ├── 01-04_os-freemem.mjs │ ├── 01-05_process-env.mjs │ ├── 01-06_os-totalmem.mjs │ ├── 01-07_os-loadavg.mjs │ ├── 01-08_os-networkinterfaces.mjs │ ├── 01-09_process-exit.mjs │ ├── 01-10_os-tmpdir.mjs │ ├── 01-11_performance-now.mjs │ ├── 02-01_array-join.mjs │ ├── 02-02_array-includes.mjs │ ├── 02-03_array-in.mjs │ ├── 02-04_array-concat.mjs │ ├── 02-05_array-merge_destructuring.mjs │ ├── 02-06_array-set.mjs │ ├── 02-07_array-fill.mjs │ ├── 02-08_array-filter.mjs │ ├── 02-09_array-every.mjs │ ├── 02-10_array-some.mjs │ ├── 02-11_array-map.mjs │ ├── 02-12_array-reduce.mjs │ ├── 02-13_array-splice.mjs │ ├── 02-15_array-flat.mjs │ ├── 02-16_array-findindex.mjs │ ├── 02-17_array-at.mjs │ ├── 02-18_array-flatmap.mjs │ ├── 02-19_array-keys.mjs │ ├── 02-20_array-entries.mjs │ ├── 02-21_array-findlastindex.mjs │ ├── 02-22_array-findlastind.mjs │ ├── 02-23_array-copywithin.mjs │ ├── 02-24_array-entries.mjs │ ├── 02-25_array-values.mjs │ ├── 02-26_array-sort.mjs │ ├── 02-27_array-reverse.mjs │ ├── 02-28_array-push-pop.mjs │ ├── 02-29_array-shift-unshift.mjs │ ├── 03-01_op-typeof.mjs │ ├── 03-02_path-sep.mjs │ ├── 03-03_os-eol.mjs │ ├── 03-12_object-groupby.mjs │ ├── 05-01_str-concat.mjs │ ├── 05-02_str-padding.mjs │ ├── 05-03_str-includes.mjs │ ├── 05-04_str-slice.mjs │ ├── 05-05_str-indexOf.mjs │ ├── 05-06_str-repeat.mjs │ ├── 05-07_str-split.mjs │ ├── 05-08_str-toUppercase.mjs │ ├── 05-09_str-toLowercase.mjs │ ├── 05-10_str-startsWith.mjs │ ├── 05-11_str-replaceAll.mjs │ ├── 05-12_str-trimstart-trimend.mjs │ ├── 05-13_str-trim.mjs │ ├── 05-14_str-endsWith.mjs │ ├── 05-15_str-substring.mjs │ ├── 05-16_str-replace.mjs │ ├── 05-17_str-lastIndexOf.mjs │ ├── 05-18_str-match.mjs │ └── 06-01_process-cwd.mjs ├── list-of-functions.md ├── package.json ├── src/ │ ├── components/ │ │ ├── about-block.astro │ │ ├── arrow.astro │ │ └── hero.astro │ ├── content/ │ │ └── docs/ │ │ ├── 00-intro/ │ │ │ ├── 00_intro.md │ │ │ ├── 01_contributing.md │ │ │ ├── 01_hacktoberfest-2024.md │ │ │ └── 02_runtime.md │ │ ├── 01-system/ │ │ │ ├── 00_system_intro.md │ │ │ ├── 01_os-cpus.md │ │ │ ├── 02_os-version.md │ │ │ ├── 03_os-userinfo.md │ │ │ ├── 04_process-env.md │ │ │ ├── 05_os-freemem.md │ │ │ ├── 06_os-totalmem.md │ │ │ ├── 07_os-loadavg.md │ │ │ ├── 08_os-networkinterfaces.md │ │ │ ├── 09_process-exit.md │ │ │ ├── 10_os-tmpdir.md │ │ │ └── 11_performance-now.md │ │ ├── 02-array/ │ │ │ ├── 00_array.md │ │ │ ├── 01_array-join.md │ │ │ ├── 02_array-includes.md │ │ │ ├── 03_array-in.md │ │ │ ├── 04_array-concat.md │ │ │ ├── 05_array-merge_destructuring.md │ │ │ ├── 06_array-set.md │ │ │ ├── 07_array-fill.md │ │ │ ├── 08_array-filter.md │ │ │ ├── 09_array-every.md │ │ │ ├── 10_array-some.md │ │ │ ├── 11_array-map.md │ │ │ ├── 12_array-reduce.md │ │ │ ├── 13_array-splice.md │ │ │ ├── 14_array-slice.md │ │ │ ├── 15_array-flat.md │ │ │ ├── 16_array-findindex.md │ │ │ ├── 17_array-at.md │ │ │ ├── 18_array-flatmap.md │ │ │ ├── 19_array-keys.md │ │ │ ├── 20_array-entries.md │ │ │ ├── 21_array-findlastindex.md │ │ │ ├── 22-array-findlast.md │ │ │ ├── 23-array-copywithin.md │ │ │ ├── 24-array-entries.md │ │ │ ├── 25_array-values.md │ │ │ ├── 26_array-sort.md │ │ │ ├── 27_array-reverse.md │ │ │ ├── 28_array-push-pop.md │ │ │ └── 29_array-shift-unshift.md │ │ ├── 03-var/ │ │ │ ├── 00_var-obj-const.md │ │ │ ├── 01_op-typeof.md │ │ │ ├── 02_path-sep.md │ │ │ ├── 03_os-eol.md │ │ │ ├── 04_object-getOwnPropertyNames.md │ │ │ ├── 05_object-keys.md │ │ │ ├── 06_object-values.md │ │ │ ├── 07_object-entries.md │ │ │ ├── 08_object-freeze.md │ │ │ ├── 09_object-seal.md │ │ │ ├── 10_object-isFrozen.md │ │ │ ├── 11_object-isSealed.md │ │ │ └── 12_object-groupby.md │ │ ├── 04-functions/ │ │ │ └── 00_functions.md │ │ ├── 05-string/ │ │ │ ├── 00_string.md │ │ │ ├── 01_str-concat.md │ │ │ ├── 02_str-padding.md │ │ │ ├── 03_str-includes.md │ │ │ ├── 04_str-slice.md │ │ │ ├── 05_str-indexOf.md │ │ │ ├── 06_str-repeat.md │ │ │ ├── 07_str-split.md │ │ │ ├── 08_str-toUppercase.md │ │ │ ├── 09_str-toLowercase.md │ │ │ ├── 10_str-startsWith.md │ │ │ ├── 11_str-replaceAll.md │ │ │ ├── 12_str-trimstart-trimend.md │ │ │ ├── 13_str-trim.md │ │ │ ├── 14_str-endsWith.md │ │ │ ├── 15_str-substring.md │ │ │ ├── 16_str-replace.md │ │ │ ├── 17_str-lastIndexOf.md │ │ │ └── 18_str-match.md │ │ ├── 06-files/ │ │ │ ├── 00_files.md │ │ │ └── 01_files-cwd.md │ │ └── index.mdx │ ├── content.config.ts │ ├── env.d.ts │ └── styles/ │ ├── custom.css │ └── tailwind.css ├── tailwind.config.mjs ├── tsconfig.json └── vercel.json
SYMBOL INDEX (45 symbols across 14 files)
FILE: examples/02-13_array-splice.mjs
function swap (line 35) | function swap(arr, index1, index2) {
FILE: examples/02-16_array-findindex.mjs
function checkAge (line 11) | function checkAge(age) {
FILE: examples/02-20_array-entries.mjs
function arrayToMap (line 53) | function arrayToMap(array) {
function filterWithIndex (line 68) | function filterWithIndex(array, callback) {
function arrayToObject (line 84) | function arrayToObject(array) {
FILE: examples/02-21_array-findlastindex.mjs
function checkLargeNumber (line 11) | function checkLargeNumber(num) {
FILE: examples/02-25_array-values.mjs
function processArrayValues (line 55) | function processArrayValues(array) {
FILE: examples/02-27_array-reverse.mjs
function reverseArrayCopy (line 35) | function reverseArrayCopy(array) {
function isPalindrome (line 49) | function isPalindrome(str) {
FILE: examples/02-28_array-push-pop.mjs
class Stack (line 45) | class Stack {
method constructor (line 46) | constructor() {
method push (line 50) | push(element) {
method pop (line 54) | pop() {
method peek (line 61) | peek() {
method isEmpty (line 65) | isEmpty() {
method size (line 69) | size() {
method clear (line 73) | clear() {
function navigateTo (line 120) | function navigateTo(page) {
function goBack (line 126) | function goBack() {
FILE: examples/02-29_array-shift-unshift.mjs
class Queue (line 45) | class Queue {
method constructor (line 46) | constructor() {
method enqueue (line 50) | enqueue(element) {
method dequeue (line 54) | dequeue() {
method front (line 61) | front() {
method isEmpty (line 68) | isEmpty() {
method size (line 72) | size() {
method clear (line 76) | clear() {
function slidingWindow (line 121) | function slidingWindow(arr, windowSize) {
FILE: examples/05-13_str-trim.mjs
function validateUsername (line 23) | function validateUsername(username) {
FILE: examples/05-14_str-endsWith.mjs
function isImageFile (line 27) | function isImageFile(filename) {
function isSecureGoogleUrl (line 38) | function isSecureGoogleUrl(url) {
function endsWithPunctuation (line 48) | function endsWithPunctuation(text) {
FILE: examples/05-15_str-substring.mjs
function truncateText (line 26) | function truncateText(text, maxLength) {
function getDomainFromUrl (line 39) | function getDomainFromUrl(url) {
function removeFirstAndLastChar (line 59) | function removeFirstAndLastChar(text) {
FILE: examples/05-16_str-replace.mjs
function formatPhoneNumber (line 31) | function formatPhoneNumber(phoneNumber) {
function sanitizeHTML (line 41) | function sanitizeHTML(text) {
function createSlug (line 57) | function createSlug(title) {
FILE: examples/05-17_str-lastIndexOf.mjs
function getFileExtension (line 25) | function getFileExtension(filename) {
function getLastWord (line 36) | function getLastWord(sentence) {
function endsWith (line 46) | function endsWith(str, suffix) {
FILE: examples/05-18_str-match.mjs
function extractEmails (line 31) | function extractEmails(text) {
function parseCSVLine (line 43) | function parseCSVLine(line) {
function isValidUsername (line 55) | function isValidUsername(username) {
function countWords (line 67) | function countWords(text) {
Condensed preview — 166 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (310K chars).
[
{
"path": ".editorconfig",
"chars": 235,
"preview": "root = true\n\n[*]\nindent_style = space\nindent_size = 2\nend_of_line = lf\ninsert_final_newline = true\ncharset = utf-8\ntrim_"
},
{
"path": ".github/ISSUE_TEMPLATE/add-new-function.md",
"chars": 951,
"preview": "---\nname: Add new JavaScript Function\nabout: Add new file for explaining a new JavaScript function\ntitle: 'New Function:"
},
{
"path": ".gitignore",
"chars": 256,
"preview": "# build output\ndist/\n# generated types\n.astro/\n\n# dependencies\nnode_modules/\npackage-lock.json\n\n# logs\nnpm-debug.log*\nya"
},
{
"path": ".prettierrc",
"chars": 115,
"preview": "{\n \"trailingComma\": \"es5\",\n \"tabWidth\": 2,\n \"useTabs\": false,\n \"semi\": false,\n \"singleQuote\": true\n}"
},
{
"path": "CONTRIBUTING.md",
"chars": 5627,
"preview": "# How to contribute\n\nThe goal is to build an open-source book about JavaScript functions for new users in the JavaScript"
},
{
"path": "HACKTOBERFEST.md",
"chars": 2051,
"preview": "# Hacktoberfest and \"Some drops of JavaScript\"\n\n\n\n## The reason why\nThis book coll"
},
{
"path": "astro.config.mjs",
"chars": 2715,
"preview": "import { defineConfig } from 'astro/config';\nimport starlight from '@astrojs/starlight';\nimport tailwind from '@astrojs/"
},
{
"path": "examples/01-01_os-cpus.mjs",
"chars": 1000,
"preview": "import { cpus } from 'os'\n\n// getting the CPUs via os.cpus() and looping\ncpus().forEach((cpu, index) => {\n // each cpu "
},
{
"path": "examples/01-02_os-version.mjs",
"chars": 470,
"preview": "import { version, platform, release, machine } from 'os'\nconst v = version()\nconsole.log(`Version: ${v}`)\n// Example\n// "
},
{
"path": "examples/01-03_os-userinfo.mjs",
"chars": 413,
"preview": "import { userInfo } from 'os'\nconst u = userInfo()\nconsole.log('Hi, %s here your infos:', u.username)\nconsole.table(u)\n/"
},
{
"path": "examples/01-04_os-freemem.mjs",
"chars": 228,
"preview": "import { freemem } from 'os'\nconst m = freemem()\nconsole.log('Hi, the free memory is %d bytes', m)\nconsole.log('Hi, the "
},
{
"path": "examples/01-05_process-env.mjs",
"chars": 312,
"preview": "console.log(process.env)\nconsole.log(process.env.PATH)\nconst envVarName = 'PATH'\nif (envVarName in process.env) {\n cons"
},
{
"path": "examples/01-06_os-totalmem.mjs",
"chars": 309,
"preview": "import { totalmem } from 'os'\nconst m = totalmem()\nconsole.log('Hi, the total memory is %d bytes', m)\nconsole.log('Hi, t"
},
{
"path": "examples/01-07_os-loadavg.mjs",
"chars": 83,
"preview": "import { loadavg } from 'os'\nconst la = loadavg()\nconsole.log(la[0], la[1], la[2])\n"
},
{
"path": "examples/01-08_os-networkinterfaces.mjs",
"chars": 402,
"preview": "import { networkInterfaces } from 'os'\nconst ni = networkInterfaces()\n\nObject.keys(ni).forEach(function (key, index) {\n "
},
{
"path": "examples/01-09_process-exit.mjs",
"chars": 76,
"preview": "console.log('Executing ...')\nprocess.exit(99)\nconsole.log('Never executed')\n"
},
{
"path": "examples/01-10_os-tmpdir.mjs",
"chars": 78,
"preview": "import { tmpdir } from 'os'\n\nconsole.log('Temporary directory: %s', tmpdir())\n"
},
{
"path": "examples/01-11_performance-now.mjs",
"chars": 332,
"preview": "let startTime = performance.now()\nconsole.log('Starting')\nconsole.log(performance.now() - startTime, startTime)\nstartTim"
},
{
"path": "examples/02-01_array-join.mjs",
"chars": 151,
"preview": "const elements = ['🥝', '🍓', '🍋']\n\nconsole.log(elements.join())\n// expected output: \"🥝,🍓,🍋\"\nconsole.log(elements.join('-'"
},
{
"path": "examples/02-02_array-includes.mjs",
"chars": 448,
"preview": "const elements = ['🥝', '🍓', '🍋']\n\nconsole.log(elements.includes('🍓'))\n// Does the array include the 🍓?\n// expected outpu"
},
{
"path": "examples/02-03_array-in.mjs",
"chars": 999,
"preview": "const fruits = {\n strawberry: 'Strawberry',\n kiwi: 'Kiwi',\n lemon: 'Lemon',\n}\n\nconsole.table(fruits)\nif ('kiwi' in fr"
},
{
"path": "examples/02-04_array-concat.mjs",
"chars": 255,
"preview": "const array1 = ['a', 'b', 'c']\nconst array2 = ['d', 'e', 'f']\nconsole.dir(array1.concat(array2))\n\nconst array3 = ['g', '"
},
{
"path": "examples/02-05_array-merge_destructuring.mjs",
"chars": 255,
"preview": "const array1 = ['a', 'b', 'c']\nconst array2 = ['d', 'e', 'f']\nconsole.dir([...array1, ...array2])\n// [ 'a', 'b', 'c', 'd"
},
{
"path": "examples/02-06_array-set.mjs",
"chars": 105,
"preview": "const array = ['a', 'b', 'c', 'b', 'd', 'e', 'a']\nconst unique = [...new Set(array)]\nconsole.dir(unique)\n"
},
{
"path": "examples/02-07_array-fill.mjs",
"chars": 600,
"preview": "const array = ['a', 'b', 'c', 'b', 'd', 'e', 'a']\narray.fill(0)\nconsole.dir(array)\n// [ 0, 0, 0, 0, 0, 0, 0 ]\n\nconst arr"
},
{
"path": "examples/02-08_array-filter.mjs",
"chars": 967,
"preview": "const numbers = [3, 75, 42, 13, 69]\nconst resultNumbers = numbers.filter((number) => number >= 50)\nconsole.dir(resultNum"
},
{
"path": "examples/02-09_array-every.mjs",
"chars": 103,
"preview": "const array = [32, 30, 39, 29, 100, 43]\n\nconsole.log(array.every((currentValue) => currentValue > 25))\n"
},
{
"path": "examples/02-10_array-some.mjs",
"chars": 102,
"preview": "const array = [32, 30, 39, 29, 100, 43]\n\nconsole.log(array.some((currentValue) => currentValue > 90))\n"
},
{
"path": "examples/02-11_array-map.mjs",
"chars": 247,
"preview": "const numbers = [1, 2, 3, 4, 5]\n\n// Using map() method to create a new array by doubling each number\nconst doubledNumber"
},
{
"path": "examples/02-12_array-reduce.mjs",
"chars": 1897,
"preview": "const numbers = [1, 2, 3, 4, 5]\n\nconst sumWithInitialValue = numbers.reduce((accumulator, currentValue) => {\n return ac"
},
{
"path": "examples/02-13_array-splice.mjs",
"chars": 1653,
"preview": "// Using splice() method to modify an array by removing, adding, and replacing elements:\nconst fruits = ['Apple', 'Banan"
},
{
"path": "examples/02-15_array-flat.mjs",
"chars": 330,
"preview": "const arr = [[1, 2, 3], [4, 5, 6], 7, 8]\nconsole.log(arr.flat()) // Output: [1, 2, 3, 4, 5, 6, 7, 8]\n\nconst arr2 = [1, 2"
},
{
"path": "examples/02-16_array-findindex.mjs",
"chars": 586,
"preview": "// using findIndex() method to get the first index of the element that passes the test\nconst ages = [3, 10, 18, 20]\n\n// "
},
{
"path": "examples/02-17_array-at.mjs",
"chars": 304,
"preview": "const fruit = ['banana', 'mango', 'orange', 'apple']\n\nconsole.log(fruit.at(0)) // Output: \"banana\"\n\nconst item = fruit.a"
},
{
"path": "examples/02-18_array-flatmap.mjs",
"chars": 494,
"preview": "const arr = [\n [1, 2],\n [3, 4],\n [5, 6],\n]\nconsole.log(arr.flatMap((x) => x)) // Output: [1, 2, 3, 4, 5, 6]\n\nconst ar"
},
{
"path": "examples/02-19_array-keys.mjs",
"chars": 425,
"preview": "const fruit = ['watermelon', 'pineapple', 'pear', 'mango']\nconst fruitKeys = fruit.keys()\n\nfor (let key of fruitKeys) {\n"
},
{
"path": "examples/02-20_array-entries.mjs",
"chars": 3304,
"preview": "// Examples for Array.entries()\n\n// Basic usage\nconst fruits = ['Apple', 'Banana', 'Orange']\nconsole.log('Original array"
},
{
"path": "examples/02-21_array-findlastindex.mjs",
"chars": 691,
"preview": "// using findLastIndex() method to get the last index of the element that passes the test\nconst numbers = [5, 12, 8, 130"
},
{
"path": "examples/02-22_array-findlastind.mjs",
"chars": 905,
"preview": "const numbers = [5, 12, 8, 130, 44]\n\nconst lastLargeNumber = numbers.findLast((element) => element > 10)\nconsole.log('La"
},
{
"path": "examples/02-23_array-copywithin.mjs",
"chars": 1026,
"preview": "const numbers = [1, 2, 3, 4, 5]\nconsole.log('Original Array:', numbers) //expected output: [1, 2, 3, 4, 5]\n\n// Using cop"
},
{
"path": "examples/02-24_array-entries.mjs",
"chars": 890,
"preview": "const fruits = ['Banana', 'Apple', 'Mango']\nconst fruitsEntries = fruits.entries()\n\nfor (const [index, fruit] of fruits."
},
{
"path": "examples/02-25_array-values.mjs",
"chars": 3105,
"preview": "// Examples for Array.values()\n\n// Basic usage\nconst fruits = ['Apple', 'Banana', 'Orange']\nconsole.log('Original array:"
},
{
"path": "examples/02-26_array-sort.mjs",
"chars": 3327,
"preview": "// Examples for Array.sort()\n\n// Basic usage - sorting strings\nconst fruits = ['Banana', 'Orange', 'Apple', 'Mango']\ncon"
},
{
"path": "examples/02-27_array-reverse.mjs",
"chars": 2874,
"preview": "// Examples for Array.reverse()\n\n// Basic usage\nconst fruits = ['Apple', 'Banana', 'Orange', 'Mango']\nconsole.log('Origi"
},
{
"path": "examples/02-28_array-push-pop.mjs",
"chars": 3850,
"preview": "// Examples for Array.push() and Array.pop()\n\n// Basic usage of push()\nconst fruits = ['Apple', 'Banana']\nconsole.log('O"
},
{
"path": "examples/02-29_array-shift-unshift.mjs",
"chars": 4134,
"preview": "// Examples for Array.shift() and Array.unshift()\n\n// Basic usage of shift()\nconst fruits = ['Apple', 'Banana', 'Orange'"
},
{
"path": "examples/03-01_op-typeof.mjs",
"chars": 118,
"preview": "console.log(typeof 12) // \"number\"\nconsole.log(typeof 'open source') //\"string\"\nconsole.log(typeof true) // \"boolean\"\n"
},
{
"path": "examples/03-02_path-sep.mjs",
"chars": 428,
"preview": "const path = require('path')\n\nconst folderName = 'documents'\nconst fileName = 'file.txt'\n\nconst filePath = `user${path.s"
},
{
"path": "examples/03-03_os-eol.mjs",
"chars": 119,
"preview": "const os = require('os')\n\nconst text = 'This is the first line' + os.EOL + 'This is the second line'\nconsole.log(text)\n"
},
{
"path": "examples/03-12_object-groupby.mjs",
"chars": 3653,
"preview": "// Sample inventory data\nconst inventory = [\n { name: 'asparagus', type: 'vegetables', quantity: 5 },\n { name: 'ba"
},
{
"path": "examples/05-01_str-concat.mjs",
"chars": 674,
"preview": "// Examples for String.concat()\n\n// Concatenating two strings\nconst str1 = 'Hello, '\nconst str2 = 'world'\nconst result1 "
},
{
"path": "examples/05-02_str-padding.mjs",
"chars": 1007,
"preview": "//Examples for padStart()\n\nconst text = 'Hello'\nconst paddedText = text.padStart(10)\nconsole.log(paddedText) // \" He"
},
{
"path": "examples/05-03_str-includes.mjs",
"chars": 422,
"preview": "const str = 'Hello, world!'\n\n// Examples of includes() with one parameter\n\nconst isWorldPresent = str.includes('world')\n"
},
{
"path": "examples/05-04_str-slice.mjs",
"chars": 548,
"preview": "const str = 'Hello, world!'\n\n// Using only the start parameter\nconst slicedString1 = str.slice(7)\nconsole.log(slicedStri"
},
{
"path": "examples/05-05_str-indexOf.mjs",
"chars": 398,
"preview": "const str = 'Hello, world!'\n\n// Finding the index of a substring\nconst index1 = str.indexOf('world')\nconsole.log(index1)"
},
{
"path": "examples/05-06_str-repeat.mjs",
"chars": 420,
"preview": "const str = 'Hello, '\n\n// Repeating a string multiple times\nconst repeatedString1 = str.repeat(3)\nconsole.log(repeatedSt"
},
{
"path": "examples/05-07_str-split.mjs",
"chars": 548,
"preview": "// Splitting a string based on a space separator\nconst str1 = 'Hello, world!'\nconst splitArray1 = str1.split(' ')\nconsol"
},
{
"path": "examples/05-08_str-toUppercase.mjs",
"chars": 165,
"preview": "const str = 'Hello, world!'\n\n// Converting a string to uppercase\nconst upperCasedString = str.toUpperCase()\nconsole.log("
},
{
"path": "examples/05-09_str-toLowercase.mjs",
"chars": 165,
"preview": "const str = 'Hello, World!'\n\n// Converting a string to lowercase\nconst lowercasedString = str.toLowerCase()\nconsole.log("
},
{
"path": "examples/05-10_str-startsWith.mjs",
"chars": 983,
"preview": "const str = 'Hello, world!'\n\n// Checking if a string starts with a specific substring\nconst startsWithHello = str.starts"
},
{
"path": "examples/05-11_str-replaceAll.mjs",
"chars": 1405,
"preview": "const str = 'Hello, world! Hello again, world!'\n\n// Replacing all occurrences of a substring\nconst replacedHello = str.r"
},
{
"path": "examples/05-12_str-trimstart-trimend.mjs",
"chars": 539,
"preview": "// Trimming Whitespace from the Start and End of a String\n\n// Removing Whitespace from the Start: trimStart()\n\n// Exampl"
},
{
"path": "examples/05-13_str-trim.mjs",
"chars": 1351,
"preview": "// Examples for String.trim()\n\n// Basic usage - removing spaces from both ends\nconst greeting = ' Hello world! '\ncon"
},
{
"path": "examples/05-14_str-endsWith.mjs",
"chars": 2036,
"preview": "// Examples for String.endsWith()\n\n// Basic usage\nconst sentence = 'This is a complete sentence.'\nconsole.log(`\"${senten"
},
{
"path": "examples/05-15_str-substring.mjs",
"chars": 2348,
"preview": "// Examples for String.substring()\n\n// Basic usage\nconst text = 'JavaScript'\nconsole.log('Original text:', text)\nconsole"
},
{
"path": "examples/05-16_str-replace.mjs",
"chars": 2456,
"preview": "// Examples for String.replace()\n\n// Basic usage with string pattern\nconst text = 'Hello, world!'\nconsole.log('Original "
},
{
"path": "examples/05-17_str-lastIndexOf.mjs",
"chars": 2488,
"preview": "// Examples for String.lastIndexOf()\n\n// Basic usage\nconst text = 'JavaScript is amazing. JavaScript is fun.'\nconsole.lo"
},
{
"path": "examples/05-18_str-match.mjs",
"chars": 2665,
"preview": "// Examples for String.match()\n\n// Basic usage with global flag\nconst text = 'The rain in Spain stays mainly in the plai"
},
{
"path": "examples/06-01_process-cwd.mjs",
"chars": 631,
"preview": "// Simple example of using process.cwd()\n\n// 1. Get and display the current working directory\nconsole.log('Current worki"
},
{
"path": "list-of-functions.md",
"chars": 4738,
"preview": "- [x] 01-00 **System**\n- [x] 01-01 Info from CPU: `os.cpus()`\n- [x] 01-02 Info from Operating System: `os.version()` and"
},
{
"path": "package.json",
"chars": 683,
"preview": "{\n \"name\": \"some-drops-of-javascript\",\n \"type\": \"module\",\n \"version\": \"0.0.1\",\n \"scripts\": {\n \"dev\": \"astro dev\","
},
{
"path": "src/components/about-block.astro",
"chars": 1324,
"preview": "---\ninterface Props {\n title: string\n}\n\nconst { title } = Astro.props\n---\n\n<article class=\"sl-flex\" aria-labelledby=\"ab"
},
{
"path": "src/components/arrow.astro",
"chars": 332,
"preview": "<svg\n class=\"w-5 h-5 ml-2 -mr-1\"\n fill=\"currentColor\"\n viewBox=\"0 0 20 20\"\n xmlns=\"http://www.w3.org/2000/svg\"\n ><p"
},
{
"path": "src/components/hero.astro",
"chars": 1836,
"preview": "---\ninterface Props {\n title: string\n}\n\nconst { title } = Astro.props\nimport Arrow from './arrow.astro'\nimport { Image "
},
{
"path": "src/content/docs/00-intro/00_intro.md",
"chars": 2820,
"preview": "---\ntitle: Some drops of JavaScript\ndescription: This HTML eBook collects some useful, unknown, underrated JavaScript fu"
},
{
"path": "src/content/docs/00-intro/01_contributing.md",
"chars": 2950,
"preview": "---\ntitle: The Open Source eBook\ndescription: We are excited to invite you to join our repository and contribute to the "
},
{
"path": "src/content/docs/00-intro/01_hacktoberfest-2024.md",
"chars": 2391,
"preview": "---\ntitle: Hacktoberfest and \"Some drops of JavaScript\"\ndescription: How to contribute for Hacktoberfest.\nsidebar:\n lab"
},
{
"path": "src/content/docs/00-intro/02_runtime.md",
"chars": 3966,
"preview": "---\ntitle: What is JavaScript?\ndescription: JavaScript, the language, the engine, and the runtime.\nsidebar:\n label: Wha"
},
{
"path": "src/content/docs/01-system/00_system_intro.md",
"chars": 2120,
"preview": "---\ntitle: System functions\ndescription: The chapter covers functions about \"system\" functionalities (for example how to"
},
{
"path": "src/content/docs/01-system/01_os-cpus.md",
"chars": 3580,
"preview": "---\ntitle: \"CPUs information\"\ndescription: \"Retrieving the list of the available CPUs\"\nsidebar:\n label: CPUs informatio"
},
{
"path": "src/content/docs/01-system/02_os-version.md",
"chars": 1226,
"preview": "---\ntitle: \"OS information\"\nsidebar:\n label: OS information\n---\nIf you need to retrieve information about the Operating"
},
{
"path": "src/content/docs/01-system/03_os-userinfo.md",
"chars": 821,
"preview": "---\ntitle: \"Getting user information\"\nsidebar:\n label: User information\n---\nWhen you launch a Node script, you will lau"
},
{
"path": "src/content/docs/01-system/04_process-env.md",
"chars": 1329,
"preview": "---\ntitle: \"Access to environment variables: process.env\"\nsidebar:\n label: Environment Vars\n---\n\n## Access to environme"
},
{
"path": "src/content/docs/01-system/05_os-freemem.md",
"chars": 556,
"preview": "---\ntitle: \"Get the amount of free memory in bytes (as integer): `os.freemem()`\"\nsidebar:\n label: Free memory\n---\n\n## G"
},
{
"path": "src/content/docs/01-system/06_os-totalmem.md",
"chars": 587,
"preview": "---\ntitle: \"Get the amount of total memory available in bytes\"\nsidebar:\n label: Available memory\n---\n\n## Get the amount"
},
{
"path": "src/content/docs/01-system/07_os-loadavg.md",
"chars": 889,
"preview": "---\ntitle: \"Getting the load average of CPU\"\nsidebar:\n label: CPU load\n---\n\n## The load average of CPU: `os.loadavg()`\n"
},
{
"path": "src/content/docs/01-system/08_os-networkinterfaces.md",
"chars": 1337,
"preview": "---\ntitle: \"Getting the network interfaces information\"\nsidebar:\n label: Network interfaces\n---\n\n## Network interfaces "
},
{
"path": "src/content/docs/01-system/09_process-exit.md",
"chars": 1305,
"preview": "---\ntitle: \"Stopping the script execution\"\nsidebar:\n label: Stop execution\n---\n\n## Stop the script execution: `process."
},
{
"path": "src/content/docs/01-system/10_os-tmpdir.md",
"chars": 474,
"preview": "---\ntitle: \"Getting the temporary directory absolute path\"\nsidebar:\n label: Temp directory\n---\n\n## Getting the temporar"
},
{
"path": "src/content/docs/01-system/11_performance-now.md",
"chars": 1040,
"preview": "---\ntitle: \"Tracking the execution time getting the monotonic time\"\nsidebar:\n label: Tracking time\n---\n\n## Getting mono"
},
{
"path": "src/content/docs/02-array/00_array.md",
"chars": 2784,
"preview": "---\ntitle: \"Array\"\ndescription: The chapter will cover functions about \"array\" functionalities\nsidebar:\n label: Introdu"
},
{
"path": "src/content/docs/02-array/01_array-join.md",
"chars": 628,
"preview": "---\ntitle: \"Create a string from an array: `join()`\"\nsidebar:\n label: From array to string\n---\n\n## Create a string from"
},
{
"path": "src/content/docs/02-array/02_array-includes.md",
"chars": 958,
"preview": "---\ntitle: \"Check if the array includes a certain value: `includes()`\"\nsidebar:\n label: Checking an item\n---\n\n## Check "
},
{
"path": "src/content/docs/02-array/03_array-in.md",
"chars": 1550,
"preview": "---\ntitle: \"Check if a property exists in the object or array: `in`\"\nsidebar:\n label: Checking a property\n---\n\n## Check"
},
{
"path": "src/content/docs/02-array/04_array-concat.md",
"chars": 607,
"preview": "---\ntitle: \"Concatenate two (or more) arrays: `concat()`\"\nsidebar:\n label: Concatenating arrays\n---\n\n## Concatenate two"
},
{
"path": "src/content/docs/02-array/05_array-merge_destructuring.md",
"chars": 1116,
"preview": "---\ntitle: \"Concat arrays via destructuring\"\nsidebar:\n label: Concatenating arrays via destructuring\n---\n\n## Concat arr"
},
{
"path": "src/content/docs/02-array/06_array-set.md",
"chars": 538,
"preview": "---\ntitle: \"Remove duplicate values in an array via `Set()`\"\nsidebar:\n label: Removing duplicates\n---\n\n## Remove duplic"
},
{
"path": "src/content/docs/02-array/07_array-fill.md",
"chars": 1780,
"preview": "---\ntitle: \"Generate and fill a new array `fill()`\"\nsidebar:\n label: Filling an array\n---\n\n## Generate and fill a new a"
},
{
"path": "src/content/docs/02-array/08_array-filter.md",
"chars": 1799,
"preview": "---\ntitle: \"Filtering elements: `filter()`\"\nsidebar:\n label: Filtering elements\n---\n\n## Filtering elements: `filter()`\n"
},
{
"path": "src/content/docs/02-array/09_array-every.md",
"chars": 510,
"preview": "---\ntitle: \"Testing all elements: `every()`\"\nsidebar:\n label: Checking all the elements\n---\n\n## Testing all elements: `"
},
{
"path": "src/content/docs/02-array/10_array-some.md",
"chars": 535,
"preview": "---\ntitle: \"Testing at least one element: `some()`\"\nsidebar:\n label: Checking at least one element\n---\n\n## Testing at l"
},
{
"path": "src/content/docs/02-array/11_array-map.md",
"chars": 810,
"preview": "---\ntitle: 'Mapping an Array: `map()`'\nsidebar:\n label: Mapping Array\n---\n\n## Mapping an Array: `map()`\n\nThe `map()` me"
},
{
"path": "src/content/docs/02-array/12_array-reduce.md",
"chars": 2429,
"preview": "---\ntitle: 'Reducing an Array'\nsidebar:\n label: Reducing Array\n---\n\n## Reducing an Array: `reduce()`\n\nThe `reduce()` me"
},
{
"path": "src/content/docs/02-array/13_array-splice.md",
"chars": 3811,
"preview": "---\ntitle: 'Modifying an Array'\ndescription: 'Adding, removing, and replacing elements in an array with JavaScript.'\nsid"
},
{
"path": "src/content/docs/02-array/14_array-slice.md",
"chars": 2685,
"preview": "---\ntitle: 'Extracting Part of an Array'\nsidebar:\n label: Extracting Array\n---\n\n## Extracting part of an Array: `slice("
},
{
"path": "src/content/docs/02-array/15_array-flat.md",
"chars": 2508,
"preview": "---\ntitle: 'Flattening an Array'\ndescription: 'Flattening an Array with the flat() method'\nsidebar:\n label: Flattening "
},
{
"path": "src/content/docs/02-array/16_array-findindex.md",
"chars": 2618,
"preview": "---\ntitle: 'Finding the Index'\ndescription: 'Finding the index of the first element that passes a test'\nsidebar:\n label"
},
{
"path": "src/content/docs/02-array/17_array-at.md",
"chars": 1589,
"preview": "---\ntitle: 'Access an element at a specific index with `at()`'\nsidebar:\n label: Accessing a specific element\n---\n\n## Ac"
},
{
"path": "src/content/docs/02-array/18_array-flatmap.md",
"chars": 2202,
"preview": "---\ntitle: 'Flattening and Mapping a Nested Array'\ndescription: 'Flattening and Mapping a Nested Array with the flatMap("
},
{
"path": "src/content/docs/02-array/19_array-keys.md",
"chars": 991,
"preview": "---\ntitle: 'Iterating over Array Indexes'\nsidebar:\n label: Iterating over Array Indexes\n---\n\n## Iterating over Array In"
},
{
"path": "src/content/docs/02-array/20_array-entries.md",
"chars": 4121,
"preview": "---\ntitle: \"Getting key-value pairs from an array\"\nsidebar:\n label: Array entries\n---\n\n## Array entries: `Array.entries"
},
{
"path": "src/content/docs/02-array/21_array-findlastindex.md",
"chars": 2724,
"preview": "---\ntitle: 'Finding the Last Index'\ndescription: 'returns the last index of the element in the array that satisfies the "
},
{
"path": "src/content/docs/02-array/22-array-findlast.md",
"chars": 5445,
"preview": "---\ntitle: 'Finding the Last Element'\ndescription: 'Returns the last element in the array that satisfies the provided te"
},
{
"path": "src/content/docs/02-array/23-array-copywithin.md",
"chars": 7274,
"preview": "---\ntitle: 'Copy within an Array: `copyWithin()`'\nsidebar:\n label: Copy within an Array\n---\n\n## Copy within an array: `"
},
{
"path": "src/content/docs/02-array/24-array-entries.md",
"chars": 3323,
"preview": "---\ntitle: 'Instances an Array iterator: `entries()`'\nsidebar:\n label: Instances an Array iterator\n---\n\n## Instances an"
},
{
"path": "src/content/docs/02-array/25_array-values.md",
"chars": 3777,
"preview": "---\ntitle: \"Getting array values as an iterator\"\nsidebar:\n label: Array values\n---\n\n## Array values: `Array.values()`\n\n"
},
{
"path": "src/content/docs/02-array/26_array-sort.md",
"chars": 4424,
"preview": "---\ntitle: \"Sorting array elements\"\nsidebar:\n label: Array sort\n---\n\n## Array sort: `Array.sort()`\n\nThe **sort()** meth"
},
{
"path": "src/content/docs/02-array/27_array-reverse.md",
"chars": 3815,
"preview": "---\ntitle: \"Reversing array elements\"\nsidebar:\n label: Array reverse\n---\n\n## Array reverse: `Array.reverse()`\n\nThe **re"
},
{
"path": "src/content/docs/02-array/28_array-push-pop.md",
"chars": 4865,
"preview": "---\ntitle: \"Adding and removing elements from the end of an array\"\nsidebar:\n label: Array push and pop\n---\n\n## Array pu"
},
{
"path": "src/content/docs/02-array/29_array-shift-unshift.md",
"chars": 5129,
"preview": "---\ntitle: \"Adding and removing elements from the beginning of an array\"\nsidebar:\n label: Array shift and unshift\n---\n\n"
},
{
"path": "src/content/docs/03-var/00_var-obj-const.md",
"chars": 1284,
"preview": "---\ntitle: \"Objects, Variables and Constants\"\ndescription: Exploring JavaScript Objects and Variables\nsidebar:\n label: "
},
{
"path": "src/content/docs/03-var/01_op-typeof.md",
"chars": 370,
"preview": "---\ntitle: Getting the type of a variable\nsidebar:\n label: Determine the type of a variable\n---\n\n## Getting the type of"
},
{
"path": "src/content/docs/03-var/02_path-sep.md",
"chars": 1432,
"preview": "---\ntitle: 'Getting the path separator'\nsidebar:\n label: Path Separator\n---\n\n## Path separator: `sep`\n\nThe `path.sep` p"
},
{
"path": "src/content/docs/03-var/03_os-eol.md",
"chars": 1276,
"preview": "---\ntitle: 'Getting the portable end of line'\nsidebar:\n label: End Of Line\n---\n\n## The portable end of line: `os.EOL`\n`"
},
{
"path": "src/content/docs/03-var/04_object-getOwnPropertyNames.md",
"chars": 1034,
"preview": "---\ntitle: 'Getting the object properties'\nsidebar:\n label: The object property names\n---\n\n## Getting the property name"
},
{
"path": "src/content/docs/03-var/05_object-keys.md",
"chars": 958,
"preview": "---\ntitle: 'Getting all the object properties/attributes'\nsidebar:\n label: The object keys\n---\n\n## Getting all the prop"
},
{
"path": "src/content/docs/03-var/06_object-values.md",
"chars": 1119,
"preview": "---\ntitle: 'Getting all the object values'\nsidebar:\n label: The object values\n---\n\n\n## Getting all the values of an obj"
},
{
"path": "src/content/docs/03-var/07_object-entries.md",
"chars": 1369,
"preview": "---\ntitle: 'Getting all the object entries'\nsidebar:\n label: The object entries\n---\n\n## Getting key-value pairs of an o"
},
{
"path": "src/content/docs/03-var/08_object-freeze.md",
"chars": 2223,
"preview": "---\ntitle: 'Freezing an object'\nsidebar:\n label: Freezing an object\n---\n\n## Prevent modification of an object using `Ob"
},
{
"path": "src/content/docs/03-var/09_object-seal.md",
"chars": 1153,
"preview": "---\ntitle: 'Sealing an object'\nsidebar:\n label: Sealing an object\n---\n\n\n## Sealing Objects with `Object.seal()`\n\nThe `O"
},
{
"path": "src/content/docs/03-var/10_object-isFrozen.md",
"chars": 1108,
"preview": "---\ntitle: 'Checking for Object Immutability in JavaScript'\nsidebar:\n label: Object Immutability\n---\n\n## Verifying Obje"
},
{
"path": "src/content/docs/03-var/11_object-isSealed.md",
"chars": 1199,
"preview": "---\ntitle: 'Checking for Object Sealing in JavaScript'\nsidebar:\n label: Object Sealing\n---\n\n## Determining Object Seali"
},
{
"path": "src/content/docs/03-var/12_object-groupby.md",
"chars": 5270,
"preview": "---\ntitle: 'Grouping array elements'\ndescription: 'Groups elements of an array based on a function, returning an object'"
},
{
"path": "src/content/docs/04-functions/00_functions.md",
"chars": 390,
"preview": "---\ntitle: \"Functions\"\ndescription: The chapter will cover several types of functions we can use in JavaScript\nsidebar:\n"
},
{
"path": "src/content/docs/05-string/00_string.md",
"chars": 573,
"preview": "---\ntitle: \"Strings\"\ndescription: The chapter will cover several JavaScript string functions\nsidebar:\n label: Introduct"
},
{
"path": "src/content/docs/05-string/01_str-concat.md",
"chars": 1604,
"preview": "---\ntitle: \"Concatenating strings\"\nsidebar:\n label: Concatenate strings\n---\n\nConcatenating strings in JavaScript allows"
},
{
"path": "src/content/docs/05-string/02_str-padding.md",
"chars": 2151,
"preview": "---\ntitle: \"Padding strings\"\nsidebar:\n label: Padding strings\n---\n\nThe padding function in JavaScript allows you to add"
},
{
"path": "src/content/docs/05-string/03_str-includes.md",
"chars": 2462,
"preview": "---\ntitle: \"Checking if a string includes a specific substring\"\nsidebar:\n label: String includes\n---\n## String includes"
},
{
"path": "src/content/docs/05-string/04_str-slice.md",
"chars": 2682,
"preview": "---\ntitle: \"Extracting a substring from a string\"\nsidebar:\n label: String slice\n---\n## String slice: `String.slice()`\n\n"
},
{
"path": "src/content/docs/05-string/05_str-indexOf.md",
"chars": 2220,
"preview": "---\ntitle: \"Finding the Index of a Substring in a String\"\nsidebar:\n label: String indexOf\n---\n## String indexOf: `Strin"
},
{
"path": "src/content/docs/05-string/06_str-repeat.md",
"chars": 2016,
"preview": "---\ntitle: \"Repeating a String\"\nsidebar:\n label: Repeating a String\n---\n## String repeat: `String.repeat()`\n\nThe `repea"
},
{
"path": "src/content/docs/05-string/07_str-split.md",
"chars": 2415,
"preview": "---\ntitle: \"Splitting a String into an Array\"\nsidebar:\n label: Splitting a String into an Array\n---\n## String split: `S"
},
{
"path": "src/content/docs/05-string/08_str-toUppercase.md",
"chars": 1209,
"preview": "---\ntitle: \"Converting a String to Uppercase\"\nsidebar:\n label: Converting a String to Uppercase\n---\n## String uppercase"
},
{
"path": "src/content/docs/05-string/09_str-toLowercase.md",
"chars": 1206,
"preview": "---\ntitle: \"Converting a String to Lowercase\"\nsidebar:\n label: Converting a String to Lowercase\n---\n## String lowercase"
},
{
"path": "src/content/docs/05-string/10_str-startsWith.md",
"chars": 3929,
"preview": "---\ntitle: \"Checking if a String Starts With a Substring\"\nsidebar:\n label: String startsWith\n---\n## String startsWith: "
},
{
"path": "src/content/docs/05-string/11_str-replaceAll.md",
"chars": 3476,
"preview": "---\ntitle: \"Replacing All Occurrences of a Substring\"\nsidebar:\n label: String replaceAll\n---\n## String replaceAll: `Str"
},
{
"path": "src/content/docs/05-string/12_str-trimstart-trimend.md",
"chars": 2120,
"preview": "---\ntitle: 'Trimming Whitespace from the Start and End of a String'\ndescription: 'Removes whitespace from the beginning "
},
{
"path": "src/content/docs/05-string/13_str-trim.md",
"chars": 2509,
"preview": "---\ntitle: \"Removing whitespace from both ends of a string\"\nsidebar:\n label: String trim\n---\n\n## String trim: `String.t"
},
{
"path": "src/content/docs/05-string/14_str-endsWith.md",
"chars": 3407,
"preview": "---\ntitle: \"Checking if a string ends with a specific substring\"\nsidebar:\n label: String endsWith\n---\n\n## String endsWi"
},
{
"path": "src/content/docs/05-string/15_str-substring.md",
"chars": 3566,
"preview": "---\ntitle: \"Extracting parts of a string\"\nsidebar:\n label: String substring\n---\n\n## String substring: `String.substring"
},
{
"path": "src/content/docs/05-string/16_str-replace.md",
"chars": 3712,
"preview": "---\ntitle: \"Replacing substrings in a string\"\nsidebar:\n label: String replace\n---\n\n## String replace: `String.replace()"
},
{
"path": "src/content/docs/05-string/17_str-lastIndexOf.md",
"chars": 3605,
"preview": "---\ntitle: \"Finding the last occurrence of a substring\"\nsidebar:\n label: String lastIndexOf\n---\n\n## String lastIndexOf:"
},
{
"path": "src/content/docs/05-string/18_str-match.md",
"chars": 3943,
"preview": "---\ntitle: \"Matching strings against regular expressions\"\nsidebar:\n label: String match\n---\n\n## String match: `String.m"
},
{
"path": "src/content/docs/06-files/00_files.md",
"chars": 1445,
"preview": "---\ntitle: \"File handling in JavaScript: essential functions for efficient file management\"\ndescription: Discover essent"
},
{
"path": "src/content/docs/06-files/01_files-cwd.md",
"chars": 1644,
"preview": "---\ntitle: 'Getting the Current Working Directory'\ndescription: 'Using process.cwd() to retrieve the current working dir"
},
{
"path": "src/content/docs/index.mdx",
"chars": 2188,
"preview": "---\ntitle: Some drops of JavaScript\ndescription: Book that collects some useful, unknown, underrated JavaScript function"
},
{
"path": "src/content.config.ts",
"chars": 269,
"preview": "import { defineCollection } from 'astro:content';\nimport { docsLoader } from '@astrojs/starlight/loaders';\nimport { docs"
},
{
"path": "src/env.d.ts",
"chars": 85,
"preview": "/// <reference path=\"../.astro/types.d.ts\" />\n/// <reference types=\"astro/client\" />\n"
},
{
"path": "src/styles/custom.css",
"chars": 1577,
"preview": "/* Dark mode colors. */\n@import url('https://fonts.googleapis.com/css2?family=Montserrat&display=swap');\n@import url('ht"
},
{
"path": "src/styles/tailwind.css",
"chars": 59,
"preview": "@tailwind base;\n@tailwind components;\n@tailwind utilities;\n"
},
{
"path": "tailwind.config.mjs",
"chars": 299,
"preview": "import starlightPlugin from '@astrojs/starlight-tailwind'\n\n/** @type {import('tailwindcss').Config} */\nexport default {\n"
},
{
"path": "tsconfig.json",
"chars": 108,
"preview": "{\n \"extends\": \"astro/tsconfigs/strict\",\n \"compilerOptions\": {\n \"types\": [\n \"bun-types\"\n ]\n }\n}"
},
{
"path": "vercel.json",
"chars": 159,
"preview": "{\n \"redirects\": [\n {\n \"source\": \"/00-intro/01_hacktoberfest/\",\n \"destination\": \"/00-intro/01_contributing/"
}
]
// ... and 1 more files (download for full content)
About this extraction
This page contains the full source code of the roberto-butti/some-drops-of-javascript GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 166 files (282.7 KB), approximately 77.2k tokens, and a symbol index with 45 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.