fix(guide): restructure curriculum guide articles (#36501)

* fix: restructure certifications guide articles
* fix: added 3 dashes line before prob expl
* fix: added 3 dashes line before hints
* fix: added 3 dashes line before solutions
This commit is contained in:
Randell Dawson
2019-07-24 00:59:27 -07:00
committed by mrugesh
parent c911e77eed
commit 1494a50123
990 changed files with 13202 additions and 8628 deletions

View File

@ -1,7 +1,7 @@
---
title: Exercise Tracker
---
## Exercise Tracker
# Exercise Tracker
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/apis-and-microservices/apis-and-microservices-projects/exercise-tracker/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.

View File

@ -1,7 +1,7 @@
---
title: File Metadata Microservice
---
## File Metadata Microservice
# File Metadata Microservice
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/apis-and-microservices/apis-and-microservices-projects/file-metadata-microservice/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.

View File

@ -1,7 +1,7 @@
---
title: APIs and Microservices Projects
---
## APIs and Microservices Projects
# APIs and Microservices Projects
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/mathematics/quadratic-equations/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.

View File

@ -1,7 +1,7 @@
---
title: Request Header Parser Microservice
---
## Request Header Parser Microservice
# Request Header Parser Microservice
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/apis-and-microservices/apis-and-microservices-projects/request-header-parser-microservice/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.

View File

@ -2,13 +2,10 @@
title: Timestamp Microservice
---
## Timestamp Microservice
# Timestamp Microservice
---
![:triangular_flag_on_post:](https://forum.freecodecamp.com/images/emoji/emoji_one/triangular_flag_on_post.png?v=3 ':triangular_flag_on_post:') Remember to use <a>**`Read-Search-Ask`**</a> if you get stuck. Try to pair program ![:busts_in_silhouette:](https://forum.freecodecamp.com/images/emoji/emoji_one/busts_in_silhouette.png?v=3 ':busts_in_silhouette:') and write your own code ![:pencil:](https://forum.freecodecamp.com/images/emoji/emoji_one/pencil.png?v=3 ':pencil:')
### ![:checkered_flag:](https://forum.freecodecamp.com/images/emoji/emoji_one/checkered_flag.png?v=3 ':checkered_flag:') Problem Explanation:
## Problem Explanation
- You need to write a microservice that will return a JSON with the date in Unix format and in a human-readable date format. The JSON format is like the example output, "{"unix":1451001600000, "utc":"Fri, 25 Dec 2015 00:00:00 GMT"}".
- The response depends on the URL. If the API endpoint is hit with no additional information, it returns the JSON with the current time.
@ -20,38 +17,37 @@ title: Timestamp Microservice
- [Date at MDN:](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date)
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ':speech_balloon:') Hint: 1
---
## Hints
## Hint: 1
You will need to create the '/api/timestamp/' endpoint separately from the endpoint that reads the date to be parsed from the URL. You won't need a conditional to deal with this endpoint.
> _try to solve the problem now_
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ':speech_balloon:') Hint: 2
## Hint: 2
Date.valueOf() and Date.toUTCString() will generate the correct strings for unix: and utc:. No need to import the Moment library!
> _try to solve the problem now_
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ':speech_balloon:') Hint: 3
## Hint: 3
The Javascript Date object checks for dates that are invalid dates under ISO-8601. Use a Javascript REPL or a short Node script to try it out. [Here is a free online service that lets you test some JS code.:]https://repl.it/site/languages/javascript
> _try to solve the problem now_
## Spoiler Alert!
![warning sign](https://discourse-user-assets.s3.amazonaws.com/original/2X/2/2d6c412a50797771301e7ceabd554cef4edcd74d.gif)
---
## Solutions
**Solution ahead!**
## ![:beginner:](https://forum.freecodecamp.com/images/emoji/emoji_one/beginner.png?v=3 ':beginner:') Basic Code Solution:
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```javascript
app.get('/api/timestamp/', (req, res) => {
app.get("/api/timestamp/", (req, res) => {
res.json({ unix: Date.now(), utc: Date() });
});
app.get('/api/timestamp/:date_string', (req, res) => {
app.get("/api/timestamp/:date_string", (req, res) => {
let dateString = req.params.date_string;
//A 4 digit number is a valid ISO-8601 for the beginning of that year
@ -64,15 +60,15 @@ app.get('/api/timestamp/:date_string', (req, res) => {
let dateObject = new Date(dateString);
if (dateObject.toString() === 'Invalid Date') {
res.json({ error: 'Invaid Date' });
if (dateObject.toString() === "Invalid Date") {
res.json({ error: "Invaid Date" });
} else {
res.json({ unix: dateObject.valueOf(), utc: dateObject.toUTCString() });
}
});
```
### Code Explanation:
#### Code Explanation
- This is a pretty straightforward application of the lessons, Basic Node and Express - Serve JSON on a Specific Route
and Basic Node and Express - Get Route Parameter Input from the Client. The added wrinkle is the use of Javascript's native Date object.
@ -81,9 +77,4 @@ app.get('/api/timestamp/:date_string', (req, res) => {
That's it. There is no intermediate or advanced solution yet. If you have a better, more elegant solution, help us all out and contribute them!
## ![:clipboard:](https://forum.freecodecamp.com/images/emoji/emoji_one/clipboard.png?v=3 ':clipboard:') NOTE TO CONTRIBUTORS:
- ![:warning:](https://forum.freecodecamp.com/images/emoji/emoji_one/warning.png?v=3 ':warning:') **DO NOT** add solutions that are similar to any existing solutions. If you think it is **_similar but better_**, then try to merge (or replace) the existing similar solution.
- Add an explanation of your solution.
- Categorize the solution in one of the following categories -- **Basic**, **Intermediate** and **Advanced**. ![:traffic_light:](https://forum.freecodecamp.com/images/emoji/emoji_one/traffic_light.png?v=3 ':traffic_light:')
</details>

View File

@ -1,11 +1,19 @@
---
title: URL Shortener Microservice
---
## URL Shortener Microservice
# URL Shortener Microservice
---
## Problem Explanation
The core features to complete this exercise are the creation and retrieval of URLs from the Database.
## Creating Short URL
---
## Hints
### Hint 1
Creating Short URL
- Connect to your database instance.
> **Note**: It's important to check your Mongoose connection status before dive into the problem, just to check if everything is okay with your database configuration. This should help: `mongoose.connection.readyState`
- Receive a POST request containing an URL to be saved on Database.
@ -16,11 +24,10 @@ The core features to complete this exercise are the creation and retrieval of UR
- There is a bunch of samples over the internet how to generate some kind of identifier, try to explore it or create your own.
- An example of how this should look like: `{'url': www.freecodecamp.org, 'hash': 'ef49fa8b4'}`
## Retrieving Short URL
### Hint 2
Retrieving Short URL
- Receive a GET request containing an identifier used to find a stored URL.
- Try to find one URL saved for this identifier
- Redirect user to URL.
> **Note**: The `res.redirect(url)` function need that the given url, has a defined protocol (http://, https://), or it will just concatenate it as an extension of your current domain. eg: Good URL: `https://www.freecodecamp.org`, Bad URL: `www.freecodecamp.org`. Try it out.
- Remember to handle error situations with proper response like, `res.json({"error":"invalid URL"});
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->

View File

@ -1,41 +1,61 @@
---
title: Chain Middleware to Create a Time Server
---
## Chain Middleware to Create a Time Server
# Chain Middleware to Create a Time Server
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
---
## Problem Explanation
Similar to the last challenge, but now we are chaining 2 functions together. It seems complicated, but it's just JavaScript.
### Hint
---
## Hints
### Hint 1
Instead of responding with the time we can also add any arbitrary property to the request object and pass it to the next function by calling the `next()` method. This is trivial, but it makes for a decent example. The code will looks like this:
```javascript
app.get("/now", (req, res, next) => {
// adding a new property to req object
// in the middleware function
req.string = "example";
next();
}, (req, res) => {
// accessing the newly added property
// in the main function
res.send(req.string);
});
app.get(
"/now",
(req, res, next) => {
// adding a new property to req object
// in the middleware function
req.string = "example";
next();
},
(req, res) => {
// accessing the newly added property
// in the main function
res.send(req.string);
}
);
```
### Solution
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```javascript
app.get("/now", (req, res, next) => {
req.time = new Date().toString();
next();
}, (req, res) => {
res.send({
time: req.time
});
});
app.get(
"/now",
(req, res, next) => {
req.time = new Date().toString();
next();
},
(req, res) => {
res.send({
time: req.time
});
}
);
```
</details>
<details><summary>Solution 2 (Click to Show/Hide)</summary>
You can also declare the middleware beforehand to use in multiple routes as shown below:
@ -51,3 +71,5 @@ app.get("/now", middleware, (req, res) => {
});
});
```
</details>

View File

@ -1,31 +1,35 @@
---
title: Get Data from POST Requests
---
## Get Data from POST Requests
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
# Get Data from POST Requests
---
## Problem Explanation
Just like using req.query we can do req.body to get our data. This challenge is very similar to "Get Query Parameter Input from the Client."
In order to get data from a post request a general format is:
## Hint
---
## Hints
### Hint 1
```javascript
app.post(PATH, function(req, res) {
// Handle the data in the request
});
```
## Solution
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```javascript
app.post('/name', function(req, res) {
app.post("/name", function(req, res) {
// Handle the data in the request
var string = req.body.first+ ' '+req.body.last;
res.json({"name": string});
var string = req.body.first + " " + req.body.last;
res.json({ name: string });
});
```
<a href='https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/apis-and-microservices/basic-node-and-express/use-body-parser-to-parse-post-requests/index.md' target='_blank' rel='nofollow'>Help our community expand these hints and guides</a>.
</details>

View File

@ -1,13 +1,18 @@
---
title: Get Query Parameter Input from the Client
---
## Get Query Parameter Input from the Client
# Get Query Parameter Input from the Client
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
---
## Problem Explanation
Given the endpoint URL, `/name?first=firstname&last=lastname`, we can extract the query parameters (`first` and `last`) and their corresponding values from the `req.query` object and send a custom JSON response containing values derived from the query parameters to the client.
### Solution
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```javascript
app.get("/name", function(req, res) {
@ -21,3 +26,4 @@ app.get("/name", function(req, res) {
});
});
```
</details>

View File

@ -1,13 +1,17 @@
---
title: Get Route Parameter Input from the Client
---
## Get Route Parameter Input from the Client
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
# Get Route Parameter Input from the Client
---
## Problem Explanation
If someone tells you to build a GET or POST endpoint you would achieve the same using `app.get(...)` or `app.post(...)` accordingly.
## Hint
---
## Hints
## Hint #1
In order to get route parameters from a POST request, the general format is as follows:
@ -23,7 +27,11 @@ app.post("/:param1/:param2", (req, res) => {
});
```
## Solution
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```javascript
app.get("/:word/echo", (req, res) => {
@ -33,3 +41,4 @@ app.get("/:word/echo", (req, res) => {
});
});
```
</details>

View File

@ -1,12 +1,19 @@
---
title: Implement a Root-Level Request Logger Middleware
---
## Implement a Root-Level Request Logger Middleware
# Implement a Root-Level Request Logger Middleware
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
---
## Problem Explanation
It is easier to write this challenge all at the top (there is already a stub for it). This is because middleware must be placed the function calls you want it to be used for.
---
## Hints
### Hint 1
To set up your own middleware you can do it like so:
```javascript
@ -15,14 +22,13 @@ app.use(function middleware(req, res, next) {
// Call the next function in line:
next();
});
```
If you have trouble formatting the string correctly, one way to do it looks like:
```javascript
var string = req.method + ' ' + req.path + ' - ' + req.ip;
var string = req.method + " " + req.path + " - " + req.ip;
```
### Resources
#### Relevant Links
- [Express Middleware](https://expressjs.com/en/guide/using-middleware.html)

View File

@ -1,7 +1,7 @@
---
title: Basic Node and Express
---
## Basic Node and Express
# Basic Node and Express
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/mathematics/quadratic-equations/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.

View File

@ -1,21 +1,20 @@
---
title: Meet the Node console
---
## Meet the Node console
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
# Meet the Node console
---
## Problem Explanation
Make sure you have cloned the correct repository/glitch project and are writing your code in myapp.js.
There are many methods available from the node console. You can find a list of these methods with Node.js documentation
<a href='https://nodejs.org/dist/latest-v10.x/docs/api/console.html' target='_blank' rel='nofollow'>here</a>. A common use would be to log errors such as:
```javascript
console.log("An error happened");
console.log("An error happened");
```
### If you use Glitch
**Note:** If you use Glitch
- Glitch had changed the 'Logs' button to 'Status' button, still on the top-left, under the app name
- Don't submit the 'Edit' page directly. Click the 'Show' button (on top) and submit the application show page's url (url format is like https://appname.glitch.me/)

View File

@ -1,18 +1,18 @@
---
title: Serve an HTML File
---
## Serve an HTML File
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
# Serve an HTML File
---
## Problem Explanation
You probably need to comment out the last challenge. If you have a website and want to serve an index.html file you probably want to put this in a public folder. This is to ensure the public doesn't see something you dont want them to, and it sometimes is called "public" or "views," but you can technically call it whatever you want.
To serve an index.html in a folder called "public" at the root domain you would do so like this:
```javascript
app.get("/", function(req, res) {
res.sendFile( __dirname + "/public/index.html");
});
app.get("/", function(req, res) {
res.sendFile(__dirname + "/public/index.html");
});
```
Note: __dirname returns the root directory is a best practice for node developers.
**Note:** __dirname returns the root directory is a best practice for node developers.

View File

@ -1,16 +1,17 @@
---
title: Serve JSON on a Specific Route
---
## Serve JSON on a Specific Route
# Serve JSON on a Specific Route
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
---
## Problem Explanation
It is rather simple to serve a JSON object with Node (at the `/json` route), if we want to deliver an object containing a key `message` and with the value `"Hello json"` we can do so as indicated:
```javascript
app.get("/json", (req, res) => {
res.json({
"message": "Hello json"
});
res.json({
message: "Hello json"
});
});
```

View File

@ -1,10 +1,10 @@
---
title: Serve Static Assets
---
## Serve Static Assets
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
# Serve Static Assets
---
## Problem Explanation
Serving static webpages and assets is fairly simple with `express`. This could be useful for building your own portfolio website or blog, single-page web applications etc.
To serve static assets from the `public` folder in the you can use the `express.static()` method as the middleware. This method takes the endpoint and the absolute path to the directory containing the static assets as arguments and exposes the files in that folder at the given endpoint. By default, if the endpoint is not passed to the method, the folder is exposed at the root endpoint i.e. `/` for the application.

View File

@ -1,9 +1,13 @@
---
title: Start a Working Express Server
---
## Start a Working Express Server
# Start a Working Express Server
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
---
## Hints
### Hint 1
If you had a website at "example.com/" and wanted to serve a string such as "Hello Express" to whoever visits the root domain you could do so easily using Node and/or express:

View File

@ -1,16 +1,16 @@
---
title: Use body-parser to Parse POST Requests
---
## Use body-parser to Parse POST Requests
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
# Use body-parser to Parse POST Requests
---
## Problem Explanation
The body-parser should already be added to your project if you used the provided boilerplate, but if not it should be there as:
```json
"dependencies": {
"body-parser": "^1.19.0",
...
"express": "^4.17.1"
}
```
@ -22,7 +22,7 @@ This guide assumes you have imported the `body-parser` module into your file as
In order to import the same, you just need to add the following line at the top of your file:
```javascript
var bodyParser = require('body-parser');
var bodyParser = require("body-parser");
```
All you need to do for this challenge is pass the middleware to `app.use()`. Make sure it comes before the paths it needs to be used on. Remember that body-parser returns with `bodyParser.urlencoded({extended: false})`. Use the following as a template:

View File

@ -1,24 +1,22 @@
---
title: Use the .env File
---
## Use the .env File
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
# Use the .env File
---
## Problem Explanation
We can use the .toUpperCase() method to make a string all caps, such as:
```javascript
var response = "Hello World".toUpperCase(); // now becomes "HELLO WORLD"
var response = "Hello World".toUpperCase(); // now becomes "HELLO WORLD"
```
All we need to do now is check what the value of the environment variable is, which you can do like:
```javascript
if (process.env.VAR_NAME === "allCaps") {
response = "Hello World".toUpperCase();
} else {
response = "Hello World";
}
});
if (process.env.VAR_NAME === "allCaps") {
response = "Hello World".toUpperCase();
} else {
response = "Hello World";
}
```

View File

@ -1,7 +1,7 @@
---
title: APIs and Microservices
---
## APIs and Microservices
# APIs and Microservices
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/mathematics/quadratic-equations/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.

View File

@ -1,7 +1,15 @@
---
title: Add a Description to Your package.json
---
## Add a Description to Your package.json
# Add a Description to Your package.json
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
To complete the challenge follow the below steps:
* Go to the link given in the curriculum starting intro page.
![freecodecamp apis-and-microservices intro](https://user-images.githubusercontent.com/15084301/45616545-65732480-ba8d-11e8-9893-412ff6c68be5.png)
@ -12,3 +20,5 @@ To complete the challenge follow the below steps:
![Glitch public project link](https://user-images.githubusercontent.com/15084301/45616579-8176c600-ba8d-11e8-8a46-4ac930578e74.png)
* Submit the link in the solution and that's it.
![sucess page](https://user-images.githubusercontent.com/15084301/45616757-019d2b80-ba8e-11e8-8b5b-98dc6d02c235.png)
</details>

View File

@ -1,13 +1,15 @@
---
title: Add a License to Your package.json
---
## Add a License to Your package.json
# Add a License to Your package.json
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
---
## Hints
### Hint 1
You should go over to the `package.json` file in your project. Licenses follow a similar convention as this:
```json
"license": "ExampleLicense"
```
<a href='https://github.com/freeCodeCamp/freeCodeCamp/blob/master/guide/english/certifications/apis-and-microservices/managing-packages-with-npm/add-a-license-to-your-package.json/index.md' target='_blank' rel='nofollow'>Help our community expand these hints and guides</a>.

View File

@ -1,9 +1,13 @@
---
title: Add a Version to Your package.json
---
## Add a Version to Your package.json
# Add a Version to Your package.json
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
---
## Hints
### Hint 1
You should go over to the package.json file in your project. Versions follow a similar convention as this:
```json

View File

@ -1,7 +1,11 @@
---
title: Add Keywords to Your package.json
---
## Add Keywords to Your package.json
# Add Keywords to Your package.json
---
## Hints
## Hint 1
* Your package.json should contain the property `keywords`.
@ -12,7 +16,14 @@ title: Add Keywords to Your package.json
## Hint 3
* One of the values in `keywords` should be `freecodecamp`.
## Solution:
```js
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```json
"keywords": [ "freecodecamp", "microservice", "guide" ]
```
</details>

View File

@ -1,9 +1,10 @@
---
title: Expand Your Project with External Packages from npm
---
## Expand Your Project with External Packages from npm
# Expand Your Project with External Packages from npm
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
---
## Problem Explanation
The `package.json` file in the root directory of your project, among other things, lists all the dependencies that your project needs in order to work, are listed under the `dependencies` key in that file and follow a similar convention as given below:

View File

@ -1,8 +1,10 @@
---
title: How to Use package.json, the Core of Any Node.js Project or npm Package
---
## How to Use package.json, the Core of Any Node.js Project or npm Package
# How to Use package.json, the Core of Any Node.js Project or npm Package
---
## Problem Explanation
According to [this issue discussed on freeCodeCamp's git repo](https://github.com/freeCodeCamp/freeCodeCamp/issues/34798), the bootstrapped glitch project in the [introduction](https://learn.freecodecamp.org/apis-and-microservices/managing-packages-with-npm/) will NOT work if you're not logged in on glitch.
Here's how to set up a new node/express project anonymously:
@ -24,9 +26,13 @@ Remember, you're writing JSON, so make sure you use
2. `"key": value` format
3. the correct number of commas
SPOILER ALERT. DO NOT SCROLL DOWN IF YOU WISH TO KEEP TRYING
```json
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```json
{
"name": "fcc-learn-npm-package-json",
"author": "foobar",
@ -45,4 +51,6 @@ SPOILER ALERT. DO NOT SCROLL DOWN IF YOU WISH TO KEEP TRYING
"url": "https://idontknow/todo.git"
}
}
```
```
</details>

View File

@ -1,7 +1,7 @@
---
title: Managing Packages with NPM
---
## Managing Packages with NPM
# Managing Packages with NPM
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
NPM stands for Node Package Manager. It is a Package Manager bundled with Node.js. A Package bundles code in a manner that makes it easy to plugin or install the application or software contained within the package. There are many package managers, such as APT, Yarn, and NPM, that perform operations related to installing and configuring software packages to work on the system that the package manager is installed on. NPM is vital to Node, as it allows for easy management of Middleware such as Express.

View File

@ -1,9 +1,13 @@
---
title: Manage npm Dependencies By Understanding Semantic Versioning
---
## Manage npm Dependencies By Understanding Semantic Versioning
# Manage npm Dependencies By Understanding Semantic Versioning
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
---
## Hints
### Hint 1
You should go over to the `package.json` file in your project. SemVer dependencies follow a similar convention like this:
```json
@ -13,4 +17,3 @@ You should go over to the `package.json` file in your project. SemVer dependenci
...
```
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/apis-and-microservices/managing-packages-with-npm/manage-npm-dependencies-by-understanding-semantic-versioning/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.

View File

@ -1,9 +1,13 @@
---
title: Remove a Package from Your Dependencies
---
## Remove a Package from Your Dependencies
# Remove a Package from Your Dependencies
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
---
## Hints
### Hint 1
You should go over to the `package.json` file in your project. Removing a package is as simple as going into your dependencies section and removing the line with the corresponding item. In the following example "express" is removed from `package.json`:
Before
@ -19,5 +23,4 @@ After
"dependencies": {
"express": "^4.16.4",
},
```
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/apis-and-microservices/managing-packages-with-npm/remove-a-package-from-your-dependencies/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.
```

View File

@ -1,7 +1,11 @@
---
title: Use the Caret-Character to Use the Latest Minor Version of a Dependency
---
## Use the Caret-Character to Use the Latest Minor Version of a Dependency
# Use the Caret-Character to Use the Latest Minor Version of a Dependency
---
## Hints
## Hint 1
* the package `moment` should be in your package.json, specifically in the
@ -10,9 +14,15 @@ dependencies property.
## Hint 2
* `moment` version should have a caret character within it.
## Solution:
```js
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```json
"dependencies": {
"moment": "^2.10.2"
}
```
</details>

View File

@ -1,7 +1,7 @@
---
title: Use the Tilde-Character to Always Use the Latest Patch Version of a Dependency
---
## Use the Tilde-Character to Always Use the Latest Patch Version of a Dependency
# Use the Tilde-Character to Always Use the Latest Patch Version of a Dependency
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/apis-and-microservices/managing-packages-with-npm/use-the-tilde-character-to-always-use-the-latest-patch-version-of-a-dependency/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.

View File

@ -1,55 +1,67 @@
---
title: Chain Search Query Helpers to Narrow Search Results
---
## Chain Search Query Helpers to Narrow Search Results
# Chain Search Query Helpers to Narrow Search Results
1. To create but not execute a find query
```javascript
Model.find( {name: 'Leah'} )
```
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
2. To store the find query into a variable for later use:
```javascript
var findQuery = YourModel.find( {name: 'Leah'} )
```
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
---
## Hints
3. To sort an array:<br>
### Hint 1
To create but not execute a find query
```javascript
yourArray.sort( {age: 1} ) // Here: 1 for ascending order and -1 for descending order.
Model.find({ name: "Leah" });
```
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
4. To limit an array's size:
```javascript
yourArray.limit(5) // return array which has 5 items in it.
```
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
5. To hide certain property from the result:
### Hint 2
To store the find query into a variable for later use:
```javascript
yourArray.select( {name: 0, age: 1} ) // Here: 0 means false and thus hide name property; 1 means true so age property will show.
var findQuery = YourModel.find({ name: "Leah" });
```
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
6. To execute this query, you can either:</br>
&nbsp;&nbsp;1) Callback:
### Hint 3
To sort an array:<br>
```javascript
yourArray.sort({ age: 1 }); // Here: 1 for ascending order and -1 for descending order.
```
### Hint 4
To limit an array's size:
```javascript
yourArray.limit(5); // return array which has 5 items in it.
```
### Hint 5
To hide certain property from the result:
```javascript
yourArray.select({ name: 0, age: 1 }); // Here: 0 means false and thus hide name property; 1 means true so age property will show.
```
### Hint 6
To execute this query, you can either:
1. Callback:
```javascript
YourQuery.exec(function(err, docs) {
//do something here
})
//do something here
});
```
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Or 2) Promise
### Hint 7
Or
2. Promise
```javascript
YourQuery.exec.then(function(err, docs) {
//do something here
})
//do something here
});
```
7. Chain it all together:
### Hint 8
Chain it all together:
```javascript
Person.find({age: 55}).sort({name: -1}).limit(5).select( {favoriteFoods: 0} ).exec(function(error, people) {
//do something here
})
Person.find({ age: 55 })
.sort({ name: -1 })
.limit(5)
.select({ favoriteFoods: 0 })
.exec(function(error, people) {
//do something here
});
```

View File

@ -2,40 +2,47 @@
title: Create a Model
---
# Create a Model
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
There are 3 things to do in this challenge. You can click each item to see the code.
<details>
<summary>Assign Mongoose Schema to a variable. This is not necessary but will make your code easier to read.</summary>
**Assign Mongoose Schema to a variable**
This is not necessary but will make your code easier to read.
```javascript
const Schema = mongoose.Schema;
```
</details>
See the [Mongoose docs](https://mongoosejs.com/docs/guide.html) first where is a lot of useful stuff.
When you are building schema you can use either of three options for name validation
```js
```
name: String
name: {type: String}
name: {type: String, required: true} //preferred
```
<details>
<summary>Create Person schema.</summary>
**Create Person schema.**
```javascript
const personSchema = new Schema({
name: { type: String, required: true },
age: Number,
favoriteFoods: [String]
favoriteFoods: [String]
});
```
**Note**: If you choose to skip the first step, you have to use `mongoose.Schema` instead of `Schema`.
</details>
<details>
<summary>Create Person model from the schema.</summary>
**Create Person model from the schema.**
```javascript
const Person = mongoose.model('Person', personSchema);
const Person = mongoose.model("Person", personSchema);
```
</details>

View File

@ -3,9 +3,11 @@ title: Create and Save a Record of a Model
---
# Create and Save a Record of a Model
---
## Hints
### Hint #1
### Hint 1
You need to do the following:
1. Create a model of a person, using the schema from exercise 2
@ -13,9 +15,11 @@ You need to do the following:
3. Save the new person you created
4. Put your new person inside the `createAndSavePerson` function
---
## Solutions
<details><summary>Solution #1 (Click to Show/Hide)</summary>
<details><summary>Solution 1 (Click to Show/Hide)</summary>
Code for `myApp.js`

View File

@ -3,23 +3,27 @@ title: Create Many Records with model.create()
---
# Create Many Records with model.create()
---
## Hints
### Hint #1
### Hint 1
Create an array of objects. Each object has a name, age and an array of favorite foods. Use the variable name `arrayOfPeople`.
### Hint #2
### Hint 2
Create your many records (ie. create your people) inside the callback for `createManyPeople`.
### Hint #3
### Hint 3
Use `Model.create()` to create many records. You should replace `Model` with the name of the model you defined in the previous section. Most likely you called your model `Person`.
### Hint #4
### Hint 4
The `Model.create` function requires a callback, similar to the `person.save` function you used in the previous section.
---
## Solutions
<details><summary>Solution #1 (Click to Show/Hide)</summary>
<details><summary>Solution 1 (Click to Show/Hide)</summary>
Code for `myApp.js`

View File

@ -1,7 +1,7 @@
---
title: Delete Many Documents with model.remove()
---
## Delete Many Documents with model.remove()
# Delete Many Documents with model.remove()
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/apis-and-microservices/mongodb-and-mongoose/delete-many-documents-with-model.remove/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.

View File

@ -1,7 +1,7 @@
---
title: Delete One Document Using model.findByIdAndRemove
---
## Delete One Document Using model.findByIdAndRemove
# Delete One Document Using model.findByIdAndRemove
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/apis-and-microservices/mongodb-and-mongoose/delete-one-document-using-model.findbyidandremove/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.

View File

@ -1,7 +1,7 @@
---
title: MongoDB and Mongoose
---
## MongoDB and Mongoose
# MongoDB and Mongoose
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/mathematics/quadratic-equations/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.

View File

@ -3,6 +3,8 @@ title: Install and Set Up Mongoose
---
# Install and Set Up Mongoose
---
## Problem Explanation
You might want to check both the [MongoDB](https://www.npmjs.com/package/mongodb) and the [Mongoose](https://www.npmjs.com/package/mongoose) NPM Repositories for the manual configuration if you are not using Giltch.
OR
@ -10,11 +12,13 @@ OR
1. You can use the glitch feature of search packages, install them and update package.json all by itself. (You should use fresh Glitch project from the url given in MongoDb and Mongoose first intro page).
2. Once done add the MONGO_URL in .env file and save your path as
```` mongodb://<dbuser>:<dbpassword>@ds<PORT>.mlab.com:<PORT>/<DATABASE-NAME> ```` which you copy from mLab. Remember to remove the angle brackets ````< >```` when you replace your username and password of your database.
``` mongodb://<dbuser>:<dbpassword>@ds<PORT>.mlab.com:<PORT>/<DATABASE-NAME> ```` which you copy from mLab. Remember to remove the angle brackets ````< >```` when you replace your username and password of your database.
---
## Hints
### Hint #1
### Hint 1
**Timeout error**
If the tests are timing out, check the `package.json` file. Ensure the final dependency does not end in a `,`.
@ -27,7 +31,7 @@ For example, this will result in a timeout error:
},
```
### Hint #2
### Hint 2
**add MONGO_URI to .env**
* Insert a line that looks similar to: `MONGO_URI=mongodb+srv://<username>:<password>@<clustername>-vlas9.mongodb.net/test?retryWrites=true`. `<username>` and `<clustername>` will be automatically generated by MongoDB.
@ -40,9 +44,11 @@ Still having issues? Check the below hints:
* Do you have symbols or special characters in your password, e.g. `$&(@`? If so, you will need to translate these into unicode. MongoDB has instructions on how to do this. I would suggest changing your password to be lettes and numbers only for simplicity.
---
## Solutions
<details><summary>Solution #1 (Click to Show/Hide)</summary>
<details><summary>Solution 1 (Click to Show/Hide)</summary>
**.env**

View File

@ -1,7 +1,7 @@
---
title: Perform Classic Updates by Running Find, Edit, then Save
---
## Perform Classic Updates by Running Find, Edit, then Save
# Perform Classic Updates by Running Find, Edit, then Save
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/apis-and-microservices/mongodb-and-mongoose/perform-classic-updates-by-running-find-edit-then-save/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.

View File

@ -1,7 +1,7 @@
---
title: Perform New Updates on a Document Using model.findOneAndUpdate()
---
## Perform New Updates on a Document Using model.findOneAndUpdate()
# Perform New Updates on a Document Using model.findOneAndUpdate()
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/apis-and-microservices/mongodb-and-mongoose/perform-new-updates-on-a-document-using-model.findoneandupdate/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.

View File

@ -3,17 +3,21 @@ title: Use model.find() to Search Your Database
---
# Use model.find() to Search Your Database
---
## Hints
### Hint #1
### Hint 1
Replace `Model` with the name of your model from the previous sections. Most likely this is `Person`.
### Hint #2
### Hint 2
Use `{name: personName}` for the first argument in `Model.find()`.
---
## Solutions
<details><summary>Solution #1 (Click to Show/Hide)</summary>
<details><summary>Solution 1 (Click to Show/Hide)</summary>
Code for `myApp.js`

View File

@ -3,9 +3,11 @@ title: Use model.findById() to Search Your Database By _id
---
# Use model.findById() to Search Your Database By _id
---
## Solutions
<details><summary>Solution #1 (Click to Show/Hide)</summary>
<details><summary>Solution 1 (Click to Show/Hide)</summary>
Code for `myApp.js`

View File

@ -3,9 +3,11 @@ title: Use model.findOne() to Return a Single Matching Document from Your Databa
---
# Use model.findOne() to Return a Single Matching Document from Your Database
---
## Solutions
<details><summary>Solution #1 (Click to Show/Hide)</summary>
<details><summary>Solution 1 (Click to Show/Hide)</summary>
Code for `myApp.js`

View File

@ -2,36 +2,35 @@
title: Find the Symmetric Difference
---
![:triangular_flag_on_post:](https://forum.freecodecamp.com/images/emoji/emoji_one/triangular_flag_on_post.png?v=3 ":triangular_flag_on_post:") Remember to use <a href="https://forum.freecodecamp.org/t/how-to-get-help-when-you-are-stuck/" rel="help">**`Read-Search-Ask`**</a> if you get stuck. Try to pair program![:busts_in_silhouette:](https://forum.freecodecamp.com/images/emoji/emoji_one/busts_in_silhouette.png?v=3 ":busts_in_silhouette:") and write your own code![:pencil:](https://forum.freecodecamp.com/images/emoji/emoji_one/pencil.png?v=3 ":pencil:")
### ![:checkered_flag:](https://forum.freecodecamp.com/images/emoji/emoji_one/checkered_flag.png?v=3 ":checkered_flag:") Problem Explanation: ###
# Find the Symmetric Difference
---
## Problem Explanation
Symmetric difference (commonly denoted by &Delta;) of two sets is the set of elements which are in either of the two sets, but not in both.
For example, `sym([1, 2, 3], [5, 2, 1, 4])` should yield `[3, 4, 5]`.
Following above definition, symmetric difference of three sets *A*, *B*, and *C* can be expressed as `(A &Delta; B) &Delta; C`.
#### Relevant Links ####
#### Relevant Links
* [Symmetric difference - Wikipedia](https://en.wikipedia.org/wiki/Symmetric_difference)
* [Symmetric difference - YouTube](https://www.youtube.com/watch?v=PxffSUQRkG4)
* [Array.reduce()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce)
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 1 ##
---
## Hints
### Hint 1
The *arguments* object is *Array*-like object that only inherits `Array.length` property. Hence consider converting it to an actual *Array*.
> _try to solve the problem now_
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 2 ##
### Hint 2
Deem writing a helper function that returns the symmetric difference of two arrays on each call instead of attempting to difference all sets simultaneously.
> _try to solve the problem now_
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 3 ##
### Hint 3
Apply helper function against the created arguments array reducing its elements pairwise recursively to form the expected output.
**Note**
@ -44,103 +43,95 @@ In the event of *odd number of sets* the symmetric difference will include ident
(A &Intersection; B) &Intersection; C = {1, 4} &Intersection {3, 4, 5}
A &Intersection; B = {1, 3, 5}
> _try to solve the problem now_
## Spoiler Alert! ##
---
## Solutions
![:warning:](//discourse-user-assets.s3.amazonaws.com/original/2X/2/2d6c412a50797771301e7ceabd554cef4edcd74d.gif ":warning:")
**Solution Ahead!**
## ![:beginner:](https://forum.freecodecamp.com/images/emoji/emoji_one/beginner.png?v=3 ":beginner:") Basic Code Solution: ##
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```javascript
function sym() {
var args = [];
for (var i = 0; i < arguments.length; i++) {
args.push(arguments[i]);
function sym() {
var args = [];
for (var i = 0; i < arguments.length; i++) {
args.push(arguments[i]);
}
function symDiff(arrayOne, arrayTwo) {
var result = [];
arrayOne.forEach(function(item) {
if (arrayTwo.indexOf(item) < 0 && result.indexOf(item) < 0) {
result.push(item);
}
});
function symDiff(arrayOne, arrayTwo) {
var result = [];
arrayOne.forEach(function(item) {
if (arrayTwo.indexOf(item) < 0 && result.indexOf(item) < 0) {
result.push(item);
}
});
arrayTwo.forEach(function(item) {
if (arrayOne.indexOf(item) < 0 && result.indexOf(item) < 0) {
result.push(item);
}
});
return result;
arrayTwo.forEach(function(item) {
if (arrayOne.indexOf(item) < 0 && result.indexOf(item) < 0) {
result.push(item);
}
});
// Apply reduce method to args array, using the symDiff function
return args.reduce(symDiff);
}
return result;
}
// Apply reduce method to args array, using the symDiff function
return args.reduce(symDiff);
}
```
### Code Explanation: ###
#### Code Explanation
* `push()` is used to break down the *arguments* object to an array, *args*.
* The `symDiff` function finds the symmetric difference between two sets. It is used as a callback function for the `reduce()` method called on *args*.
* `arrayOne.forEach()` pushes the elements to *result* which are present only in *arrayOne* as well as not already a part of *result*.
* `arrayTwo.forEach()` pushes the elements to *result* which are present only in *arrayTwo* as well as not already a part of *result*.
* The *result*, which is the symmetric difference is returned. This solution works for any number of sets.
#### Relevant Links ####
#### Relevant Links
* [Statement for](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/statements/for)
* [Array.length](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/length)
* [Array.push()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push)
* [Array.forEach()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach)
* [Array.indexOf()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf)
</details>
## ![:sunflower:](https://forum.freecodecamp.com/images/emoji/emoji_one/sunflower.png?v=3 ":sunflower:") Intermediate Code Solution: ##
<details><summary>Solution 2 (Click to Show/Hide)</summary>
```javascript
function sym() {
function sym() {
// Convert the argument object into a proper array
var args = Array.prototype.slice.call(arguments);
// Convert the argument object into a proper array
var args = Array.prototype.slice.call(arguments);
// Return the symmetric difference of 2 arrays
var getDiff = function(arr1, arr2) {
// Returns items in arr1 that don't exist in arr2
function filterFunction(arr1, arr2) {
return arr1.filter(function(item) {
return arr2.indexOf(item) === -1;
});
}
// Run filter function on each array against the other
return filterFunction(arr1, arr2)
.concat(filterFunction(arr2, arr1));
};
// Reduce all arguments getting the difference of them
var summary = args.reduce(getDiff, []);
// Run filter function to get the unique values
var unique = summary.filter(function(elem, index, self) {
return index === self.indexOf(elem);
});
return unique;
// Return the symmetric difference of 2 arrays
var getDiff = function(arr1, arr2) {
// Returns items in arr1 that don't exist in arr2
function filterFunction(arr1, arr2) {
return arr1.filter(function(item) {
return arr2.indexOf(item) === -1;
});
}
// test here
sym([1, 2, 3], [5, 2, 1, 4]);
// Run filter function on each array against the other
return filterFunction(arr1, arr2).concat(filterFunction(arr2, arr1));
};
// Reduce all arguments getting the difference of them
var summary = args.reduce(getDiff, []);
// Run filter function to get the unique values
var unique = summary.filter(function(elem, index, self) {
return index === self.indexOf(elem);
});
return unique;
}
// test here
sym([1, 2, 3], [5, 2, 1, 4]);
```
### Code Explanation: ###
#### Code Explanation
* The `slice()` method is used to break down the *arguments* object to an array, *args*.
* The `getDiff` function finds the symmetric difference between two sets, *arr1* and *arr2*. It is used as a callback function for the `reduce()` method called on *args*.
* The first `filterFunction()` returns elements in *arr1* that don't exist in *arr2*.
@ -148,41 +139,36 @@ In the event of *odd number of sets* the symmetric difference will include ident
* *summary* consists of the reduced arguments.
* `filter()` is used on *summary* to keep only the unique values and *unique* is returned.
#### Relevant Links ####
#### Relevant Links
* [Array.slice()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice)
* [Array.filter()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter)
* [Array.concat()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat)
</details>
## ![:rotating_light:](https://forum.freecodecamp.com/images/emoji/emoji_one/rotating_light.png?v=3 ":rotating_light:") Advanced Code Solution: ##
<details><summary>Solution 3 (Click to Show/Hide)</summary>
```javascript
const diff = (arr1, arr2) => (
[
...arr1.filter(e => !arr2.includes(e)),
...arr2.filter(e => !arr1.includes(e)),
]
);
const diff = (arr1, arr2) => [
...arr1.filter(e => !arr2.includes(e)),
...arr2.filter(e => !arr1.includes(e))
];
const sym = (...args) => [...new Set(args.reduce(diff))];
const sym = (...args) => [...new Set(args.reduce(diff))];
// test here
sym([1, 2, 3], [5, 2, 1, 4]);
// test here
sym([1, 2, 3], [5, 2, 1, 4]);
```
### Code Explanation: ###
#### Code Explanation
* The main function *sym()* reduces given arrays utilising helper function *diff()* to a single array. Also, it temporary converts the result to *Set* to remove duplicates.
* The function *diff()* returns the symmetric difference of two arrays by picking out elements in parameterised arrays; *arr1* and *arr2*.
#### Relevant Links ####
#### Relevant Links
* [Set](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set)
* [Array.filter()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter)
## ![:clipboard:](https://forum.freecodecamp.com/images/emoji/emoji_one/clipboard.png?v=3 ":clipboard:") NOTES FOR CONTRIBUTIONS: ##
* ![:warning:](https://forum.freecodecamp.com/images/emoji/emoji_one/warning.png?v=3 ":warning:") **DO NOT** add solutions that are similar to any existing solutions. If you think it is **_similar but better_**, then try to merge (or replace) the existing similar solution.
* Add an explanation of your solution.
* Categorize the solution in one of the following categories — **Basic**, **Intermediate** and **Advanced**. ![:traffic_light:](https://forum.freecodecamp.com/images/emoji/emoji_one/traffic_light.png?v=3 ":traffic_light:")
</details>

View File

@ -1,48 +1,58 @@
---
title: Implement Bubble Sort
---
## Implement Bubble Sort
# Implement Bubble Sort
### Method:
---
## Problem Explanation
- Bubble Sort is a sorting algorithm which sorts or *bubbles* the largest number as last element at the end of each pass.
- We compare each element to the one ahead of it, if the element before is smaller, we swap their places.
- Bubble Sort's time complexity is **O(n<sup>2</sup>)**.
- It's a **stable** algorithm.
- ![Bubble sort in action](https://upload.wikimedia.org/wikipedia/commons/c/c8/Bubble-sort-example-300px.gif)
### Solution:
#### Solution 1: Basic
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```js
function swap(a, b, arr){
function swap(a, b, arr) {
let tmp = arr[a];
arr[a] = arr[b];
arr[b] = tmp;
}
function bubbleSort(array) {
for (let i = 0; i < array.length; i++){
for (let j = 0; j < array.length-1-i; j++){ // -i because the largest element will be bubbled at the end so we don't have to compare.
if (array[j] > array[j+1]){
swap(j, j+1, array);
for (let i = 0; i < array.length; i++) {
for (let j = 0; j < array.length - 1 - i; j++) {
// -i because the largest element will be bubbled at the end so we don't have to compare.
if (array[j] > array[j + 1]) {
swap(j, j + 1, array);
}
}
}
return array;
}
```
#### Solution 2: Advanced
</details>
<details><summary>Solution 2 (Click to Show/Hide)</summary>
```js
function bubbleSort(array) {
for (let i = 0; i < array.length; i++){
for (let j = 0; j < array.length-1-i; j++){
if (array[j] > array[j+1]) [array[j], array[j+1]] = [array[j+1], array[j]]; // Using ES6 array destructuring to swap
for (let i = 0; i < array.length; i++) {
for (let j = 0; j < array.length - 1 - i; j++) {
if (array[j] > array[j + 1])
[array[j], array[j + 1]] = [array[j + 1], array[j]]; // Using ES6 array destructuring to swap
}
}
return array;
}
```
```
### References:
#### Relevant Links
- [GeeksForGeeks](https://www.geeksforgeeks.org/bubble-sort/)
- [Wikipedia](https://en.wikipedia.org/wiki/Bubble_sort)
- Video by [HackerRank](https://www.youtube.com/watch?v=6Gv8vg0kcHc)
</details>

View File

@ -1,9 +1,10 @@
---
title: Implement Insertion Sort
---
## Implement Insertion Sort
# Implement Insertion Sort
### Method:
---
## Problem Explanation
- Insertion Sort assumes that array is divided in two parts:
1. Sorted (Initially the first element)
2. Unsorted
@ -13,21 +14,27 @@ title: Implement Insertion Sort
- Time comlexity of Insertion sort is of **O(n<sup>2</sup>)**.
- It's a **stable** algorithm.
### Solution:
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```js
function insertionSort(array) {
for (let i = 1; i < array.length; i++){
for (let i = 1; i < array.length; i++) {
let curr = array[i];
for (var j = i-1; j >= 0 && array[j] > curr; j--){
array[j+1] = array[j];
for (var j = i - 1; j >= 0 && array[j] > curr; j--) {
array[j + 1] = array[j];
}
array[j+1] = curr;
array[j + 1] = curr;
}
return array;
}
```
### References:
#### Relevant Links
- [Wikipedia](https://en.wikipedia.org/wiki/Insertion_sort)
- [Khan Academy](https://www.youtube.com/watch?v=lCzQvQr8Utw)
</details>

View File

@ -1,9 +1,10 @@
---
title: Implement Merge Sort
---
## Implement Merge Sort
# Implement Merge Sort
### Method:
---
## Problem Explanation
- Merge Sort is a classic divide and conquer problem.
- The following steps are involved:
- Divide: We break the array from the middle using recusion until we're left with 1 element.
@ -14,19 +15,26 @@ title: Implement Merge Sort
- It's a **stable** algorithm.
- ![Merge Sort in action](https://upload.wikimedia.org/wikipedia/commons/c/cc/Merge-sort-example-300px.gif)
### Solution:
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```js
//Merger function, which merges 2 sorted array into 1 sorted array
function merger(arr1, arr2){
let i = 0, j = 0, mergedArr = [];
while (i < arr1.length && j < arr2.length){
function merger(arr1, arr2) {
let i = 0,
j = 0,
mergedArr = [];
while (i < arr1.length && j < arr2.length) {
if (arr1[i] > arr2[j]) mergedArr.push(arr2[j++]);
else mergedArr.push(arr1[i++]);
}
while (i < arr1.length){
while (i < arr1.length) {
mergedArr.push(arr1[i++]);
}
while (j < arr2.length){
while (j < arr2.length) {
mergedArr.push(arr2[j++]);
}
return mergedArr;
@ -34,17 +42,18 @@ function merger(arr1, arr2){
function mergeSort(array) {
//Array of length 1 is sorted so we return the same array back
if (array.length == 1) return array;
//Break down the array to half from middle into left and right
let middle = Math.floor(array.length/2);
let middle = Math.floor(array.length / 2);
let left = mergeSort(array.slice(0, middle));
let right = mergeSort(array.slice(middle));
let right = mergeSort(array.slice(middle));
//Return the merged sorted array
return merger(left, right);
}
```
### References:
#### Relevant Links
- [Wikipedia](https://en.wikipedia.org/wiki/Merge_sort)
- Video by [Hackerrank](https://www.youtube.com/watch?v=KF2j-9iSf4Q)
</details>

View File

@ -1,9 +1,10 @@
---
title: Implement Quick Sort
---
## Implement Quick Sort
# Implement Quick Sort
### Method:
---
## Problem Explanation
- Quick sort is an efficient sorting algorithm. It's an in-place algorithm so it doesn't take any auxilary space.
- First pick a random pivot point around which move all the smaller elements to it to the left of it and the bigger elements to the right of it.
- After getting the pivotIndex which is essentially the fixed position of that element, we find other pivotIndex by recusirvely calling this function.
@ -12,40 +13,44 @@ title: Implement Quick Sort
- It's an **unstable** algorithm.
- ![Quick sort in action](https://upload.wikimedia.org/wikipedia/commons/6/6a/Sorting_quicksort_anim.gif)
### Solution:
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```js
//Swapping array elements via ES6 array destructuring
function swap(arr, x, y){
//Swapping array elements via ES6 array destructuring
function swap(arr, x, y) {
[arr[x], arr[y]] = [arr[y], arr[x]];
}
//Pivot function returns the fixed pivot point
function pivot(arr, left = 0, right = arr.length-1){
function pivot(arr, left = 0, right = arr.length - 1) {
let shift = left;
for (let i = left+1; i <= right; i++){
for (let i = left + 1; i <= right; i++) {
//Move all the small elements on the left side
if (arr[i] < arr[left]) swap(arr, i, ++shift);
}
//Finally swapping the last element with the left
swap(arr, left, shift);
return shift;
}
function quickSort(array, left = 0, right = array.length-1) {
if (left < right){
function quickSort(array, left = 0, right = array.length - 1) {
if (left < right) {
let pivotIndex = pivot(array, left, right);
//Recusrively calling the function to the left of the pivot and to the right of the pivot
quickSort(array, left, pivotIndex-1);
quickSort(array, pivotIndex+1, right);
quickSort(array, left, pivotIndex - 1);
quickSort(array, pivotIndex + 1, right);
}
return array;
}
```
### Reference:
#### Relevant Links
- [Wikipedia](https://en.wikipedia.org/wiki/Quicksort)
- [Khan Academy](https://www.khanacademy.org/computing/computer-science/algorithms/quick-sort/a/overview-of-quicksort)
</details>

View File

@ -1,9 +1,10 @@
---
title: Implement Selection Sort
---
## Implement Selection Sort
# Implement Selection Sort
### Method:
---
## Problem Explanation
- Selection Sort is one of the easier sorting algorithm to understand and implement.
- This algorithm splits the array in two parts:
1. Sorted
@ -12,17 +13,21 @@ title: Implement Selection Sort
- Each pass, initially we assume the first element to be the smallest then we loop through the whole array and *select* the smallest element. At the end of the pass we swap smallest element to the sorted array.
- It has **O(n<sup>2</sup>)** time complexity.
### Solution:
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```js
function swap(a, b, arr){
function swap(a, b, arr) {
let tmp = arr[a];
arr[a] = arr[b];
arr[b] = tmp;
}
function selectionSort(array) {
for (let i = 0; i < array.length-1; i++){
for (let i = 0; i < array.length - 1; i++) {
let min = i;
for (let j = i+1; j < array.length; j++){
for (let j = i + 1; j < array.length; j++) {
if (array[min] > array[j]) min = j;
}
swap(i, min, array);
@ -31,6 +36,8 @@ function selectionSort(array) {
}
```
### References:
#### Relevant Links
- Read about Selection Sort at [Wikipedia](https://en.wikipedia.org/wiki/Selection_sort)
</details>

View File

@ -1,7 +1,7 @@
---
title: Algorithms
---
## Algorithms
# Algorithms
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/mathematics/quadratic-equations/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.

View File

@ -1,9 +1,11 @@
---
title: Inventory Update
---
![:triangular_flag_on_post:](https://forum.freecodecamp.com/images/emoji/emoji_one/triangular_flag_on_post.png?v=3 ":triangular_flag_on_post:") Remember to use <a>**`Read-Search-Ask`**</a> if you get stuck. Try to pair program ![:busts_in_silhouette:](https://forum.freecodecamp.com/images/emoji/emoji_one/busts_in_silhouette.png?v=3 ":busts_in_silhouette:") and write your own code ![:pencil:](https://forum.freecodecamp.com/images/emoji/emoji_one/pencil.png?v=3 ":pencil:")
### ![:checkered_flag:](https://forum.freecodecamp.com/images/emoji/emoji_one/checkered_flag.png?v=3 ":checkered_flag:") Problem Explanation:
# Inventory Update
---
## Problem Explanation
In this problem, you've to compare and update the inventory stored in a 2D array against a second 2D array of a fresh delivery. Update the current existing inventory item quantities (in `arr1`). If an item cannot be found, add the new item and quantity into the inventory array. The returned inventory array should be in alphabetical order by item.
@ -13,100 +15,92 @@ The current as well as new inventory will be in this format: `[[2, "item-0"], [3
* <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array' target='_blank' rel='nofollow'>JS Array</a>
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 1
---
## Hints
### Hint 1
You need to work through each item of the new inventory to see if it exists in the current inventory or not. Remember that the product name is stored as the second element of each sub-array: `array[0][1] = "item-name"`.
> _try to solve the problem now_
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 2
### Hint 2
If the item exists, you need to add the quantity from the new inventory. If the item doesn't exist, you need to add the entire item.
> _try to solve the problem now_
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 3
### Hint 3
Return the completed inventory in alphabetical order.
> _try to solve the problem now_
## Spoiler Alert!
![warning sign](//discourse-user-assets.s3.amazonaws.com/original/2X/2/2d6c412a50797771301e7ceabd554cef4edcd74d.gif)
**Solution ahead!**
## ![:beginner:](https://forum.freecodecamp.com/images/emoji/emoji_one/beginner.png?v=3 ":beginner:") Basic Code Solution:
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```javascript
function updateInventory(arr1, arr2) {
function updateInventory(arr1, arr2) {
// Variable for location of product
var index;
// Variable for location of product
var index;
// A helper method to return the index of a specified product (undefined if not found)
var getProductIndex = function (name) {
for (var i = 0; i < this.length; i++) {
if (this[i][1] === name) {
return i;
}
}
return undefined;
}
// For each item of the new Inventory
for (var i = 0; i < arr2.length; i++) {
// Invoke our helper function using arr1 as this
index = getProductIndex.call(arr1, arr2[i][1]);
// If the item doesn't exist
if (index === undefined) {
// Push the entire item
arr1.push(arr2[i]);
} else {
// Add the new quantity of the current item
arr1[index][0] += arr2[i][0];
}
}
// Sort alphabetically, by the product name of each item
arr1.sort(function (a, b) {
if (a[1] > b[1]) {
return 1;
}
if (a[1] < b[1]) {
return -1;
}
return 0;
});
return arr1;
// A helper method to return the index of a specified product (undefined if not found)
var getProductIndex = function(name) {
for (var i = 0; i < this.length; i++) {
if (this[i][1] === name) {
return i;
}
}
return undefined;
};
// test here
// Example inventory lists
var curInv = [
[21, "Bowling Ball"],
[2, "Dirty Sock"],
[1, "Hair Pin"],
[5, "Microphone"]
];
// For each item of the new Inventory
for (var i = 0; i < arr2.length; i++) {
// Invoke our helper function using arr1 as this
index = getProductIndex.call(arr1, arr2[i][1]);
var newInv = [
[2, "Hair Pin"],
[3, "Half-Eaten Apple"],
[67, "Bowling Ball"],
[7, "Toothpaste"]
];
// If the item doesn't exist
if (index === undefined) {
// Push the entire item
arr1.push(arr2[i]);
} else {
// Add the new quantity of the current item
arr1[index][0] += arr2[i][0];
}
}
updateInventory(curInv, newInv);
// Sort alphabetically, by the product name of each item
arr1.sort(function(a, b) {
if (a[1] > b[1]) {
return 1;
}
if (a[1] < b[1]) {
return -1;
}
return 0;
});
return arr1;
}
// test here
// Example inventory lists
var curInv = [
[21, "Bowling Ball"],
[2, "Dirty Sock"],
[1, "Hair Pin"],
[5, "Microphone"]
];
var newInv = [
[2, "Hair Pin"],
[3, "Half-Eaten Apple"],
[67, "Bowling Ball"],
[7, "Toothpaste"]
];
updateInventory(curInv, newInv);
```
### Code Explanation:
#### Code Explanation
* The variable **index** stores the location (index) of a product.
* The helper function `getProductIndex()` returns the index of a specified product. It iterates through each element of the array that it is called on until it can find the name parameter. If the product is not found in the inventory, `undefined` is returned.
@ -124,74 +118,75 @@ Return the completed inventory in alphabetical order.
* <a href='http://forum.freecodecamp.com/t/javascript-array-prototype-push/14298' target='_blank' rel='nofollow'>JS Array.prototype.push()</a>
* <a href='http://forum.freecodecamp.com/t/javascript-array-prototype-sort/14306' target='_blank' rel='nofollow'>JS Array.prototype.sort()</a>
## ![:sunflower:](https://forum.freecodecamp.com/images/emoji/emoji_one/sunflower.png?v=3 ":sunflower:") Intermediate Code Solution:
</details>
<details><summary>Solution 2 (Click to Show/Hide)</summary>
```javascript
function updateInventory(arr1, arr2) {
// All inventory must be accounted for or you're fired!
function updateInventory(arr1, arr2) {
// All inventory must be accounted for or you're fired!
var index;
var arrCurInvName = []; // Names of arr1's items
var arrNeInvName = []; // Names of arr2's items
var index;
var arrCurInvName = []; // Names of arr1's items
var arrNeInvName = []; // Names of arr2's items
// Same as using two for loops, this takes care of increasing the number of stock quantity.
arr1.map(function(item1) {
return arr2.map(function(item2) {
if (item1[1] === item2[1]) {
item1[0] = item1[0] + item2[0]; //Increase number of stock
}
});
});
// Same as using two for loops, this takes care of increasing the number of stock quantity.
arr1.map(function(item1) {
return arr2.map(function(item2) {
if (item1[1] === item2[1]) {
item1[0] = item1[0] + item2[0]; //Increase number of stock
}
});
});
// Get item's name for new Inventory
arr2.map(function(item) {
arrNeInvName.push(item[1]);
});
// Get item's name for new Inventory
arr2.map(function(item) {
arrNeInvName.push(item[1]);
});
// Get item's name for Current Inventory
arr1.map(function(item) {
arrCurInvName.push(item[1]);
});
// Get item's name for Current Inventory
arr1.map(function(item) {
arrCurInvName.push(item[1]);
});
// Add new inventory items to current inventory.
arrNeInvName.map(function(item) {
if (arrCurInvName.indexOf(item) === -1) {
index = arrNeInvName.indexOf(item);
arr1.push(arr2[index]);
}
});
// Sort the array alphabetically using the second element of the array as base.
arr1.sort(function(currItem, nextItem) {
//Ternary function to avoid using if else
return currItem[1] > nextItem[1] ? 1 : -1;
});
return arr1;
// Add new inventory items to current inventory.
arrNeInvName.map(function(item) {
if (arrCurInvName.indexOf(item) === -1) {
index = arrNeInvName.indexOf(item);
arr1.push(arr2[index]);
}
});
// test here
// Example inventory lists
var curInv = [
[21, "Bowling Ball"],
[2, "Dirty Sock"],
[1, "Hair Pin"],
[5, "Microphone"]
];
// Sort the array alphabetically using the second element of the array as base.
arr1.sort(function(currItem, nextItem) {
//Ternary function to avoid using if else
return currItem[1] > nextItem[1] ? 1 : -1;
});
var newInv = [
[2, "Hair Pin"],
[3, "Half-Eaten Apple"],
[67, "Bowling Ball"],
[7, "Toothpaste"]
];
return arr1;
}
updateInventory(curInv, newInv);
// test here
// Example inventory lists
var curInv = [
[21, "Bowling Ball"],
[2, "Dirty Sock"],
[1, "Hair Pin"],
[5, "Microphone"]
];
var newInv = [
[2, "Hair Pin"],
[3, "Half-Eaten Apple"],
[67, "Bowling Ball"],
[7, "Toothpaste"]
];
updateInventory(curInv, newInv);
```
### Code Explanation:
#### Code Explanation
* The variable **index** stores the location (index) of a product.
* **arrCurInvName** has the names of **arr1**'s items.
@ -207,66 +202,64 @@ Return the completed inventory in alphabetical order.
* <a href='http://forum.freecodecamp.com/t/javascript-array-prototype-indexof/14291' target='_blank' rel='nofollow'>JS Array.prototype.indexOf()</a>
* <a href='http://forum.freecodecamp.com/t/javascript-ternary-operator/15973' target='_blank' rel='nofollow'>JS Ternary Operator</a>
## ![:rotating_light:](https://forum.freecodecamp.com/images/emoji/emoji_one/rotating_light.png?v=3 ":rotating_light:") Advanced Code Solution:
</details>
<details><summary>Solution 3 (Click to Show/Hide)</summary>
```javascript
function updateInventory(arr1, arr2) {
// All inventory must be accounted for or you're fired!
function updateInventory(arr1, arr2) {
// All inventory must be accounted for or you're fired!
// convert current inventory (arr1) to an one-dimensional array
const inventory = Array.prototype.concat.apply([], arr1);
// convert current inventory (arr1) to an one-dimensional array
const inventory = Array.prototype.concat.apply([], arr1);
// loop through new delivery (arr2)
for (let i = 0; i < arr2.length; i++) {
// loop through new delivery (arr2)
for (let i = 0; i < arr2.length; i++) {
// extract item properties for easy reference
const item = arr2[i][1];
const quantity = arr2[i][0];
// extract item properties for easy reference
const item = arr2[i][1];
const quantity = arr2[i][0];
// check if item already exists in inventory
const position = inventory.indexOf(item);
// exsisting item: update quantity
if (position !== -1) {
const row = Math.floor(position / 2);
arr1[row][0] += quantity;
continue;
}
// alien item: add to inventory
arr1.push([quantity, item]);
}
// sort inventory in alphabetical order
arr1.sort((previous, next) => (previous[1] > [next[1]]) ? 1 : -1);
return arr1;
// check if item already exists in inventory
const position = inventory.indexOf(item);
// exsisting item: update quantity
if (position !== -1) {
const row = Math.floor(position / 2);
arr1[row][0] += quantity;
continue;
}
// alien item: add to inventory
arr1.push([quantity, item]);
}
// test here
// Example inventory lists
var curInv = [
[21, "Bowling Ball"],
[2, "Dirty Sock"],
[1, "Hair Pin"],
[5, "Microphone"]
];
// sort inventory in alphabetical order
arr1.sort((previous, next) => (previous[1] > [next[1]] ? 1 : -1));
var newInv = [
[2, "Hair Pin"],
[3, "Half-Eaten Apple"],
[67, "Bowling Ball"],
[7, "Toothpaste"]
];
return arr1;
}
updateInventory(curInv, newInv);
// test here
// Example inventory lists
var curInv = [
[21, "Bowling Ball"],
[2, "Dirty Sock"],
[1, "Hair Pin"],
[5, "Microphone"]
];
var newInv = [
[2, "Hair Pin"],
[3, "Half-Eaten Apple"],
[67, "Bowling Ball"],
[7, "Toothpaste"]
];
updateInventory(curInv, newInv);
```
### Code Explanation:
#### Code Explanation
* Convert current inventory array **arr1** to an one-dimensional array in order that `indexOf()` method could be used to check existance of new delivery items in current inventory.
* Check if item already exists in current inventory using `indexOf()`.
@ -279,9 +272,5 @@ Return the completed inventory in alphabetical order.
* <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply'>JS Function.prototype.apply()</a>
* <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/continue' target='_blank' rel='nofollow'>JS continue</a>
* <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort' target='_blank' rel='nofollow'>JS Array.prototype.sort()</a>
</details>
## ![:clipboard:](https://forum.freecodecamp.com/images/emoji/emoji_one/clipboard.png?v=3 ":clipboard:") NOTES FOR CONTRIBUTIONS:
* ![:warning:](https://forum.freecodecamp.com/images/emoji/emoji_one/warning.png?v=3 ":warning:") **DO NOT** add solutions that are similar to any existing solutions. If you think it is **_similar but better_**, then try to merge (or replace) the existing similar solution.
* Add an explanation of your solution.
* Categorize the solution in one of the following categories — **Basic**, **Intermediate** and **Advanced**. ![:traffic_light:](https://forum.freecodecamp.com/images/emoji/emoji_one/traffic_light.png?v=3 ":traffic_light:")

View File

@ -1,17 +1,19 @@
---
title: No Repeats Please
---
![:triangular_flag_on_post:](https://forum.freecodecamp.com/images/emoji/emoji_one/triangular_flag_on_post.png?v=3 ":triangular_flag_on_post:") Remember to use <a>**`Read-Search-Ask`**</a> if you get stuck. Try to pair program ![:busts_in_silhouette:](https://forum.freecodecamp.com/images/emoji/emoji_one/busts_in_silhouette.png?v=3 ":busts_in_silhouette:") and write your own code ![:pencil:](https://forum.freecodecamp.com/images/emoji/emoji_one/pencil.png?v=3 ":pencil:")
### ![:checkered_flag:](https://forum.freecodecamp.com/images/emoji/emoji_one/checkered_flag.png?v=3 ":checkered_flag:") Problem Explanation:
# No Repeats Please
---
## Problem Explanation
This task requires us to return the number of total permutations of the provided string that don't have repeated consecutive letters. It is to be assumed that all characters in the provided string are each unique. For example, `aab` should return 2 because it has 6 total permutations (`aab`, `aab`, `aba`, `aba`, `baa`, `baa`), but only 2 of them (`aba` and `aba`) don't have the same letter (in this case `a`) repeating.
To achieve that, we'll have to look at each possible permutation of a string. There are several ways to do that. A common interview question is building a function that collects all permutations of a string. There are several tutorials available on the internet on how to do that.
#### Potential Methods Used As Solution
**Potential Methods Used As Solution**
##### Recursive Method
**Recursive Method**
This task can be daunting even after watching a tutorial. To write a recursive solution, you will want to send each new use of the function three inputs:
@ -21,6 +23,7 @@ This task can be daunting even after watching a tutorial. To write a recursive s
The pseudo code will look something like this:
```
var str = ???;
permAlone(current position in original string, characters used already in original string, created string) {
if (current string is finished) {
@ -37,13 +40,15 @@ The pseudo code will look something like this:
}
}
permAlone(0, nothing used yet, empty new string (or array the same size as str));
```
Another way to think about this problem is to start from an empty space. Introduce the first letter to the space. This space will now contain the first sub-permutation. Here's a diagram illustrating the idea:
![diagram](//discourse-user-assets.s3.amazonaws.com/original/2X/6/69896bacc8bd3b2e347beb4b304a7f97caa6d9ab.png)
##### Non-Recursive Method
**Non-Recursive Method**
```
// An approach to introduce a new character to a permutation
var ch = '?';
var source = ['?', '?', '?']; // Current sub-permutation
@ -54,6 +59,7 @@ Another way to think about this problem is to start from an empty space. Introdu
temp.splice(i, 0, ch); // Insert the new character
dest.push(temp); // Store the new sub-permutation
}
```
Finding each permutation could then be done non-recursively by including the above in a function taking a source array and returning a destination array. For each letter of the input string, pass that character, as well as the array returned from the previous call of the function.
@ -68,81 +74,76 @@ A way to visualize this is by considering a tree that starts with the first char
* <a>JS Regex Resources</a>
* <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String' target='_blank' rel='nofollow'>JS String object</a>
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 1
---
## Hints
### Hint 1
* The easiest way is to use Heap's algorithm to recursively get a list of all the permutations.
> _try to solve the problem now_
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 2
### Hint 2
* Once you have the list then just create a regular expression to catch the repeating characters.
> _try to solve the problem now_
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 3
### Hint 3
* You will want to have the permutations as an array of joined strings instead of separated characters.
> _try to solve the problem now_
## Spoiler Alert!
<details><summary>Solution 1 (Click to Show/Hide)</summary>
![warning sign](//discourse-user-assets.s3.amazonaws.com/original/2X/2/2d6c412a50797771301e7ceabd554cef4edcd74d.gif)
```js
function permAlone(str) {
// Create a regex to match repeated consecutive characters.
var regex = /(.)\1+/;
**Solution ahead!**
// Split the string into an array of characters.
var arr = str.split("");
var permutations = [];
var tmp;
## ![:beginner:](https://forum.freecodecamp.com/images/emoji/emoji_one/beginner.png?v=3 ":beginner:") Basic Code Solution:
// Return 0 if str contains same character.
if (str.match(regex) !== null && str.match(regex)[0] === str) return 0;
function permAlone(str) {
// Function to swap variables' content.
function swap(index1, index2) {
tmp = arr[index1];
arr[index1] = arr[index2];
arr[index2] = tmp;
}
// Create a regex to match repeated consecutive characters.
var regex = /(.)\1+/;
// Split the string into an array of characters.
var arr = str.split('');
var permutations = [];
var tmp;
// Return 0 if str contains same character.
if (str.match(regex) !== null && str.match(regex)[0] === str) return 0;
// Function to swap variables' content.
function swap(index1, index2) {
tmp = arr[index1];
arr[index1] = arr[index2];
arr[index2] = tmp;
// Generate arrays of permutations using the algorithm.
function generate(int) {
if (int === 1) {
// Make sure to join the characters as we create the permutation arrays
permutations.push(arr.join(""));
} else {
for (var i = 0; i != int; ++i) {
generate(int - 1);
swap(int % 2 ? 0 : i, int - 1);
}
// Generate arrays of permutations using the algorithm.
function generate(int) {
if (int === 1) {
// Make sure to join the characters as we create the permutation arrays
permutations.push(arr.join(''));
} else {
for (var i = 0; i != int; ++i) {
generate(int - 1);
swap(int % 2 ? 0 : i, int - 1);
}
}
}
generate(arr.length);
// Filter the array of repeated permutations.
var filtered = permutations.filter(function(string) {
return !string.match(regex);
});
// Return how many have no repetitions.
return filtered.length;
}
}
// Test here.
permAlone('aab');
generate(arr.length);
// Filter the array of repeated permutations.
var filtered = permutations.filter(function(string) {
return !string.match(regex);
});
### Code Explanation:
// Return how many have no repetitions.
return filtered.length;
}
// Test here.
permAlone("aab");
```
#### Code Explanation
* **regex** contains the regular expression to match repeated consecutive characters.
* The string **str** is split into an array of characters, **arr**.
@ -162,8 +163,5 @@ A way to visualize this is by considering a tree that starts with the first char
* <a href='https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/length' target='_blank' rel='nofollow'>array.length</a>
* <a href='http://forum.freecodecamp.com/t/javascript-array-prototype-filter/14289' target='_blank' rel='nofollow'>JS Array Prototype Filter</a>
## ![:clipboard:](https://forum.freecodecamp.com/images/emoji/emoji_one/clipboard.png?v=3 ":clipboard:") NOTES FOR CONTRIBUTIONS:
* ![:warning:](https://forum.freecodecamp.com/images/emoji/emoji_one/warning.png?v=3 ":warning:") **DO NOT** add solutions that are similar to any existing solutions. If you think it is **_similar but better_**, then try to merge (or replace) the existing similar solution.
* Add an explanation of your solution.
* Categorize the solution in one of the following categories — **Basic**, **Intermediate** and **Advanced**. ![:traffic_light:](https://forum.freecodecamp.com/images/emoji/emoji_one/traffic_light.png?v=3 ":traffic_light:")
</details>

View File

@ -1,7 +1,7 @@
---
title: Pairwise
---
## Pairwise
# Pairwise
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/coding-interview-prep/algorithms/pairwise/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.

View File

@ -1,7 +1,7 @@
---
title: Add a New Element to a Binary Search Tree
---
## Add a New Element to a Binary Search Tree
# Add a New Element to a Binary Search Tree
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/coding-interview-prep/data-structures/add-a-new-element-to-a-binary-search-tree/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.

View File

@ -1,7 +1,7 @@
---
title: Add Elements at a Specific Index in a Linked List
---
## Add Elements at a Specific Index in a Linked List
# Add Elements at a Specific Index in a Linked List
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/coding-interview-prep/data-structures/add-elements-at-a-specific-index-in-a-linked-list/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.

View File

@ -1,50 +1,44 @@
---
title: Adjacency List
---
## Adjacency List
![:triangular_flag_on_post:](https://forum.freecodecamp.com/images/emoji/emoji_one/triangular_flag_on_post.png?v=3 ":triangular_flag_on_post:") Remember to use <a>**`Read-Search-Ask`**</a> if you get stuck. Try to pair program ![:busts_in_silhouette:](https://forum.freecodecamp.com/images/emoji/emoji_one/busts_in_silhouette.png?v=3 ":busts_in_silhouette:") and write your own code ![:pencil:](https://forum.freecodecamp.com/images/emoji/emoji_one/pencil.png?v=3 ":pencil:")
# Adjacency List
### ![:checkered_flag:](https://forum.freecodecamp.com/images/emoji/emoji_one/checkered_flag.png?v=3 ":checkered_flag:") Problem Explanation:
---
## Problem Explanation
To solve this problem, you have to create a Javascript Object to emulate an undirected graph in the form of an adjacency list.
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 1
---
## Hints
### Hint 1
Create keys with the names James, Jill, Jenny and Jeff.
> _try to solve the problem now_
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 2
### Hint 2
Read the presentation and try to understand what it means to be an undirected graph.
> _try to solve the problem now_
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```js
var undirectedAdjList = {
James: ["Jeff"],
Jill: ["Jenny"],
Jenny: ["Jill", "Jeff"],
Jeff: ["Jenny", "James"]
};
```
## Spoiler Alert!
![warning sign](//discourse-user-assets.s3.amazonaws.com/original/2X/2/2d6c412a50797771301e7ceabd554cef4edcd74d.gif)
**Solution ahead!**
## ![:beginner:](https://forum.freecodecamp.com/images/emoji/emoji_one/beginner.png?v=3 ":beginner:") Basic Code Solution:
var undirectedAdjList = {
James: ["Jeff"],
Jill: ["Jenny"],
Jenny: ["Jill", "Jeff"],
Jeff: ["Jenny", "James"]
};
### Code Explanation:
#### Code Explanation
* The undirected graph is created using a Javascript Object. Each unique name is a key and the each person who has a relationship with the name is in the unique name's array value. e.g. if James and Jeff have a relationship, Jeff will be in James's array value and James will be in Jeff's array value.
## ![:clipboard:](https://forum.freecodecamp.com/images/emoji/emoji_one/clipboard.png?v=3 ":clipboard:") NOTES FOR CONTRIBUTIONS:
* ![:warning:](https://forum.freecodecamp.com/images/emoji/emoji_one/warning.png?v=3 ":warning:") **DO NOT** add solutions that are similar to any existing solutions. If you think it is **_similar but better_**, then try to merge (or replace) the existing similar solution.
* Add an explanation of your solution.
* Categorize the solution in one of the following categories — **Basic**, **Intermediate** and **Advanced**. ![:traffic_light:](https://forum.freecodecamp.com/images/emoji/emoji_one/traffic_light.png?v=3 ":traffic_light:")
</details>

View File

@ -1,7 +1,7 @@
---
title: Adjacency Matrix
---
## Adjacency Matrix
# Adjacency Matrix
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/coding-interview-prep/data-structures/adjacency-matrix/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.

View File

@ -1,56 +1,46 @@
---
title: Breadth-First Search
---
## Breadth-First Search
# Breadth-First Search
Let's first define the `Tree` class to be used for the implementation of the Breadth First Search algorithm.
```python
class Tree:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```js
function bfs(graph, root) {
// Distance object returned
var nodesLen = {};
// Set all distances to infinity
for (var i = 0; i < graph.length; i++) {
nodesLen[i] = Infinity;
}
nodesLen[root] = 0; // ...except root node
var queue = [root]; // Keep track of nodes to visit
var current; // Current node traversing
// Keep on going until no more nodes to traverse
while (queue.length !== 0) {
current = queue.shift();
// Get adjacent nodes from current node
var curConnected = graph[current]; // Get layer of edges from current
var neighborIdx = []; // List of nodes with edges
var idx = curConnected.indexOf(1); // Get first edge connection
while (idx !== -1) {
neighborIdx.push(idx); // Add to list of neighbors
idx = curConnected.indexOf(1, idx + 1); // Keep on searching
}
// Loop through neighbors and get lengths
for (var j = 0; j < neighborIdx.length; j++) {
// Increment distance for nodes traversed
if (nodesLen[neighborIdx[j]] === Infinity) {
nodesLen[neighborIdx[j]] = nodesLen[current] + 1;
queue.push(neighborIdx[j]); // Add new neighbors to queue
}
}
}
return nodesLen;
}
```
The breadth first search algorithm moves from one level to another starting from the root of the tree. We will make use of a `queue` for this.
```python
def bfs(root_node):
queue = [root_node]
while queue:
top_element = queue.pop()
print("Node processed: ",top_element)
if top_element.left:
queue.append(top_element.left)
if top_element.right:
queue.append(top_element.right)
```
We can easily modify the above code to print the level of each node as well.
```python
def bfs(root_node):
queue = [(root_node, 0)]
while queue:
top_element, level = queue.pop()
print("Node processed: {} at level {}".format(top_element, level))
if top_element.left:
queue.append((top_element.left, level + 1))
if top_element.right:
queue.append((top_element.right, level + 1))
```
| Complexity | Time | Space |
| ----- | ------ | ------ |
| BFS | n | n |
</details>

View File

@ -1,7 +1,7 @@
---
title: Check if an Element is Present in a Binary Search Tree
---
## Check if an Element is Present in a Binary Search Tree
# Check if an Element is Present in a Binary Search Tree
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/coding-interview-prep/data-structures/check-if-an-element-is-present-in-a-binary-search-tree/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.

View File

@ -1,81 +1,88 @@
---
title: Create a Circular Queue
---
## Create a Circular Queue
# Create a Circular Queue
### Method:
---
## Problem Explanation
- In this challenge we create a Circular Queue data structure.
- First, we need to create an array of `size` with all elements set to `null`.
- Then we create an equeue method, which moves the write pointer but doesnt exceed the read pointer.
- The dequeue method on the other hand, moves the read pointer but doesnt exceed the write pointer.
- Example:
- First, we create an array of length 5:
```shell
```
[null, null, null, null, null]
^Read @ 0
^Write @ 0
```
- Then we enqueue `a`, `b`, and `c`:
```shell
```
- Then we enqueue `a`, `b`, and `c`:
```
[a, b, c, null, null]
^Read @ 0
^Write @ 3
```
```
- Now we dequeue all the enqueued items:
```shell
```
[null, null, null, null, null]
^Read @ 3
^Write @ 3
```
```
- Finally, we enqueue `d`, `e` and `f`:
```shell
```
[f, null, null, d, e]
^Read @ 3
^Write @ 1
```
### Solution:
```
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```js
class CircularQueue {
constructor(size) {
this.queue = [];
this.read = 0;
this.write = 0;
this.max = size - 1;
while (size > 0) {
this.queue.push(null);
size--;
}
constructor(size) {
this.queue = [];
this.read = 0;
this.write = 0;
this.max = size - 1;
while (size > 0) {
this.queue.push(null);
size--;
}
print() {
return this.queue;
}
print() {
return this.queue;
}
enqueue(item) {
if (this.queue[this.write] === null) {
this.queue[this.write++] = item;
if (this.write > this.max) this.write = 0;
return item;
}
enqueue(item) {
if (this.queue[this.write] === null){
this.queue[this.write++] = item;
if (this.write > this.max) this.write = 0;
return item;
}
return null;
return null;
}
dequeue() {
if (this.queue[this.read] != null) {
let item = this.queue[this.read];
this.queue[this.read++] = null;
if (this.read > this.max) this.read = 0;
return item;
}
dequeue() {
if (this.queue[this.read] != null){
let item = this.queue[this.read];
this.queue[this.read++] = null;
if (this.read > this.max) this.read = 0;
return item;
}
return null;
}
}
```
### References:
return null;
}
}
```
#### Relevant Links
- [Wikipedia](https://en.wikipedia.org/wiki/Circular_buffer)
</details>

View File

@ -1,7 +1,7 @@
---
title: Create a Doubly Linked List
---
## Create a Doubly Linked List
# Create a Doubly Linked List
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/coding-interview-prep/data-structures/create-a-doubly-linked-list/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.

View File

@ -1,7 +1,7 @@
---
title: Create a Hash Table
---
## Create a Hash Table
# Create a Hash Table
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/coding-interview-prep/data-structures/create-a-hash-table/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.

View File

@ -1,7 +1,7 @@
---
title: Create a Linked List Class
---
## Create a Linked List Class
# Create a Linked List Class
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/coding-interview-prep/data-structures/create-a-linked-list-class/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.

View File

@ -1,7 +1,7 @@
---
title: Create a Map Data Structure
---
## Create a Map Data Structure
# Create a Map Data Structure
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/coding-interview-prep/data-structures/create-a-map-data-structure/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.

View File

@ -1,9 +1,10 @@
---
title: Create a Priority Queue Class
---
## Create a Priority Queue Class
# Create a Priority Queue Class
### Method:
---
## Problem Explanation
- Priority Queue is an Abstract Data Type.
- It can be implemented using other Data Structures but is commonly implemented using a Heap.
- Each node contains a priority. When we enqueue a node to the queue, it's "bubbled up" to its place in the queue.
@ -18,7 +19,11 @@ title: Create a Priority Queue Class
| Priority Queue | 1 | 1 | logn | logn |
### Solution:
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```js
//function which swaps elements in array, using ES6 syntax
function swap(arr, i, j) {
@ -121,5 +126,7 @@ class PriorityQueue {
}
```
### References:
#### Relevant Links
- [Wikipedia](https://en.wikipedia.org/wiki/Priority_queue)
</details>

View File

@ -1,10 +1,11 @@
---
title: Create a Queue Class
---
## Create a Queue Class
# Create a Queue Class
### Method:
---
## Problem Explanation
- A Queue is an abstract Data Structure.
- A Queue folow FIFO/LILO principle.
- In this challenge we nede to implement `enqueue()`, `dequeue()`, `front()`, `size()`, `isEmpty()` methods.
@ -20,61 +21,69 @@ title: Create a Queue Class
- ![Queue in action](https://upload.wikimedia.org/wikipedia/commons/thumb/5/52/Data_Queue.svg/405px-Data_Queue.svg.png)
### Solution:
#### Basic:
##### Note:
- This solution is not exactly a queue, the shift() method used in the dequeue() method is of complexity `O(n)` and not `O(1)`. However, the advanced solution rectifies this and uses Object(HashTables) instead of Array to implement Queue.
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
**Note:** This solution is not exactly a queue, the shift() method used in the dequeue() method is of complexity `O(n)` and not `O(1)`. However, the advanced solution rectifies this and uses Object(HashTables) instead of Array to implement Queue.
```js
function Queue () {
var collection = [];
this.print = function() {
console.log(collection);
};
this.enqueue = function(val){
collection.push(val);
};
this.dequeue = function(){
return collection.shift();
}
this.front = function(){
return collection[0];
}
this.size = function(){
return collection.length;
}
this.isEmpty = function(){
return collection.length === 0;
}
function Queue() {
var collection = [];
this.print = function() {
console.log(collection);
};
this.enqueue = function(val) {
collection.push(val);
};
this.dequeue = function() {
return collection.shift();
};
this.front = function() {
return collection[0];
};
this.size = function() {
return collection.length;
};
this.isEmpty = function() {
return collection.length === 0;
};
}
```
#### Advanced - ES6 class syntax:
</details>
<details><summary>Solution 2 (Click to Show/Hide)</summary>
```js
class Queue {
constructor(){
this.collection = {};
this.start = 0;
this.end = 0;
}
print(){
console.log(this.collection);
}
enqueue(val){
this.collection[this.end++] = val;
}
dequeue(){
return this.collection[this.start++];
}
front(){
return this.collection[this.start];
}
size(){
return this.end - this.start;
}
isEmpty(){
return this.size() === 0;
}
constructor() {
this.collection = {};
this.start = 0;
this.end = 0;
}
print() {
console.log(this.collection);
}
enqueue(val) {
this.collection[this.end++] = val;
}
dequeue() {
return this.collection[this.start++];
}
front() {
return this.collection[this.start];
}
size() {
return this.end - this.start;
}
isEmpty() {
return this.size() === 0;
}
}
```
### References:
#### Relevant Links
- [Wikipedia](https://en.wikipedia.org/wiki/Queue_(abstract_data_type))
</details>

View File

@ -1,32 +1,39 @@
---
title: Create a Set Class
---
## Create a Set Class
# Create a Set Class
### Method:
---
## Problem Explanation
- A Set is an abstract data structure.
- It can store unique value and the collection is unordered.
- In this challenge, we have to implement `.add()` method. This method should only add unique values to `collection`.
- The method should return `true`, if the value is sucessfully added to the collection, otherwise it should return `false`.
### Solution:
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```js
function Set() {
// the var collection will hold our set
var collection = [];
// this method will check for the presence of an element and return true or false
this.has = function(element) {
return (collection.indexOf(element) !== -1);
};
// this method will return all the values in the set
this.values = function() {
return collection;
};
this.add = function(el) {
return this.has(el) ? false : Boolean(collection.push(el));
}
// the var collection will hold our set
var collection = [];
// this method will check for the presence of an element and return true or false
this.has = function(element) {
return collection.indexOf(element) !== -1;
};
// this method will return all the values in the set
this.values = function() {
return collection;
};
this.add = function(el) {
return this.has(el) ? false : Boolean(collection.push(el));
};
}
```
### Resources:
#### Relevant Links
- [Wikipedia](https://en.wikipedia.org/wiki/Set_(abstract_data_type))
</details>

View File

@ -1,9 +1,10 @@
---
title: Create a Stack Class
---
## Create a Stack Class
# Create a Stack Class
### Method:
---
## Problem Explanation
- Stack is an abstract data structure.
- Stack follows LIFO/FILO principle.
- In this challenge, we need to add `.push()`, `.pop()`, `.peek()`, `.isEmpty()` and `.clear()` methods to the class.
@ -18,58 +19,65 @@ title: Create a Stack Class
| ----- | ------ | ------ | ------ | ------ |
| Stack | n | n | 1 | 1 |
### Solution:
#### Basic:
```js
function Stack() {
var collection = [];
this.print = function() {
console.log(collection);
};
this.push = function(val){
return collection.push(val);
}
this.pop = function(){
return collection.pop();
}
this.peek = function(){
return collection[collection.length-1];
}
this.isEmpty = function(){
return collection.length === 0;
}
this.clear = function(){
collection.length = 0;
}
}
```
#### Advanced - ES6 Class syntax:
```js
class Stack {
constructor() {
this.collection = [];
}
print(){
console.log(this.collection);
}
push(val){
retiurn this.collection.push(val);
}
pop(){
return this.collection.pop();
}
peek(){
return this.collection[this.collection.length-1];
}
isEmpty(){
return this.collection.length === 0;
}
clear(){
return this.collection.length = 0;
}
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```js
function Stack() {
var collection = [];
this.print = function() {
console.log(collection);
};
this.push = function(val) {
return collection.push(val);
};
this.pop = function() {
return collection.pop();
};
this.peek = function() {
return collection[collection.length - 1];
};
this.isEmpty = function() {
return collection.length === 0;
};
this.clear = function() {
collection.length = 0;
};
}
```
### Resources:
</details>
<details><summary>Solution 2 (Click to Show/Hide)</summary>
```js
class Stack {
constructor() {
this.collection = [];
}
print() {
console.log(this.collection);
}
push(val) {
return this.collection.push(val);
}
pop() {
return this.collection.pop();
}
peek() {
return this.collection[this.collection.length - 1];
}
isEmpty() {
return this.collection.length === 0;
}
clear() {
return (this.collection.length = 0);
}
}
```
#### Relevant Links
- [Wikipedia](https://en.wikipedia.org/wiki/Stack_(abstract_data_type))
</details>

View File

@ -1,7 +1,7 @@
---
title: Create a Trie Search Tree
---
## Create a Trie Search Tree
# Create a Trie Search Tree
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/coding-interview-prep/data-structures/create-a-trie-search-tree/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.

View File

@ -1,7 +1,7 @@
---
title: Create an ES6 JavaScript Map
---
## Create an ES6 JavaScript Map
# Create an ES6 JavaScript Map
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/coding-interview-prep/data-structures/create-an-es6-javascript-map/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.

View File

@ -1,37 +1,31 @@
---
title: Create and Add to Sets in ES6
---
## Create and Add to Sets in ES6
# Create and Add to Sets in ES6
![:triangular_flag_on_post:](https://forum.freecodecamp.com/images/emoji/emoji_one/triangular_flag_on_post.png?v=3 ":triangular_flag_on_post:") Remember to use <a>**`Read-Search-Ask`**</a> if you get stuck. Try to pair program ![:busts_in_silhouette:](https://forum.freecodecamp.com/images/emoji/emoji_one/busts_in_silhouette.png?v=3 ":busts_in_silhouette:") and write your own code ![:pencil:](https://forum.freecodecamp.com/images/emoji/emoji_one/pencil.png?v=3 ":pencil:")
### ![:checkered_flag:](https://forum.freecodecamp.com/images/emoji/emoji_one/checkered_flag.png?v=3 ":checkered_flag:") Problem Explanation:
---
## Problem Explanation
To solve this problem, you have to add an array of items to the set.
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 1
---
## Hints
### Hint 1
Use the add function to add an array of strings to the set.
> _try to solve the problem now_
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 2
### Hint 2
Use the length attribute on the values of the Set.
> _try to solve the problem now_
---
## Solutions
## Spoiler Alert!
![warning sign](//discourse-user-assets.s3.amazonaws.com/original/2X/2/2d6c412a50797771301e7ceabd554cef4edcd74d.gif)
**Solution ahead!**
## ![:beginner:](https://forum.freecodecamp.com/images/emoji/emoji_one/beginner.png?v=3 ":beginner:") Basic Code Solution:
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```js
function checkSet() {
@ -46,13 +40,10 @@ function checkSet() {
checkSet();
```
### Code Explanation:
#### Code Explanation
* Creating a set object as shown in pre-written code will create the set without duplicate objects.
* Therefore, by using the add function, we can add items to the set and they will not be duplicated, and will still be represented in the array.
## ![:clipboard:](https://forum.freecodecamp.com/images/emoji/emoji_one/clipboard.png?v=3 ":clipboard:") NOTES FOR CONTRIBUTIONS:
* ![:warning:](https://forum.freecodecamp.com/images/emoji/emoji_one/warning.png?v=3 ":warning:") **DO NOT** add solutions that are similar to any existing solutions. If you think it is **_similar but better_**, then try to merge (or replace) the existing similar solution.
* Add an explanation of your solution.
* Categorize the solution in one of the following categories — **Basic**, **Intermediate** and **Advanced**. ![:traffic_light:](https://forum.freecodecamp.com/images/emoji/emoji_one/traffic_light.png?v=3 ":traffic_light:")
</details>

View File

@ -1,7 +1,7 @@
---
title: Delete a Leaf Node in a Binary Search Tree
---
## Delete a Leaf Node in a Binary Search Tree
# Delete a Leaf Node in a Binary Search Tree
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/coding-interview-prep/data-structures/delete-a-leaf-node-in-a-binary-search-tree/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.

View File

@ -1,7 +1,7 @@
---
title: Delete a Node with One Child in a Binary Search Tree
---
## Delete a Node with One Child in a Binary Search Tree
# Delete a Node with One Child in a Binary Search Tree
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/coding-interview-prep/data-structures/delete-a-node-with-one-child-in-a-binary-search-tree/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.

View File

@ -1,7 +1,7 @@
---
title: Delete a Node with Two Children in a Binary Search Tree
---
## Delete a Node with Two Children in a Binary Search Tree
# Delete a Node with Two Children in a Binary Search Tree
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/coding-interview-prep/data-structures/delete-a-node-with-two-children-in-a-binary-search-tree/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.

View File

@ -1,7 +1,7 @@
---
title: Depth-First Search
---
## Depth-First Search
# Depth-First Search
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/coding-interview-prep/data-structures/depth-first-search/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.

View File

@ -1,87 +1,88 @@
---
title: Find the Minimum and Maximum Height of a Binary Search Tree
---
## Find the Minimum and Maximum Height of a Binary Search Tree
# Find the Minimum and Maximum Height of a Binary Search Tree
### Solution
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```js
var displayTree = (tree) => console.log(JSON.stringify(tree, null, 2));
var displayTree = tree => console.log(JSON.stringify(tree, null, 2));
function Node(value) {
this.value = value;
this.left = null;
this.right = null;
this.value = value;
this.left = null;
this.right = null;
}
function BinarySearchTree() {
this.root = null;
// change code below this line
// change code above this line
this.findMinHeight = function(root = this.root) {
// empty tree.
if(root === null) {
return -1;
}
// leaf node.
if(root.left === null && root.right === null) {
return 0;
}
if(root.left === null){
return this.findMinHeight(root.right) + 1;
}
if(root.right === null){
return this.findMinHeight(root.left) + 1;
}
const lHeight = this.findMinHeight(root.left);
const rHeight = this.findMinHeight(root.right);
return Math.min(lHeight, rHeight) + 1;
};
this.findMaxHeight = function(root = this.root) {
// empty tree.
if(root === null) {
return -1;
}
// leaf node.
if(root.left === null && root.right === null) {
return 0;
}
if(root.left === null){
return this.findMaxHeight(root.right) + 1;
}
if(root.right === null){
return this.findMaxHeight(root.left) + 1;
}
const lHeight = this.findMaxHeight(root.left);
const rHeight = this.findMaxHeight(root.right);
return Math.max(lHeight, rHeight) + 1;
};
this.isBalanced = function(root = this.root) {
this.root = null;
// change code below this line
// change code above this line
this.findMinHeight = function(root = this.root) {
// empty tree.
if (root === null) {
return -1;
}
// leaf node.
if (root.left === null && root.right === null) {
return 0;
}
if (root.left === null) {
return this.findMinHeight(root.right) + 1;
}
if (root.right === null) {
return this.findMinHeight(root.left) + 1;
}
const lHeight = this.findMinHeight(root.left);
const rHeight = this.findMinHeight(root.right);
return Math.min(lHeight, rHeight) + 1;
};
this.findMaxHeight = function(root = this.root) {
// empty tree.
if (root === null) {
return -1;
}
// leaf node.
if (root.left === null && root.right === null) {
return 0;
}
if (root.left === null) {
return this.findMaxHeight(root.right) + 1;
}
if (root.right === null) {
return this.findMaxHeight(root.left) + 1;
}
const lHeight = this.findMaxHeight(root.left);
const rHeight = this.findMaxHeight(root.right);
return Math.max(lHeight, rHeight) + 1;
};
this.isBalanced = function(root = this.root) {
if (root === null) {
return true;
}
if(root === null) {
return true;
}
if (root.left === null && root.right === null) {
return true;
}
if(root.left === null && root.right === null){
return true;
}
if (root.left === null) {
return this.findMaxHeight(root.right) <= 0;
}
if(root.left === null) {
return this.findMaxHeight(root.right) <= 0;
}
if (root.right === null) {
return this.findMaxHeight(root.left) <= 0;
}
if(root.right === null) {
return this.findMaxHeight(root.left) <= 0;
}
const lHeight = this.findMaxHeight(root.left);
const rHeight = this.findMaxHeight(root.right);
if(Math.abs(lHeight - rHeight) > 1){
return false;
}
return this.isBalanced(root.left) && this.isBalanced(root.right);
};
const lHeight = this.findMaxHeight(root.left);
const rHeight = this.findMaxHeight(root.right);
if (Math.abs(lHeight - rHeight) > 1) {
return false;
}
return this.isBalanced(root.left) && this.isBalanced(root.right);
};
}
```
</details>

View File

@ -1,7 +1,7 @@
---
title: Find the Minimum and Maximum Value in a Binary Search Tree
---
## Find the Minimum and Maximum Value in a Binary Search Tree
# Find the Minimum and Maximum Value in a Binary Search Tree
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/coding-interview-prep/data-structures/find-the-minimum-and-maximum-value-in-a-binary-search-tree/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.

View File

@ -1,7 +1,7 @@
---
title: Implement Heap Sort with a Min Heap
---
## Implement Heap Sort with a Min Heap
# Implement Heap Sort with a Min Heap
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/coding-interview-prep/data-structures/implement-heap-sort-with-a-min-heap/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.

View File

@ -1,7 +1,7 @@
---
title: Incidence Matrix
---
## Incidence Matrix
# Incidence Matrix
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/coding-interview-prep/data-structures/incidence-matrix/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.

View File

@ -1,7 +1,7 @@
---
title: Data Structures
---
## Data Structures
# Data Structures
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/mathematics/quadratic-equations/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.

View File

@ -1,7 +1,7 @@
---
title: Insert an Element into a Max Heap
---
## Insert an Element into a Max Heap
# Insert an Element into a Max Heap
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/coding-interview-prep/data-structures/insert-an-element-into-a-max-heap/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.

View File

@ -1,33 +1,28 @@
---
title: Invert a Binary Tree
---
## Invert a Binary Tree
# Invert a Binary Tree
---
## Hints
## Hint: 1
### Hint 1
Create a invert(node = this.root) method in the BinarySearchTree constructor function.
> _try to solve the problem now_
## Hint: 2
Try to use recursion and think of a base case.
> _try to solve the problem now_
---
## Solutions
## Spoiler Alert!
**Solution ahead!**
## Basic Code Solution:
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```js
var displayTree = (tree) => console.log(JSON.stringify(tree, null, 2));
var displayTree = tree => console.log(JSON.stringify(tree, null, 2));
function Node(value) {
this.value = value;
this.left = null;
@ -45,15 +40,13 @@ function BinarySearchTree() {
this.invert(node.right);
}
return node;
}
// change code above this line
};
// change code above this line
}
```
<a href='https://repl.it/repls/SereneScholarlyAnalyst' target='_blank' rel='nofollow'>Run Code</a>
### Code Explanation:
#### Code Explanation
* Using recursion will allow you to traverse each node once and the only extra memory used is the auxiliary temp variable that enables you to swap. You keep swapping the left and right pointers of a node until you reach the leaves which will not do anything as the left and right of them are null references.
## NOTES FOR CONTRIBUTIONS:
**DO NOT** add solutions that are similar to any existing solutions. If you think it is **_similar but better_**, then try to merge (or replace) the existing similar solution.
* Add an explanation of your solution.
* Categorize the solution in one of the following categories — **Basic**, **Intermediate** and **Advanced**.
</details>

View File

@ -1,23 +1,30 @@
---
title: Learn how a Stack Works
---
## Learn how a Stack Works
# Learn how a Stack Works
### Method:
---
## Problem Explanation
- Stacks are an abstract data structures.
- They follow LIFO (Last In First Out) or FILO (First In Last Out) principle.
- Stack's insertion and deletion operations are of **O(1)** time complexity.
- In JavaScript, arrays can be treated as a Stack since `.push()` and `.pop()` methods have time complexity of **O(1)**.
- In this challenge we need to `.pop()` and then `.push()` into the stack.
### Solution:
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```js
var homeworkStack = ["BIO12","HIS80","MAT122","PSY44"];
var homeworkStack = ["BIO12", "HIS80", "MAT122", "PSY44"];
homeworkStack.pop();
homeworkStack.push("CS50");
```
### Reference:
#### Relevant Links
- [Wikipedia](https://en.wikipedia.org/wiki/Stack_(abstract_data_type))
- Video by [Hackerrank](https://www.youtube.com/watch?v=wjI1WNcIntg)
</details>

View File

@ -1,7 +1,7 @@
---
title: Perform a Difference on Two Sets of Data
---
## Perform a Difference on Two Sets of Data
# Perform a Difference on Two Sets of Data
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/coding-interview-prep/data-structures/perform-a-difference-on-two-sets-of-data/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.

View File

@ -1,7 +1,7 @@
---
title: Perform a Subset Check on Two Sets of Data
---
## Perform a Subset Check on Two Sets of Data
# Perform a Subset Check on Two Sets of Data
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/coding-interview-prep/data-structures/perform-a-subset-check-on-two-sets-of-data/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.

View File

@ -1,7 +1,7 @@
---
title: Perform a Union on Two Sets
---
## Perform a Union on Two Sets
# Perform a Union on Two Sets
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/coding-interview-prep/data-structures/perform-a-union-on-two-sets/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.

View File

@ -1,7 +1,7 @@
---
title: Perform an Intersection on Two Sets of Data
---
## Perform an Intersection on Two Sets of Data
# Perform an Intersection on Two Sets of Data
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/coding-interview-prep/data-structures/perform-an-intersection-on-two-sets-of-data/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.

View File

@ -1,7 +1,7 @@
---
title: Remove an Element from a Max Heap
---
## Remove an Element from a Max Heap
# Remove an Element from a Max Heap
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/coding-interview-prep/data-structures/remove-an-element-from-a-max-heap/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.

View File

@ -1,7 +1,7 @@
---
title: Remove Elements from a Linked List by Index
---
## Remove Elements from a Linked List by Index
# Remove Elements from a Linked List by Index
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/coding-interview-prep/data-structures/remove-elements-from-a-linked-list-by-index/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.

View File

@ -1,7 +1,7 @@
---
title: Remove Elements from a Linked List
---
## Remove Elements from a Linked List
# Remove Elements from a Linked List
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/coding-interview-prep/data-structures/remove-elements-from-a-linked-list/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.

View File

@ -1,7 +1,7 @@
---
title: Remove items from a set in ES6
---
## Remove items from a set in ES6
# Remove items from a set in ES6
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/coding-interview-prep/data-structures/remove-items-from-a-set-in-es6/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.

View File

@ -2,15 +2,20 @@
title: Reverse a Doubly Linked List
---
## Reverse a Doubly Linked List
# Reverse a Doubly Linked List
### Method:
---
## Problem Explanation
- Reverse the doubly linked list, and update previous and next variables for each member node accordingly.
- Define privileged methods add() and reverse().
- add() will find the end of the list and append new entries at this location.
- reverse() will swap entries one pair at a time using a temporary variable.
### Solution:
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```js
var Node = function(data, prev) {
@ -31,32 +36,32 @@ var DoublyLinkedList = function() {
this.head = node;
this.tail = node;
} else {
while (currentNode.next) {
previousNode = currentNode;
while (currentNode.next) {
previousNode = currentNode;
currentNode = currentNode.next;
}
node.prev = currentNode;
currentNode.next = node;
this.tail = node;
}
};
};
this.reverse = function() {
let temp = null;
let currentNode = this.head;
if (this.head === null) {
return null;
}
this.tail = currentNode;
while (currentNode) {
temp = currentNode.prev;
temp = currentNode.prev;
currentNode.prev = currentNode.next;
currentNode.next = temp;
currentNode = currentNode.prev;
}
if (temp != null) {
this.head = temp.prev;
}
@ -65,5 +70,7 @@ var DoublyLinkedList = function() {
};
```
### Reference:
#### Relevant Links
- [Wikipedia](https://en.wikipedia.org/wiki/Doubly_linked_list)
</details>

View File

@ -1,7 +1,7 @@
---
title: Search within a Linked List
---
## Search within a Linked List
# Search within a Linked List
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/coding-interview-prep/data-structures/search-within-a-linked-list/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.

View File

@ -1,13 +1,19 @@
---
title: Typed Arrays
---
## Typed Arrays
# Typed Arrays
### Method:
---
## Problem Explanation
- In this challenge, first we need to create a buffer of 64 bytes. We can use `ArrayBuffer()` constructor.
- After creating a buffer we need to create an Int32Array, for that we can use `Int32Array()` constructor.
### Solution:
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```js
//Create a buffer of 64 bytes
var buffer = new ArrayBuffer(64);
@ -16,6 +22,8 @@ var buffer = new ArrayBuffer(64);
var i32View = new Int32Array(buffer);
```
### References:
#### Relevant Links
- [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer)
- [TypedArray](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays)
</details>

View File

@ -1,7 +1,7 @@
---
title: Use .has and .size on an ES6 Set
---
## Use .has and .size on an ES6 Set
# Use .has and .size on an ES6 Set
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/coding-interview-prep/data-structures/use-.has-and-.size-on-an-es6-set/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.

View File

@ -1,7 +1,7 @@
---
title: Use Breadth First Search in a Binary Search Tree
---
## Use Breadth First Search in a Binary Search Tree
# Use Breadth First Search in a Binary Search Tree
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/coding-interview-prep/data-structures/use-breadth-first-search-in-a-binary-search-tree/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.

View File

@ -1,7 +1,7 @@
---
title: Use Depth First Search in a Binary Search Tree
---
## Use Depth First Search in a Binary Search Tree
# Use Depth First Search in a Binary Search Tree
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/coding-interview-prep/data-structures/use-depth-first-search-in-a-binary-search-tree/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.

View File

@ -1,7 +1,7 @@
---
title: Use Spread and Notes for ES5 Set() Integration
---
## Use Spread and Notes for ES5 Set() Integration
# Use Spread and Notes for ES5 Set() Integration
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/coding-interview-prep/data-structures/use-spread-and-notes-for-es5-set-integration/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.

View File

@ -1,7 +1,7 @@
---
title: Work with Nodes in a Linked List
---
## Work with Nodes in a Linked List
# Work with Nodes in a Linked List
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/coding-interview-prep/data-structures/work-with-nodes-in-a-linked-list/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.

Some files were not shown because too many files have changed in this diff Show More