/g).length, 'Make sure your
div
element has a closing tag.');"
+ "testString":
+ "assert(code.match(/<\\/div>/g) && code.match(/<\\/div>/g).length === code.match(/
/g).length, 'Make sure your
div
element has a closing tag.');"
}
],
"challengeType": 0,
@@ -2493,22 +2654,27 @@
"The
!
and uppercase
DOCTYPE
is important, especially for older browsers. The
html
is not case sensitive.",
"Next, the rest of your HTML code needs to be wrapped in
html
tags. The opening
<html>
goes directly below the
<!DOCTYPE html>
line, and the closing
</html>
goes at the end of the page.",
"Here's an example of the page structure:",
- "
<!DOCTYPE html>
<html>
<!-- Your HTML code goes here -->
</html>
",
+ "
<!DOCTYPE html>
<html>
<!-- Your HTML code goes here -->
</html>
",
"
",
"Add a
DOCTYPE
tag for HTML5 to the top of the blank HTML document in the code editor. Under it, add opening and closing
html
tags, which wrap around an
h1
element. The heading can include any text."
],
"tests": [
{
- "text": "Your code should include a
<!DOCTYPE html>
tag.",
- "testString": "assert(code.match(//gi), 'Your code should include a
<!DOCTYPE html>
tag.');"
+ "text":
+ "Your code should include a
<!DOCTYPE html>
tag.",
+ "testString":
+ "assert(code.match(//gi), 'Your code should include a
<!DOCTYPE html>
tag.');"
},
{
"text": "There should be one
html
element.",
- "testString": "assert($('html').length == 1, 'There should be one
html
element.');"
+ "testString":
+ "assert($('html').length == 1, 'There should be one
html
element.');"
},
{
- "text": "The
html
tags should wrap around one
h1
element.",
- "testString": "assert(code.match(/\\s*?
\\s*?.*?\\s*?<\\/h1>\\s*?<\\/html>/gi), 'The html
tags should wrap around one h1
element.');"
+ "text":
+ "The html
tags should wrap around one h1
element.",
+ "testString":
+ "assert(code.match(/\\s*?\\s*?.*?\\s*?<\\/h1>\\s*?<\\/html>/gi), 'The html
tags should wrap around one h1
element.');"
}
],
"challengeType": 0,
@@ -2522,7 +2688,7 @@
"O !
e o DOCTYPE
todo em maiúsculas são importantes, especialmente para navegadores mais velhos. O html
não é sensível a maiúsculas e minúsculas.",
"Em seguida, o resto do seu código HTML deve estar delimitado por tags html
. A tag <html>
vai diretamente abaixo da linha <!DOCTYPE html>
, e a tag </html>
vai no final da página.",
"Aqui está um exemplo da estrutura de uma página:",
- "<!DOCTYPE html>
<html>
<!-- Seu código HTML vai aqui -->
</html>
",
+ "<!DOCTYPE html>
<html>
<!-- Seu código HTML vai aqui -->
</html>
",
"
",
"Adicione uma tag DOCTYPE
para HTML5 no topo do documento HTML em branco no editor de texto. Abaixo dela, adicione tags html
de abertura e fechamento, ao redor de um elemento h1
. O texto do h1
pode ser qualquer um."
]
@@ -2546,34 +2712,46 @@
"You can add another level of organization in your HTML document within the html
tags with the head
and body
elements. Any markup with information about your page would go into the head
tag. Then any markup with the content of the page (what displays for a user) would go into the body
tag.",
"Metadata elements, such as link
, meta
, title
, and style
, typically go inside the head
element.",
"Here's an example of a page's layout:",
- "<!DOCTYPE html>
<html>
<head>
<!-- metadata elements -->
</head>
<body>
<!-- page contents -->
</body>
</html>
",
+ "<!DOCTYPE html>
<html>
<head>
<!-- metadata elements -->
</head>
<body>
<!-- page contents -->
</body>
</html>
",
"
",
"Edit the markup so there's a head
and a body
. The head
element should only include the title
, and the body
element should only include the h1
and p
."
],
"tests": [
{
- "text": "There should be only one head
element on the page.",
- "testString": "assert($('head').length == 1, 'There should be only one head
element on the page.');"
+ "text":
+ "There should be only one head
element on the page.",
+ "testString":
+ "assert($('head').length == 1, 'There should be only one head
element on the page.');"
},
{
- "text": "There should be only one body
element on the page.",
- "testString": "assert($('body').length == 1, 'There should be only one body
element on the page.');"
+ "text":
+ "There should be only one body
element on the page.",
+ "testString":
+ "assert($('body').length == 1, 'There should be only one body
element on the page.');"
},
{
- "text": "The head
element should be a child of the html
element.",
- "testString": "assert($('html').children('head').length == 1, 'The head
element should be a child of the html
element.');"
+ "text":
+ "The head
element should be a child of the html
element.",
+ "testString":
+ "assert($('html').children('head').length == 1, 'The head
element should be a child of the html
element.');"
},
{
- "text": "The body
element should be a child of the html
element.",
- "testString": "assert($('html').children('body').length == 1, 'The body
element should be a child of the html
element.');"
+ "text":
+ "The body
element should be a child of the html
element.",
+ "testString":
+ "assert($('html').children('body').length == 1, 'The body
element should be a child of the html
element.');"
},
{
- "text": "The head
element should wrap around the title
element.",
- "testString": "assert(code.match(/\\s*?\\s*?.*?\\s*?<\\/title>\\s*?<\\/head>/gi), 'The head
element should wrap around the title
element.');"
+ "text":
+ "The head
element should wrap around the title
element.",
+ "testString":
+ "assert(code.match(/\\s*?\\s*?.*?\\s*?<\\/title>\\s*?<\\/head>/gi), 'The head
element should wrap around the title
element.');"
},
{
- "text": "The body
element should wrap around both the h1
and p
elements.",
- "testString": "assert($('body').children('h1').length == 1 && $('body').children('p').length == 1, 'The body
element should wrap around both the h1
and p
elements.');"
+ "text":
+ "The body
element should wrap around both the h1
and p
elements.",
+ "testString":
+ "assert($('body').children('h1').length == 1 && $('body').children('p').length == 1, 'The body
element should wrap around both the h1
and p
elements.');"
}
],
"challengeType": 0,
@@ -2584,7 +2762,7 @@
"Você pode adicionar mais um nível de organização ao seu documento HTML dentro da tag html
com os elementos head
(cabeça) e body
(corpo). Qualquer código com informações sobre a sua página deve estar dentro da tag head
. Assim, qualquer código com o conteúdo da sua página (o que aparece para o usuário) deve estar dentro da tag body
.",
"Elementos de metadados, como link
, meta
, title
e style
, tipicamente aparecem dentro do elemento head
.",
"Aqui está um exemplo da estrutura de uma página:",
- "<!DOCTYPE html>
<html>
<head>
<!-- elementos de metadados -->
</head>
<body>
<!-- conteúdo da página -->
</body>
</html>
",
+ "<!DOCTYPE html>
<html>
<head>
<!-- elementos de metadados -->
</head>
<body>
<!-- conteúdo da página -->
</body>
</html>
",
"
",
"Edite o código para que tenha uma head
e um body
. O elemento head
deve incluir apenas o title
, e o elemento body
deve conter apenas o h1
e o p
."
]
diff --git a/challenges/01-responsive-web-design/css-grid.json b/challenges/01-responsive-web-design/css-grid.json
index 2f1e82f20..97dc2b05d 100644
--- a/challenges/01-responsive-web-design/css-grid.json
+++ b/challenges/01-responsive-web-design/css-grid.json
@@ -15,8 +15,10 @@
],
"tests": [
{
- "text": "container
class should have a display
property with a value of grid
.",
- "testString": "assert(code.match(/.container\\s*?{[\\s\\S]*display\\s*?:\\s*?grid\\s*?;[\\s\\S]*}/gi), 'container
class should have a display
property with a value of grid
.');"
+ "text":
+ "container
class should have a display
property with a value of grid
.",
+ "testString":
+ "assert(code.match(/.container\\s*?{[\\s\\S]*display\\s*?:\\s*?grid\\s*?;[\\s\\S]*}/gi), 'container
class should have a display
property with a value of grid
.');"
}
],
"solutions": [],
@@ -66,7 +68,7 @@
"title": "Add Columns with grid-template-columns",
"description": [
"Simply creating a grid element doesn't get you very far. You need to define the structure of the grid as well. To add some columns to the grid, use the grid-template-columns
property on a grid container as demonstrated below:",
- ".container {
display: grid;
grid-template-columns: 50px 50px;
}
",
+ ".container {
display: grid;
grid-template-columns: 50px 50px;
}
",
"This will give your grid two columns that are 50px wide each.",
"The number of parameters given to the grid-template-columns
property indicates the number of columns in the grid, and the value of each parameter indicates the width of each column.",
"
",
@@ -74,8 +76,10 @@
],
"tests": [
{
- "text": "container
class should have a grid-template-columns
property with three units of 100px
.",
- "testString": "assert(code.match(/.container\\s*?{[\\s\\S]*grid-template-columns\\s*?:\\s*?100px\\s*?100px\\s*?100px\\s*?;[\\s\\S]*}/gi), 'container
class should have a grid-template-columns
property with three units of 100px
.');"
+ "text":
+ "container
class should have a grid-template-columns
property with three units of 100px
.",
+ "testString":
+ "assert(code.match(/.container\\s*?{[\\s\\S]*grid-template-columns\\s*?:\\s*?100px\\s*?100px\\s*?100px\\s*?;[\\s\\S]*}/gi), 'container
class should have a grid-template-columns
property with three units of 100px
.');"
}
],
"solutions": [],
@@ -131,8 +135,10 @@
],
"tests": [
{
- "text": "container
class should have a grid-template-rows
property with two units of 50px
.",
- "testString": "assert(code.match(/.container\\s*?{[\\s\\S]*grid-template-rows\\s*?:\\s*?50px\\s*?50px\\s*?;[\\s\\S]*}/gi), 'container
class should have a grid-template-rows
property with two units of 50px
.');"
+ "text":
+ "container
class should have a grid-template-rows
property with two units of 50px
.",
+ "testString":
+ "assert(code.match(/.container\\s*?{[\\s\\S]*grid-template-rows\\s*?:\\s*?50px\\s*?50px\\s*?;[\\s\\S]*}/gi), 'container
class should have a grid-template-rows
property with two units of 50px
.');"
}
],
"solutions": [],
@@ -195,8 +201,10 @@
],
"tests": [
{
- "text": "container
class should have a grid-template-columns
property that has three columns with the following widths: 1fr, 100px, and 2fr
.",
- "testString": "assert(code.match(/.container\\s*?{[\\s\\S]*grid-template-columns\\s*?:\\s*?1fr\\s*?100px\\s*?2fr\\s*?;[\\s\\S]*}/gi), 'container
class should have a grid-template-columns
property that has three columns with the following widths: 1fr, 100px, and 2fr
.');"
+ "text":
+ "container
class should have a grid-template-columns
property that has three columns with the following widths: 1fr, 100px, and 2fr
.",
+ "testString":
+ "assert(code.match(/.container\\s*?{[\\s\\S]*grid-template-columns\\s*?:\\s*?1fr\\s*?100px\\s*?2fr\\s*?;[\\s\\S]*}/gi), 'container
class should have a grid-template-columns
property that has three columns with the following widths: 1fr, 100px, and 2fr
.');"
}
],
"solutions": [],
@@ -256,8 +264,10 @@
],
"tests": [
{
- "text": "container
class should have a grid-column-gap
property that has the value of 20px
.",
- "testString": "assert(code.match(/.container\\s*?{[\\s\\S]*grid-column-gap\\s*?:\\s*?20px\\s*?;[\\s\\S]*}/gi), 'container
class should have a grid-column-gap
property that has the value of 20px
.');"
+ "text":
+ "container
class should have a grid-column-gap
property that has the value of 20px
.",
+ "testString":
+ "assert(code.match(/.container\\s*?{[\\s\\S]*grid-column-gap\\s*?:\\s*?20px\\s*?;[\\s\\S]*}/gi), 'container
class should have a grid-column-gap
property that has the value of 20px
.');"
}
],
"solutions": [],
@@ -316,8 +326,10 @@
],
"tests": [
{
- "text": "container
class should have a grid-row-gap
property that has the value of 5px
.",
- "testString": "assert(code.match(/.container\\s*?{[\\s\\S]*grid-row-gap\\s*?:\\s*?5px\\s*?;[\\s\\S]*}/gi), 'container
class should have a grid-row-gap
property that has the value of 5px
.');"
+ "text":
+ "container
class should have a grid-row-gap
property that has the value of 5px
.",
+ "testString":
+ "assert(code.match(/.container\\s*?{[\\s\\S]*grid-row-gap\\s*?:\\s*?5px\\s*?;[\\s\\S]*}/gi), 'container
class should have a grid-row-gap
property that has the value of 5px
.');"
}
],
"solutions": [],
@@ -376,8 +388,10 @@
],
"tests": [
{
- "text": "container
class should have a grid-gap
property that introduces 10px
gap between the rows and 20px
gap between the columns.",
- "testString": "assert(code.match(/.container\\s*?{[\\s\\S]*grid-gap\\s*?:\\s*?10px\\s*?20px\\s*?;[\\s\\S]*}/gi), 'container
class should have a grid-gap
property that introduces 10px
gap between the rows and 20px
gap between the columns.');"
+ "text":
+ "container
class should have a grid-gap
property that introduces 10px
gap between the rows and 20px
gap between the columns.",
+ "testString":
+ "assert(code.match(/.container\\s*?{[\\s\\S]*grid-gap\\s*?:\\s*?10px\\s*?20px\\s*?;[\\s\\S]*}/gi), 'container
class should have a grid-gap
property that introduces 10px
gap between the rows and 20px
gap between the columns.');"
}
],
"solutions": [],
@@ -442,8 +456,10 @@
],
"tests": [
{
- "text": "item5
class should have a grid-column
property that has the value of 2 / 4
.",
- "testString": "assert(code.match(/.item5\\s*?{[\\s\\S]*grid-column\\s*?:\\s*?2\\s*?\\/\\s*?4\\s*?;[\\s\\S]*}/gi), 'item5
class should have a grid-column
property that has the value of 2 / 4
.');"
+ "text":
+ "item5
class should have a grid-column
property that has the value of 2 / 4
.",
+ "testString":
+ "assert(code.match(/.item5\\s*?{[\\s\\S]*grid-column\\s*?:\\s*?2\\s*?\\/\\s*?4\\s*?;[\\s\\S]*}/gi), 'item5
class should have a grid-column
property that has the value of 2 / 4
.');"
}
],
"solutions": [],
@@ -506,8 +522,10 @@
],
"tests": [
{
- "text": "item5
class should have a grid-row
property that has the value of 2 / 4
.",
- "testString": "assert(code.match(/.item5\\s*?{[\\s\\S]*grid-row\\s*?:\\s*?2\\s*?\\/\\s*?4\\s*?;[\\s\\S]*}/gi), 'item5
class should have a grid-row
property that has the value of 2 / 4
.');"
+ "text":
+ "item5
class should have a grid-row
property that has the value of 2 / 4
.",
+ "testString":
+ "assert(code.match(/.item5\\s*?{[\\s\\S]*grid-row\\s*?:\\s*?2\\s*?\\/\\s*?4\\s*?;[\\s\\S]*}/gi), 'item5
class should have a grid-row
property that has the value of 2 / 4
.');"
}
],
"solutions": [],
@@ -574,8 +592,10 @@
],
"tests": [
{
- "text": "item2
class should have a justify-self
property that has the value of center
.",
- "testString": "assert(code.match(/.item2\\s*?{[\\s\\S]*justify-self\\s*?:\\s*?center\\s*?;[\\s\\S]*}/gi), 'item2
class should have a justify-self
property that has the value of center
.');"
+ "text":
+ "item2
class should have a justify-self
property that has the value of center
.",
+ "testString":
+ "assert(code.match(/.item2\\s*?{[\\s\\S]*justify-self\\s*?:\\s*?center\\s*?;[\\s\\S]*}/gi), 'item2
class should have a justify-self
property that has the value of center
.');"
}
],
"solutions": [],
@@ -639,8 +659,10 @@
],
"tests": [
{
- "text": "item3
class should have a align-self
property that has the value of end
.",
- "testString": "assert(code.match(/.item3\\s*?{[\\s\\S]*align-self\\s*?:\\s*?end\\s*?;[\\s\\S]*}/gi), 'item3
class should have a align-self
property that has the value of end
.');"
+ "text":
+ "item3
class should have a align-self
property that has the value of end
.",
+ "testString":
+ "assert(code.match(/.item3\\s*?{[\\s\\S]*align-self\\s*?:\\s*?end\\s*?;[\\s\\S]*}/gi), 'item3
class should have a align-self
property that has the value of end
.');"
}
],
"solutions": [],
@@ -704,8 +726,10 @@
],
"tests": [
{
- "text": "container
class should have a justify-items
property that has the value of center
.",
- "testString": "assert(code.match(/.container\\s*?{[\\s\\S]*justify-items\\s*?:\\s*?center\\s*?;[\\s\\S]*}/gi), 'container
class should have a justify-items
property that has the value of center
.');"
+ "text":
+ "container
class should have a justify-items
property that has the value of center
.",
+ "testString":
+ "assert(code.match(/.container\\s*?{[\\s\\S]*justify-items\\s*?:\\s*?center\\s*?;[\\s\\S]*}/gi), 'container
class should have a justify-items
property that has the value of center
.');"
}
],
"solutions": [],
@@ -765,8 +789,10 @@
],
"tests": [
{
- "text": "container
class should have a align-items
property that has the value of end
.",
- "testString": "assert(code.match(/.container\\s*?{[\\s\\S]*align-items\\s*?:\\s*?end\\s*?;[\\s\\S]*}/gi), 'container
class should have a align-items
property that has the value of end
.');"
+ "text":
+ "container
class should have a align-items
property that has the value of end
.",
+ "testString":
+ "assert(code.match(/.container\\s*?{[\\s\\S]*align-items\\s*?:\\s*?end\\s*?;[\\s\\S]*}/gi), 'container
class should have a align-items
property that has the value of end
.');"
}
],
"solutions": [],
@@ -821,7 +847,7 @@
"title": "Divide the Grid Into an Area Template",
"description": [
"You can group cells of your grid together into an area and give the area a custom name. Do this by using grid-template-areas
on the container like this:",
- "grid-template-areas:
\"header header header\"
\"advert content content\"
\"footer footer footer\";
",
+ "grid-template-areas:
\"header header header\"
\"advert content content\"
\"footer footer footer\";
",
"The code above merges the top three cells together into an area named header
, the bottom three cells into a footer
area, and it makes two areas in the middle row; advert
and content
.",
"Note
Every word in the code represents a cell and every pair of quotation marks represent a row.",
"In addition to custom labels, you can use a period (.
) to designate an empty cell in the grid.",
@@ -830,8 +856,10 @@
],
"tests": [
{
- "text": "container
class should have a grid-template-areas
propertiy similar to the preview but has .
instead of the advert
area.",
- "testString": "assert(code.match(/.container\\s*?{[\\s\\S]*grid-template-areas\\s*?:\\s*?\"\\s*?header\\s*?header\\s*?header\\s*?\"\\s*?\"\\s*?.\\s*?content\\s*?content\\s*?\"\\s*?\"\\s*?footer\\s*?footer\\s*?footer\\s*?\"\\s*?;[\\s\\S]*}/gi), 'container
class should have a grid-template-areas
propertiy similar to the preview but has .
instead of the advert
area.');"
+ "text":
+ "container
class should have a grid-template-areas
propertiy similar to the preview but has .
instead of the advert
area.",
+ "testString":
+ "assert(code.match(/.container\\s*?{[\\s\\S]*grid-template-areas\\s*?:\\s*?\"\\s*?header\\s*?header\\s*?header\\s*?\"\\s*?\"\\s*?.\\s*?content\\s*?content\\s*?\"\\s*?\"\\s*?footer\\s*?footer\\s*?footer\\s*?\"\\s*?;[\\s\\S]*}/gi), 'container
class should have a grid-template-areas
propertiy similar to the preview but has .
instead of the advert
area.');"
}
],
"solutions": [],
@@ -896,8 +924,10 @@
],
"tests": [
{
- "text": "item5
class should have a grid-area
property that has the value of footer
.",
- "testString": "assert(code.match(/.item5\\s*?{[\\s\\S]*grid-area\\s*?:\\s*?footer\\s*?;[\\s\\S]*}/gi), 'item5
class should have a grid-area
property that has the value of footer
.');"
+ "text":
+ "item5
class should have a grid-area
property that has the value of footer
.",
+ "testString":
+ "assert(code.match(/.item5\\s*?{[\\s\\S]*grid-area\\s*?:\\s*?footer\\s*?;[\\s\\S]*}/gi), 'item5
class should have a grid-area
property that has the value of footer
.');"
}
],
"solutions": [],
@@ -968,8 +998,10 @@
],
"tests": [
{
- "text": "item5
class should have a grid-area
property that has the value of 3/1/4/4
.",
- "testString": "assert(code.match(/.item5\\s*?{[\\s\\S]*grid-area\\s*?:\\s*?3\\s*?\\/\\s*?1\\s*?\\/\\s*?4\\s*?\\/\\s*?4\\s*?;[\\s\\S]*}/gi), 'item5
class should have a grid-area
property that has the value of 3/1/4/4
.');"
+ "text":
+ "item5
class should have a grid-area
property that has the value of 3/1/4/4
.",
+ "testString":
+ "assert(code.match(/.item5\\s*?{[\\s\\S]*grid-area\\s*?:\\s*?3\\s*?\\/\\s*?1\\s*?\\/\\s*?4\\s*?\\/\\s*?4\\s*?;[\\s\\S]*}/gi), 'item5
class should have a grid-area
property that has the value of 3/1/4/4
.');"
}
],
"solutions": [],
@@ -1040,8 +1072,10 @@
],
"tests": [
{
- "text": "container
class should have a grid-template-columns
property that is set to repeat 3 columns with the width of 1fr
.",
- "testString": "assert(code.match(/.container\\s*?{[\\s\\S]*grid-template-columns\\s*?:\\s*?repeat\\s*?\\(\\s*?3\\s*?,\\s*?1fr\\s*?\\)\\s*?;[\\s\\S]*}/gi), 'container
class should have a grid-template-columns
property that is set to repeat 3 columns with the width of 1fr
.');"
+ "text":
+ "container
class should have a grid-template-columns
property that is set to repeat 3 columns with the width of 1fr
.",
+ "testString":
+ "assert(code.match(/.container\\s*?{[\\s\\S]*grid-template-columns\\s*?:\\s*?repeat\\s*?\\(\\s*?3\\s*?,\\s*?1fr\\s*?\\)\\s*?;[\\s\\S]*}/gi), 'container
class should have a grid-template-columns
property that is set to repeat 3 columns with the width of 1fr
.');"
}
],
"solutions": [],
@@ -1103,8 +1137,10 @@
],
"tests": [
{
- "text": "container
class should have a grid-template-columns
property that is set to repeat 3 columns with the minimum width of 90px
and maximum width of 1fr
.",
- "testString": "assert(code.match(/.container\\s*?{[\\s\\S]*grid-template-columns\\s*?:\\s*?repeat\\s*?\\(\\s*?3\\s*?,\\s*?minmax\\s*?\\(\\s*?90px\\s*?,\\s*?1fr\\s*?\\)\\s*?\\)\\s*?;[\\s\\S]*}/gi), 'container
class should have a grid-template-columns
property that is set to repeat 3 columns with the minimum width of 90px
and maximum width of 1fr
.');"
+ "text":
+ "container
class should have a grid-template-columns
property that is set to repeat 3 columns with the minimum width of 90px
and maximum width of 1fr
.",
+ "testString":
+ "assert(code.match(/.container\\s*?{[\\s\\S]*grid-template-columns\\s*?:\\s*?repeat\\s*?\\(\\s*?3\\s*?,\\s*?minmax\\s*?\\(\\s*?90px\\s*?,\\s*?1fr\\s*?\\)\\s*?\\)\\s*?;[\\s\\S]*}/gi), 'container
class should have a grid-template-columns
property that is set to repeat 3 columns with the minimum width of 90px
and maximum width of 1fr
.');"
}
],
"solutions": [],
@@ -1168,8 +1204,10 @@
],
"tests": [
{
- "text": "container
class should have a grid-template-columns
property with repeat
and auto-fill
that will fill the grid with columns that have a minimum width of 60px
and maximum of 1fr
.",
- "testString": "assert(code.match(/.container\\s*?{[\\s\\S]*grid-template-columns\\s*?:\\s*?repeat\\s*?\\(\\s*?auto-fill\\s*?,\\s*?minmax\\s*?\\(\\s*?60px\\s*?,\\s*?1fr\\s*?\\)\\s*?\\)\\s*?;[\\s\\S]*}/gi), 'container
class should have a grid-template-columns
property with repeat
and auto-fill
that will fill the grid with columns that have a minimum width of 60px
and maximum of 1fr
.');"
+ "text":
+ "container
class should have a grid-template-columns
property with repeat
and auto-fill
that will fill the grid with columns that have a minimum width of 60px
and maximum of 1fr
.",
+ "testString":
+ "assert(code.match(/.container\\s*?{[\\s\\S]*grid-template-columns\\s*?:\\s*?repeat\\s*?\\(\\s*?auto-fill\\s*?,\\s*?minmax\\s*?\\(\\s*?60px\\s*?,\\s*?1fr\\s*?\\)\\s*?\\)\\s*?;[\\s\\S]*}/gi), 'container
class should have a grid-template-columns
property with repeat
and auto-fill
that will fill the grid with columns that have a minimum width of 60px
and maximum of 1fr
.');"
}
],
"solutions": [],
@@ -1247,8 +1285,10 @@
],
"tests": [
{
- "text": "container2
class should have a grid-template-columns
property with repeat
and auto-fit
that will fill the grid with columns that have a minimum width of 60px
and maximum of 1fr
.",
- "testString": "assert(code.match(/.container\\s*?{[\\s\\S]*grid-template-columns\\s*?:\\s*?repeat\\s*?\\(\\s*?auto-fit\\s*?,\\s*?minmax\\s*?\\(\\s*?60px\\s*?,\\s*?1fr\\s*?\\)\\s*?\\)\\s*?;[\\s\\S]*}/gi), 'container2
class should have a grid-template-columns
property with repeat
and auto-fit
that will fill the grid with columns that have a minimum width of 60px
and maximum of 1fr
.');"
+ "text":
+ "container2
class should have a grid-template-columns
property with repeat
and auto-fit
that will fill the grid with columns that have a minimum width of 60px
and maximum of 1fr
.",
+ "testString":
+ "assert(code.match(/.container\\s*?{[\\s\\S]*grid-template-columns\\s*?:\\s*?repeat\\s*?\\(\\s*?auto-fit\\s*?,\\s*?minmax\\s*?\\(\\s*?60px\\s*?,\\s*?1fr\\s*?\\)\\s*?\\)\\s*?;[\\s\\S]*}/gi), 'container2
class should have a grid-template-columns
property with repeat
and auto-fit
that will fill the grid with columns that have a minimum width of 60px
and maximum of 1fr
.');"
}
],
"solutions": [],
@@ -1327,8 +1367,10 @@
],
"tests": [
{
- "text": "When the viewport is 400px
or more, container
class should have a grid-template-areas
property in which the footer and header areas occupy the top and bottom rows respectively and advert and content occupy the left and right columns of the middle row.",
- "testString": "assert(code.match(/@media\\s*?\\(\\s*?min-width\\s*?:\\s*?400px\\s*?\\)[\\s\\S]*.container\\s*?{[\\s\\S]*grid-template-areas\\s*?:\\s*?\"\\s*?header\\s*?header\\s*?\"\\s*?\"\\s*?advert\\s*?content\\s*?\"\\s*?\"\\s*?footer\\s*?footer\\s*?\"\\s*?;[\\s\\S]*}/gi), 'When the viewport is 400px
or more, container
class should have a grid-template-areas
property in which the footer and header areas occupy the top and bottom rows respectively and advert and content occupy the left and right columns of the middle row.');"
+ "text":
+ "When the viewport is 400px
or more, container
class should have a grid-template-areas
property in which the footer and header areas occupy the top and bottom rows respectively and advert and content occupy the left and right columns of the middle row.",
+ "testString":
+ "assert(code.match(/@media\\s*?\\(\\s*?min-width\\s*?:\\s*?400px\\s*?\\)[\\s\\S]*.container\\s*?{[\\s\\S]*grid-template-areas\\s*?:\\s*?\"\\s*?header\\s*?header\\s*?\"\\s*?\"\\s*?advert\\s*?content\\s*?\"\\s*?\"\\s*?footer\\s*?footer\\s*?\"\\s*?;[\\s\\S]*}/gi), 'When the viewport is 400px
or more, container
class should have a grid-template-areas
property in which the footer and header areas occupy the top and bottom rows respectively and advert and content occupy the left and right columns of the middle row.');"
}
],
"solutions": [],
@@ -1427,12 +1469,16 @@
],
"tests": [
{
- "text": "item3
class should have a grid-template-columns
property with auto
and 1fr
as values.",
- "testString": "assert(code.match(/.item3\\s*?{[\\s\\S]*grid-template-columns\\s*?:\\s*?auto\\s*?1fr\\s*?;[\\s\\S]*}/gi), 'item3
class should have a grid-template-columns
property with auto
and 1fr
as values.');"
+ "text":
+ "item3
class should have a grid-template-columns
property with auto
and 1fr
as values.",
+ "testString":
+ "assert(code.match(/.item3\\s*?{[\\s\\S]*grid-template-columns\\s*?:\\s*?auto\\s*?1fr\\s*?;[\\s\\S]*}/gi), 'item3
class should have a grid-template-columns
property with auto
and 1fr
as values.');"
},
{
- "text": "item3
class should have a display
property with the value of grid
.",
- "testString": "assert(code.match(/.item3\\s*?{[\\s\\S]*display\\s*?:\\s*?grid\\s*?;[\\s\\S]*}/gi), 'item3
class should have a display
property with the value of grid
.');"
+ "text":
+ "item3
class should have a display
property with the value of grid
.",
+ "testString":
+ "assert(code.match(/.item3\\s*?{[\\s\\S]*display\\s*?:\\s*?grid\\s*?;[\\s\\S]*}/gi), 'item3
class should have a display
property with the value of grid
.');"
}
],
"solutions": [],
diff --git a/challenges/01-responsive-web-design/responsive-web-design.json b/challenges/01-responsive-web-design/responsive-web-design.json
index ace65c742..a25c4a1e7 100644
--- a/challenges/01-responsive-web-design/responsive-web-design.json
+++ b/challenges/01-responsive-web-design/responsive-web-design.json
@@ -20,12 +20,16 @@
],
"tests": [
{
- "text": "Your p
element should have the font-size
of 10px when the device height
is less than or equal to 800px.",
- "testString": "assert($('p').css('font-size') == '10px', 'Your p
element should have the font-size
of 10px when the device height
is less than or equal to 800px.');"
+ "text":
+ "Your p
element should have the font-size
of 10px when the device height
is less than or equal to 800px.",
+ "testString":
+ "assert($('p').css('font-size') == '10px', 'Your p
element should have the font-size
of 10px when the device height
is less than or equal to 800px.');"
},
{
- "text": "Declare a @media
query for devices with a height
less than or equal to 800px.",
- "testString": "assert(code.match(/@media\\s?\\(max-height:\\s*?800px\\)/g), 'Declare a @media
query for devices with a height
less than or equal to 800px.');"
+ "text":
+ "Declare a @media
query for devices with a height
less than or equal to 800px.",
+ "testString":
+ "assert(code.match(/@media\\s?\\(max-height:\\s*?800px\\)/g), 'Declare a @media
query for devices with a height
less than or equal to 800px.');"
}
],
"releasedOn": "Feb 17, 2017",
@@ -75,23 +79,29 @@
"Making images responsive with CSS is actually very simple. Instead of applying an absolute width to an element:",
"img { width: 720px; }
",
"You can use:",
- "img {
max-width: 100%;
display: block;
height: auto;
}
",
+ "img {
max-width: 100%;
display: block;
height: auto;
}
",
"The max-width
property of 100% scales the image to fit the width of its container, but the image won't stretch wider than its original width. Setting the display
property to block changes the image from an inline element (its default), to a block element on its own line. The height
property of auto keeps the original aspect ratio of the image.",
"
",
"Add style rules for the img
tag to make it responsive to the size of its container. It should display as a block-level element, it should fit the full width of its container without stretching, and it should keep its original aspect ratio."
],
"tests": [
{
- "text": "Your img
tag should have a max-width
set to 100%.",
- "testString": "assert(code.match(/max-width:\\s*?100%;/g), 'Your img
tag should have a max-width
set to 100%.');"
+ "text":
+ "Your img
tag should have a max-width
set to 100%.",
+ "testString":
+ "assert(code.match(/max-width:\\s*?100%;/g), 'Your img
tag should have a max-width
set to 100%.');"
},
{
- "text": "Your img
tag should have a display
set to block.",
- "testString": "assert($('img').css('display') == 'block', 'Your img
tag should have a display
set to block.');"
+ "text":
+ "Your img
tag should have a display
set to block.",
+ "testString":
+ "assert($('img').css('display') == 'block', 'Your img
tag should have a display
set to block.');"
},
{
- "text": "Your img
tag should have a height
set to auto.",
- "testString": "assert(code.match(/height:\\s*?auto;/g), 'Your img
tag should have a height
set to auto.');"
+ "text":
+ "Your img
tag should have a height
set to auto.",
+ "testString":
+ "assert(code.match(/height:\\s*?auto;/g), 'Your img
tag should have a height
set to auto.');"
}
],
"releasedOn": "Feb 17, 2017",
@@ -105,7 +115,7 @@
"Fazer com que imagens sejam responsivas é muito simples com CSS. Ao invés de aplicar uma largura absoluta a um elemento:",
"img { width: 720px; }
",
"Você pode usar:",
- "img {
max-width: 100%;
display: block;
height: auto;
}
",
+ "img {
max-width: 100%;
display: block;
height: auto;
}
",
"A propriedade max-width
em 100% ajusta o tamanho da imagem para preencher a largura de seu container, mas a imagem não irá esticar mais que sua largura original. Ajustando a propriedade display
como block muda imagem de elemento inline (o padrão) para um elemento block com uma linha própria. A propriedade height
na configuração auto mantem a proporção original da imagem.",
"
",
"Adicione regras de estilo para a tag img
para torná-la responsiva com relação ao tamanho do seu container. Ela deve ser exibida como um elemento de nível block, e deve preencher toda a largura de seu container sem esticar, mantendo as proporções originais."
@@ -135,18 +145,22 @@
"description": [
"The simplest way to make your images appear \"retina\" (and optimize them for retina displays) is to define their width
and height
values as only half of what the original file is.",
"Here is an example of an image that is only using half of the original height and width:",
- "<style>
img { height: 250px; width: 250px; }
</style>
<img src="coolPic500x500" alt="A most excellent picture">
",
+ "<style>
img { height: 250px; width: 250px; }
</style>
<img src="coolPic500x500" alt="A most excellent picture">
",
"
",
"Set the width
and height
of the img
tag to half of their original values. In this case, both the original height
and the original width
are 200px."
],
"tests": [
{
- "text": "Your img
tag should have a width
of 100 pixels.",
- "testString": "assert($('img').css('width') == '100px', 'Your img
tag should have a width
of 100 pixels.');"
+ "text":
+ "Your img
tag should have a width
of 100 pixels.",
+ "testString":
+ "assert($('img').css('width') == '100px', 'Your img
tag should have a width
of 100 pixels.');"
},
{
- "text": "Your img
tag should have a height
of 100 pixels.",
- "testString": "assert($('img').css('height') == '100px', 'Your img
tag should have a height
of 100 pixels.');"
+ "text":
+ "Your img
tag should have a height
of 100 pixels.",
+ "testString":
+ "assert($('img').css('height') == '100px', 'Your img
tag should have a height
of 100 pixels.');"
}
],
"releasedOn": "Feb 17, 2017",
@@ -159,7 +173,7 @@
"description": [
"A maneira mais simples de fazer com que suas imagens tenham uma aparência \"retina\" (e otimizadas para telas retina) é definindo seus valores de width
e height
como somente metade do tamanho original dos arquivos.",
"Segue um exemplo de imagem que possui somente metade dos valores originais de altura e largura:",
- "<style>
img { height: 250px; width: 250px; }
</style>
<img src="coolPic500x500" alt="A most excellent picture">
",
+ "<style>
img { height: 250px; width: 250px; }
</style>
<img src="coolPic500x500" alt="A most excellent picture">
",
"
",
"Configure os valores de width
e height
da tag img
como metade do seu tamanho original. Nesse caso, o valor original de height
e o valor original de width
são de 200px."
]
@@ -194,12 +208,16 @@
],
"tests": [
{
- "text": "Your h2
tag should have a width
of 80vw.",
- "testString": "assert(code.match(/h2\\s*?{\\s*?width:\\s*?80vw;\\s*?}/g), 'Your h2
tag should have a width
of 80vw.');"
+ "text":
+ "Your h2
tag should have a width
of 80vw.",
+ "testString":
+ "assert(code.match(/h2\\s*?{\\s*?width:\\s*?80vw;\\s*?}/g), 'Your h2
tag should have a width
of 80vw.');"
},
{
- "text": "Your p
tag should have a width
of 75vmin.",
- "testString": "assert(code.match(/p\\s*?{\\s*?width:\\s*?75vmin;\\s*?}/g), 'Your p
tag should have a width
of 75vmin.');"
+ "text":
+ "Your p
tag should have a width
of 75vmin.",
+ "testString":
+ "assert(code.match(/p\\s*?{\\s*?width:\\s*?75vmin;\\s*?}/g), 'Your p
tag should have a width
of 75vmin.');"
}
],
"releasedOn": "Feb 17, 2017",
@@ -237,4 +255,4 @@
}
}
]
-}
\ No newline at end of file
+}
diff --git a/challenges/02-javascript-algorithms-and-data-structures/basic-data-structures.json b/challenges/02-javascript-algorithms-and-data-structures/basic-data-structures.json
index c858270f7..18bc603e4 100644
--- a/challenges/02-javascript-algorithms-and-data-structures/basic-data-structures.json
+++ b/challenges/02-javascript-algorithms-and-data-structures/basic-data-structures.json
@@ -12,30 +12,38 @@
"let simpleArray = ['one', 2, 'three’, true, false, undefined, null];
console.log(simpleArray.length);
// logs 7
",
"All array's have a length property, which as shown above, can be very easily accessed with the syntax Array.length
.",
"A more complex implementation of an array can be seen below. This is known as a multi-dimensional array, or an array that contains other arrays. Notice that this array also contains JavaScript objects, which we will examine very closely in our next section, but for now, all you need to know is that arrays are also capable of storing complex objects.",
- "let complexArray = [
[
{
one: 1,
two: 2
},
{
three: 3,
four: 4
}
],
[
{
a: \"a\",
b: \"b\"
},
{
c: \"c\",
d: “d”
}
]
];
",
+ "let complexArray = [
[
{
one: 1,
two: 2
},
{
three: 3,
four: 4
}
],
[
{
a: \"a\",
b: \"b\"
},
{
c: \"c\",
d: “d”
}
]
];
",
"
",
"We have defined a variable called yourArray
. Complete the statement by assigning an array of at least 5 elements in length to the yourArray
variable. Your array should contain at least one string, one number, and one boolean."
],
"tests": [
{
"text": "yourArray is an array",
- "testString": "assert.strictEqual(Array.isArray(yourArray), true, 'yourArray is an array');"
+ "testString":
+ "assert.strictEqual(Array.isArray(yourArray), true, 'yourArray is an array');"
},
{
"text": "yourArray
is at least 5 elements long",
- "testString": "assert.isAtLeast(yourArray.length, 5, 'yourArray
is at least 5 elements long');"
+ "testString":
+ "assert.isAtLeast(yourArray.length, 5, 'yourArray
is at least 5 elements long');"
},
{
- "text": "yourArray
contains at least one boolean
",
- "testString": "assert(yourArray.filter( el => typeof el === 'boolean').length >= 1, 'yourArray
contains at least one boolean
');"
+ "text":
+ "yourArray
contains at least one boolean
",
+ "testString":
+ "assert(yourArray.filter( el => typeof el === 'boolean').length >= 1, 'yourArray
contains at least one boolean
');"
},
{
- "text": "yourArray
contains at least one number
",
- "testString": "assert(yourArray.filter( el => typeof el === 'number').length >= 1, 'yourArray
contains at least one number
');"
+ "text":
+ "yourArray
contains at least one number
",
+ "testString":
+ "assert(yourArray.filter( el => typeof el === 'number').length >= 1, 'yourArray
contains at least one number
');"
},
{
- "text": "yourArray
contains at least one string
",
- "testString": "assert(yourArray.filter( el => typeof el === 'string').length >= 1, 'yourArray
contains at least one string
');"
+ "text":
+ "yourArray
contains at least one string
",
+ "testString":
+ "assert(yourArray.filter( el => typeof el === 'string').length >= 1, 'yourArray
contains at least one string
');"
}
],
"releasedOn": "Feb 17, 2017",
@@ -47,9 +55,7 @@
"key": "indexjs",
"ext": "js",
"name": "index",
- "contents": [
- "let yourArray; // change this line"
- ],
+ "contents": ["let yourArray; // change this line"],
"head": [],
"tail": []
}
@@ -75,19 +81,24 @@
"tests": [
{
"text": "myArray[0]
is equal to \"a\"
",
- "testString": "assert.strictEqual(myArray[0], \"a\", 'myArray[0]
is equal to \"a\"
');"
+ "testString":
+ "assert.strictEqual(myArray[0], \"a\", 'myArray[0]
is equal to \"a\"
');"
},
{
- "text": "myArray[1]
is no longer set to \"b\"
",
- "testString": "assert.notStrictEqual(myArray[1], \"b\", 'myArray[1]
is no longer set to \"b\"
');"
+ "text":
+ "myArray[1]
is no longer set to \"b\"
",
+ "testString":
+ "assert.notStrictEqual(myArray[1], \"b\", 'myArray[1]
is no longer set to \"b\"
');"
},
{
"text": "myArray[2]
is equal to \"c\"
",
- "testString": "assert.strictEqual(myArray[2], \"c\", 'myArray[2]
is equal to \"c\"
');"
+ "testString":
+ "assert.strictEqual(myArray[2], \"c\", 'myArray[2]
is equal to \"c\"
');"
},
{
"text": "myArray[3]
is equal to \"d\"
",
- "testString": "assert.strictEqual(myArray[3], \"d\", 'myArray[3]
is equal to \"d\"
');"
+ "testString":
+ "assert.strictEqual(myArray[3], \"d\", 'myArray[3]
is equal to \"d\"
');"
}
],
"solutions": [],
@@ -123,16 +134,22 @@
],
"tests": [
{
- "text": "mixedNumbers([\"IV\", 5, \"six\"])
should now return [\"I\", 2, \"three\", \"IV\", 5, \"six\", 7, \"VIII\", 9]
",
- "testString": "assert.deepEqual(mixedNumbers(['IV', 5, 'six']), ['I', 2, 'three', 'IV', 5, 'six', 7, 'VIII', 9], 'mixedNumbers([\"IV\", 5, \"six\"])
should now return [\"I\", 2, \"three\", \"IV\", 5, \"six\", 7, \"VIII\", 9]
');"
+ "text":
+ "mixedNumbers([\"IV\", 5, \"six\"])
should now return [\"I\", 2, \"three\", \"IV\", 5, \"six\", 7, \"VIII\", 9]
",
+ "testString":
+ "assert.deepEqual(mixedNumbers(['IV', 5, 'six']), ['I', 2, 'three', 'IV', 5, 'six', 7, 'VIII', 9], 'mixedNumbers([\"IV\", 5, \"six\"])
should now return [\"I\", 2, \"three\", \"IV\", 5, \"six\", 7, \"VIII\", 9]
');"
},
{
- "text": "The mixedNumbers
function should utilize the push()
method",
- "testString": "assert.notStrictEqual(mixedNumbers.toString().search(/\\.push\\(/), -1, 'The mixedNumbers
function should utilize the push()
method');"
+ "text":
+ "The mixedNumbers
function should utilize the push()
method",
+ "testString":
+ "assert.notStrictEqual(mixedNumbers.toString().search(/\\.push\\(/), -1, 'The mixedNumbers
function should utilize the push()
method');"
},
{
- "text": "The mixedNumbers
function should utilize the unshift()
method",
- "testString": "assert.notStrictEqual(mixedNumbers.toString().search(/\\.unshift\\(/), -1, 'The mixedNumbers
function should utilize the unshift()
method');"
+ "text":
+ "The mixedNumbers
function should utilize the unshift()
method",
+ "testString":
+ "assert.notStrictEqual(mixedNumbers.toString().search(/\\.unshift\\(/), -1, 'The mixedNumbers
function should utilize the unshift()
method');"
}
],
"releasedOn": "Feb 17, 2017",
@@ -174,16 +191,22 @@
],
"tests": [
{
- "text": "popShift([\"challenge\", \"is\", \"not\", \"complete\"])
should return [\"challenge\", \"complete\"]
",
- "testString": "assert.deepEqual(popShift(['challenge', 'is', 'not', 'complete']), [\"challenge\", \"complete\"], 'popShift([\"challenge\", \"is\", \"not\", \"complete\"])
should return [\"challenge\", \"complete\"]
');"
+ "text":
+ "popShift([\"challenge\", \"is\", \"not\", \"complete\"])
should return [\"challenge\", \"complete\"]
",
+ "testString":
+ "assert.deepEqual(popShift(['challenge', 'is', 'not', 'complete']), [\"challenge\", \"complete\"], 'popShift([\"challenge\", \"is\", \"not\", \"complete\"])
should return [\"challenge\", \"complete\"]
');"
},
{
- "text": "The popShift
function should utilize the pop()
method",
- "testString": "assert.notStrictEqual(popShift.toString().search(/\\.pop\\(/), -1, 'The popShift
function should utilize the pop()
method');"
+ "text":
+ "The popShift
function should utilize the pop()
method",
+ "testString":
+ "assert.notStrictEqual(popShift.toString().search(/\\.pop\\(/), -1, 'The popShift
function should utilize the pop()
method');"
},
{
- "text": "The popShift
function should utilize the shift()
method",
- "testString": "assert.notStrictEqual(popShift.toString().search(/\\.shift\\(/), -1, 'The popShift
function should utilize the shift()
method');"
+ "text":
+ "The popShift
function should utilize the shift()
method",
+ "testString":
+ "assert.notStrictEqual(popShift.toString().search(/\\.shift\\(/), -1, 'The popShift
function should utilize the shift()
method');"
}
],
"releasedOn": "Feb 17, 2017",
@@ -225,11 +248,14 @@
"tests": [
{
"text": "sumOfTen
should return 10",
- "testString": "assert.strictEqual(sumOfTen([2, 5, 1, 5, 2, 1]), 10, 'sumOfTen
should return 10');"
+ "testString":
+ "assert.strictEqual(sumOfTen([2, 5, 1, 5, 2, 1]), 10, 'sumOfTen
should return 10');"
},
{
- "text": "The sumOfTen
function should utilize the splice()
method",
- "testString": "assert.notStrictEqual(sumOfTen.toString().search(/\\.splice\\(/), -1, 'The sumOfTen
function should utilize the splice()
method');"
+ "text":
+ "The sumOfTen
function should utilize the splice()
method",
+ "testString":
+ "assert.notStrictEqual(sumOfTen.toString().search(/\\.splice\\(/), -1, 'The sumOfTen
function should utilize the splice()
method');"
}
],
"releasedOn": "Feb 17, 2017",
@@ -269,20 +295,27 @@
],
"tests": [
{
- "text": "htmlColorNames
should return [\"DarkSalmon\", \"BlanchedAlmond\", \"LavenderBlush\", \"PaleTurqoise\", \"FireBrick\"]
",
- "testString": "assert.deepEqual(htmlColorNames(['DarkGoldenRod', 'WhiteSmoke', 'LavenderBlush', 'PaleTurqoise', 'FireBrick']), ['DarkSalmon', 'BlanchedAlmond', 'LavenderBlush', 'PaleTurqoise', 'FireBrick'], 'htmlColorNames
should return [\"DarkSalmon\", \"BlanchedAlmond\", \"LavenderBlush\", \"PaleTurqoise\", \"FireBrick\"]
');"
+ "text":
+ "htmlColorNames
should return [\"DarkSalmon\", \"BlanchedAlmond\", \"LavenderBlush\", \"PaleTurqoise\", \"FireBrick\"]
",
+ "testString":
+ "assert.deepEqual(htmlColorNames(['DarkGoldenRod', 'WhiteSmoke', 'LavenderBlush', 'PaleTurqoise', 'FireBrick']), ['DarkSalmon', 'BlanchedAlmond', 'LavenderBlush', 'PaleTurqoise', 'FireBrick'], 'htmlColorNames
should return [\"DarkSalmon\", \"BlanchedAlmond\", \"LavenderBlush\", \"PaleTurqoise\", \"FireBrick\"]
');"
},
{
- "text": "The htmlColorNames
function should utilize the splice()
method",
- "testString": "assert(/.splice/.test(code), 'The htmlColorNames
function should utilize the splice()
method');"
+ "text":
+ "The htmlColorNames
function should utilize the splice()
method",
+ "testString":
+ "assert(/.splice/.test(code), 'The htmlColorNames
function should utilize the splice()
method');"
},
{
- "text": "You should not use shift()
or unshift()
.",
- "testString": "assert(!/shift|unshift/.test(code), 'You should not use shift()
or unshift()
.');"
+ "text":
+ "You should not use shift()
or unshift()
.",
+ "testString":
+ "assert(!/shift|unshift/.test(code), 'You should not use shift()
or unshift()
.');"
},
{
"text": "You should not use array bracket notation.",
- "testString": "assert(!/\\[\\d\\]\\s*=/.test(code), 'You should not use array bracket notation.');"
+ "testString":
+ "assert(!/\\[\\d\\]\\s*=/.test(code), 'You should not use array bracket notation.');"
}
],
"releasedOn": "Feb 17, 2017",
@@ -322,12 +355,16 @@
],
"tests": [
{
- "text": "forecast
should return [\"warm\", \"sunny\"]",
- "testString": "assert.deepEqual(forecast(['cold', 'rainy', 'warm', 'sunny', 'cool', 'thunderstorms']), ['warm', 'sunny'], 'forecast
should return [\"warm\", \"sunny\"]');"
+ "text":
+ "forecast
should return [\"warm\", \"sunny\"]",
+ "testString":
+ "assert.deepEqual(forecast(['cold', 'rainy', 'warm', 'sunny', 'cool', 'thunderstorms']), ['warm', 'sunny'], 'forecast
should return [\"warm\", \"sunny\"]');"
},
{
- "text": "The forecast
function should utilize the slice()
method",
- "testString": "assert(/\\.slice\\(/.test(code), 'The forecast
function should utilize the slice()
method');"
+ "text":
+ "The forecast
function should utilize the slice()
method",
+ "testString":
+ "assert(/\\.slice\\(/.test(code), 'The forecast
function should utilize the slice()
method');"
}
],
"releasedOn": "Feb 17, 2017",
@@ -366,24 +403,34 @@
],
"tests": [
{
- "text": "copyMachine([true, false, true], 2)
should return [[true, false, true], [true, false, true]]
",
- "testString": "assert.deepEqual(copyMachine([true, false, true], 2), [[true, false, true], [true, false, true]], 'copyMachine([true, false, true], 2)
should return [[true, false, true], [true, false, true]]
');"
+ "text":
+ "copyMachine([true, false, true], 2)
should return [[true, false, true], [true, false, true]]
",
+ "testString":
+ "assert.deepEqual(copyMachine([true, false, true], 2), [[true, false, true], [true, false, true]], 'copyMachine([true, false, true], 2)
should return [[true, false, true], [true, false, true]]
');"
},
{
- "text": "copyMachine([1, 2, 3], 5)
should return [[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]]
",
- "testString": "assert.deepEqual(copyMachine([1, 2, 3], 5), [[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]], 'copyMachine([1, 2, 3], 5)
should return [[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]]
');"
+ "text":
+ "copyMachine([1, 2, 3], 5)
should return [[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]]
",
+ "testString":
+ "assert.deepEqual(copyMachine([1, 2, 3], 5), [[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]], 'copyMachine([1, 2, 3], 5)
should return [[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]]
');"
},
{
- "text": "copyMachine([true, true, null], 1)
should return [[true, true, null]]
",
- "testString": "assert.deepEqual(copyMachine([true, true, null], 1), [[true, true, null]], 'copyMachine([true, true, null], 1)
should return [[true, true, null]]
');"
+ "text":
+ "copyMachine([true, true, null], 1)
should return [[true, true, null]]
",
+ "testString":
+ "assert.deepEqual(copyMachine([true, true, null], 1), [[true, true, null]], 'copyMachine([true, true, null], 1)
should return [[true, true, null]]
');"
},
{
- "text": "copyMachine([\"it works\"], 3)
should return [[\"it works\"], [\"it works\"], [\"it works\"]]
",
- "testString": "assert.deepEqual(copyMachine(['it works'], 3), [['it works'], ['it works'], ['it works']], 'copyMachine([\"it works\"], 3)
should return [[\"it works\"], [\"it works\"], [\"it works\"]]
');"
+ "text":
+ "copyMachine([\"it works\"], 3)
should return [[\"it works\"], [\"it works\"], [\"it works\"]]
",
+ "testString":
+ "assert.deepEqual(copyMachine(['it works'], 3), [['it works'], ['it works'], ['it works']], 'copyMachine([\"it works\"], 3)
should return [[\"it works\"], [\"it works\"], [\"it works\"]]
');"
},
{
- "text": "The copyMachine
function should utilize the spread operator
with array arr
",
- "testString": "assert.notStrictEqual(copyMachine.toString().indexOf('.concat(_toConsumableArray(arr))'), -1, 'The copyMachine
function should utilize the spread operator
with array arr
');"
+ "text":
+ "The copyMachine
function should utilize the spread operator
with array arr
",
+ "testString":
+ "assert.notStrictEqual(copyMachine.toString().indexOf('.concat(_toConsumableArray(arr))'), -1, 'The copyMachine
function should utilize the spread operator
with array arr
');"
}
],
"releasedOn": "Feb 17, 2017",
@@ -427,12 +474,16 @@
],
"tests": [
{
- "text": "spreadOut
should return [\"learning\", \"to\", \"code\", \"is\", \"fun\"]
",
- "testString": "assert.deepEqual(spreadOut(), ['learning', 'to', 'code', 'is', 'fun'], 'spreadOut
should return [\"learning\", \"to\", \"code\", \"is\", \"fun\"]
');"
+ "text":
+ "spreadOut
should return [\"learning\", \"to\", \"code\", \"is\", \"fun\"]
",
+ "testString":
+ "assert.deepEqual(spreadOut(), ['learning', 'to', 'code', 'is', 'fun'], 'spreadOut
should return [\"learning\", \"to\", \"code\", \"is\", \"fun\"]
');"
},
{
- "text": "The spreadOut
function should utilize spread syntax",
- "testString": "assert.notStrictEqual(spreadOut.toString().search(/[...]/), -1, 'The spreadOut
function should utilize spread syntax');"
+ "text":
+ "The spreadOut
function should utilize spread syntax",
+ "testString":
+ "assert.notStrictEqual(spreadOut.toString().search(/[...]/), -1, 'The spreadOut
function should utilize spread syntax');"
}
],
"releasedOn": "Feb 17, 2017",
@@ -471,24 +522,34 @@
],
"tests": [
{
- "text": "quickCheck([\"squash\", \"onions\", \"shallots\"], \"mushrooms\")
should return false
",
- "testString": "assert.strictEqual(quickCheck(['squash', 'onions', 'shallots'], 'mushrooms'), false, 'quickCheck([\"squash\", \"onions\", \"shallots\"], \"mushrooms\")
should return false
');"
+ "text":
+ "quickCheck([\"squash\", \"onions\", \"shallots\"], \"mushrooms\")
should return false
",
+ "testString":
+ "assert.strictEqual(quickCheck(['squash', 'onions', 'shallots'], 'mushrooms'), false, 'quickCheck([\"squash\", \"onions\", \"shallots\"], \"mushrooms\")
should return false
');"
},
{
- "text": "quickCheck([\"squash\", \"onions\", \"shallots\"], \"onions\")
should return true
",
- "testString": "assert.strictEqual(quickCheck(['squash', 'onions', 'shallots'], 'onions'), true, 'quickCheck([\"squash\", \"onions\", \"shallots\"], \"onions\")
should return true
');"
+ "text":
+ "quickCheck([\"squash\", \"onions\", \"shallots\"], \"onions\")
should return true
",
+ "testString":
+ "assert.strictEqual(quickCheck(['squash', 'onions', 'shallots'], 'onions'), true, 'quickCheck([\"squash\", \"onions\", \"shallots\"], \"onions\")
should return true
');"
},
{
- "text": "quickCheck([3, 5, 9, 125, 45, 2], 125)
should return true
",
- "testString": "assert.strictEqual(quickCheck([3, 5, 9, 125, 45, 2], 125), true, 'quickCheck([3, 5, 9, 125, 45, 2], 125)
should return true
');"
+ "text":
+ "quickCheck([3, 5, 9, 125, 45, 2], 125)
should return true
",
+ "testString":
+ "assert.strictEqual(quickCheck([3, 5, 9, 125, 45, 2], 125), true, 'quickCheck([3, 5, 9, 125, 45, 2], 125)
should return true
');"
},
{
- "text": "quickCheck([true, false, false], undefined)
should return false
",
- "testString": "assert.strictEqual(quickCheck([true, false, false], undefined), false, 'quickCheck([true, false, false], undefined)
should return false
');"
+ "text":
+ "quickCheck([true, false, false], undefined)
should return false
",
+ "testString":
+ "assert.strictEqual(quickCheck([true, false, false], undefined), false, 'quickCheck([true, false, false], undefined)
should return false
');"
},
{
- "text": "The quickCheck
function should utilize the indexOf()
method",
- "testString": "assert.notStrictEqual(quickCheck.toString().search(/\\.indexOf\\(/), -1, 'The quickCheck
function should utilize the indexOf()
method');"
+ "text":
+ "The quickCheck
function should utilize the indexOf()
method",
+ "testString":
+ "assert.notStrictEqual(quickCheck.toString().search(/\\.indexOf\\(/), -1, 'The quickCheck
function should utilize the indexOf()
method');"
}
],
"releasedOn": "Feb 17, 2017",
@@ -528,24 +589,34 @@
],
"tests": [
{
- "text": "filteredArray([[10, 8, 3], [14, 6, 23], [3, 18, 6]], 18)
should return [ [10, 8, 3], [14, 6, 23] ]
",
- "testString": "assert.deepEqual(filteredArray([ [10, 8, 3], [14, 6, 23], [3, 18, 6] ], 18), [[10, 8, 3], [14, 6, 23]], 'filteredArray([[10, 8, 3], [14, 6, 23], [3, 18, 6]], 18)
should return [ [10, 8, 3], [14, 6, 23] ]
');"
+ "text":
+ "filteredArray([[10, 8, 3], [14, 6, 23], [3, 18, 6]], 18)
should return [ [10, 8, 3], [14, 6, 23] ]
",
+ "testString":
+ "assert.deepEqual(filteredArray([ [10, 8, 3], [14, 6, 23], [3, 18, 6] ], 18), [[10, 8, 3], [14, 6, 23]], 'filteredArray([[10, 8, 3], [14, 6, 23], [3, 18, 6]], 18)
should return [ [10, 8, 3], [14, 6, 23] ]
');"
},
{
- "text": "filteredArray([ [\"trumpets\", 2], [\"flutes\", 4], [\"saxophones\", 2] ], 2)
should return [ [\"flutes\", 4] ]
",
- "testString": "assert.deepEqual(filteredArray([ ['trumpets', 2], ['flutes', 4], ['saxophones', 2] ], 2), [['flutes', 4]], 'filteredArray([ [\"trumpets\", 2], [\"flutes\", 4], [\"saxophones\", 2] ], 2)
should return [ [\"flutes\", 4] ]
');"
+ "text":
+ "filteredArray([ [\"trumpets\", 2], [\"flutes\", 4], [\"saxophones\", 2] ], 2)
should return [ [\"flutes\", 4] ]
",
+ "testString":
+ "assert.deepEqual(filteredArray([ ['trumpets', 2], ['flutes', 4], ['saxophones', 2] ], 2), [['flutes', 4]], 'filteredArray([ [\"trumpets\", 2], [\"flutes\", 4], [\"saxophones\", 2] ], 2)
should return [ [\"flutes\", 4] ]
');"
},
{
- "text": "filteredArray([ [\"amy\", \"beth\", \"sam\"], [\"dave\", \"sean\", \"peter\"] ], \"peter\")
should return [ [\"amy\", \"beth\", \"sam\"] ]
",
- "testString": "assert.deepEqual(filteredArray([['amy', 'beth', 'sam'], ['dave', 'sean', 'peter']], 'peter'), [['amy', 'beth', 'sam']], 'filteredArray([ [\"amy\", \"beth\", \"sam\"], [\"dave\", \"sean\", \"peter\"] ], \"peter\")
should return [ [\"amy\", \"beth\", \"sam\"] ]
');"
+ "text":
+ "filteredArray([ [\"amy\", \"beth\", \"sam\"], [\"dave\", \"sean\", \"peter\"] ], \"peter\")
should return [ [\"amy\", \"beth\", \"sam\"] ]
",
+ "testString":
+ "assert.deepEqual(filteredArray([['amy', 'beth', 'sam'], ['dave', 'sean', 'peter']], 'peter'), [['amy', 'beth', 'sam']], 'filteredArray([ [\"amy\", \"beth\", \"sam\"], [\"dave\", \"sean\", \"peter\"] ], \"peter\")
should return [ [\"amy\", \"beth\", \"sam\"] ]
');"
},
{
- "text": "filteredArray([[3, 2, 3], [1, 6, 3], [3, 13, 26], [19, 3, 9]], 3)
should return [ ]
",
- "testString": "assert.deepEqual(filteredArray([[3, 2, 3], [1, 6, 3], [3, 13, 26], [19, 3, 9]], 3), [], 'filteredArray([[3, 2, 3], [1, 6, 3], [3, 13, 26], [19, 3, 9]], 3)
should return [ ]
');"
+ "text":
+ "filteredArray([[3, 2, 3], [1, 6, 3], [3, 13, 26], [19, 3, 9]], 3)
should return [ ]
",
+ "testString":
+ "assert.deepEqual(filteredArray([[3, 2, 3], [1, 6, 3], [3, 13, 26], [19, 3, 9]], 3), [], 'filteredArray([[3, 2, 3], [1, 6, 3], [3, 13, 26], [19, 3, 9]], 3)
should return [ ]
');"
},
{
- "text": "The filteredArray
function should utilize a for
loop",
- "testString": "assert.notStrictEqual(filteredArray.toString().search(/for/), -1, 'The filteredArray
function should utilize a for
loop');"
+ "text":
+ "The filteredArray
function should utilize a for
loop",
+ "testString":
+ "assert.notStrictEqual(filteredArray.toString().search(/for/), -1, 'The filteredArray
function should utilize a for
loop');"
}
],
"releasedOn": "Feb 17, 2017",
@@ -591,24 +662,34 @@
],
"tests": [
{
- "text": "myNestedArray
should contain only numbers, booleans, and strings as data elements",
- "testString": "assert.strictEqual((function(arr) { let flattened = (function flatten(arr) { const flat = [].concat(...arr); return flat.some (Array.isArray) ? flatten(flat) : flat; })(arr); for (let i = 0; i < flattened.length; i++) { if ( typeof flattened[i] !== 'number' && typeof flattened[i] !== 'string' && typeof flattened[i] !== 'boolean') { return false } } return true })(myNestedArray), true, 'myNestedArray
should contain only numbers, booleans, and strings as data elements');"
+ "text":
+ "myNestedArray
should contain only numbers, booleans, and strings as data elements",
+ "testString":
+ "assert.strictEqual((function(arr) { let flattened = (function flatten(arr) { const flat = [].concat(...arr); return flat.some (Array.isArray) ? flatten(flat) : flat; })(arr); for (let i = 0; i < flattened.length; i++) { if ( typeof flattened[i] !== 'number' && typeof flattened[i] !== 'string' && typeof flattened[i] !== 'boolean') { return false } } return true })(myNestedArray), true, 'myNestedArray
should contain only numbers, booleans, and strings as data elements');"
},
{
- "text": "myNestedArray
should have exactly 5 levels of depth",
- "testString": "assert.strictEqual((function(arr) {let depth = 0;function arrayDepth(array, i, d) { if (Array.isArray(array[i])) { arrayDepth(array[i], 0, d + 1);} else { depth = (d > depth) ? d : depth;}if (i < array.length) { arrayDepth(array, i + 1, d);} }arrayDepth(arr, 0, 0);return depth;})(myNestedArray), 4, 'myNestedArray
should have exactly 5 levels of depth');"
+ "text":
+ "myNestedArray
should have exactly 5 levels of depth",
+ "testString":
+ "assert.strictEqual((function(arr) {let depth = 0;function arrayDepth(array, i, d) { if (Array.isArray(array[i])) { arrayDepth(array[i], 0, d + 1);} else { depth = (d > depth) ? d : depth;}if (i < array.length) { arrayDepth(array, i + 1, d);} }arrayDepth(arr, 0, 0);return depth;})(myNestedArray), 4, 'myNestedArray
should have exactly 5 levels of depth');"
},
{
- "text": "myNestedArray
should contain exactly one occurrence of the string \"deep\"
on an array nested 3 levels deep",
- "testString": "assert((function howDeep(array, target, depth = 0) {return array.reduce((combined, current) => {if (Array.isArray(current)) { return combined.concat(howDeep(current, target, depth + 1));} else if (current === target) { return combined.concat(depth);} else { return combined;}}, []);})(myNestedArray, 'deep').length === 1 && (function howDeep(array, target, depth = 0) {return array.reduce((combined, current) => {if (Array.isArray(current)) { return combined.concat(howDeep(current, target, depth + 1));} else if (current === target) { return combined.concat(depth);} else { return combined;}}, []);})(myNestedArray, 'deep')[0] === 2, 'myNestedArray
should contain exactly one occurrence of the string \"deep\"
on an array nested 3 levels deep');"
+ "text":
+ "myNestedArray
should contain exactly one occurrence of the string \"deep\"
on an array nested 3 levels deep",
+ "testString":
+ "assert((function howDeep(array, target, depth = 0) {return array.reduce((combined, current) => {if (Array.isArray(current)) { return combined.concat(howDeep(current, target, depth + 1));} else if (current === target) { return combined.concat(depth);} else { return combined;}}, []);})(myNestedArray, 'deep').length === 1 && (function howDeep(array, target, depth = 0) {return array.reduce((combined, current) => {if (Array.isArray(current)) { return combined.concat(howDeep(current, target, depth + 1));} else if (current === target) { return combined.concat(depth);} else { return combined;}}, []);})(myNestedArray, 'deep')[0] === 2, 'myNestedArray
should contain exactly one occurrence of the string \"deep\"
on an array nested 3 levels deep');"
},
{
- "text": "myNestedArray
should contain exactly one occurrence of the string \"deeper\"
on an array nested 4 levels deep",
- "testString": "assert((function howDeep(array, target, depth = 0) {return array.reduce((combined, current) => {if (Array.isArray(current)) { return combined.concat(howDeep(current, target, depth + 1));} else if (current === target) { return combined.concat(depth);} else { return combined;}}, []);})(myNestedArray, 'deeper').length === 1 && (function howDeep(array, target, depth = 0) {return array.reduce((combined, current) => {if (Array.isArray(current)) { return combined.concat(howDeep(current, target, depth + 1));} else if (current === target) { return combined.concat(depth);} else { return combined;}}, []);})(myNestedArray, 'deeper')[0] === 3, 'myNestedArray
should contain exactly one occurrence of the string \"deeper\"
on an array nested 4 levels deep');"
+ "text":
+ "myNestedArray
should contain exactly one occurrence of the string \"deeper\"
on an array nested 4 levels deep",
+ "testString":
+ "assert((function howDeep(array, target, depth = 0) {return array.reduce((combined, current) => {if (Array.isArray(current)) { return combined.concat(howDeep(current, target, depth + 1));} else if (current === target) { return combined.concat(depth);} else { return combined;}}, []);})(myNestedArray, 'deeper').length === 1 && (function howDeep(array, target, depth = 0) {return array.reduce((combined, current) => {if (Array.isArray(current)) { return combined.concat(howDeep(current, target, depth + 1));} else if (current === target) { return combined.concat(depth);} else { return combined;}}, []);})(myNestedArray, 'deeper')[0] === 3, 'myNestedArray
should contain exactly one occurrence of the string \"deeper\"
on an array nested 4 levels deep');"
},
{
- "text": "myNestedArray
should contain exactly one occurrence of the string \"deepest\"
on an array nested 5 levels deep",
- "testString": "assert((function howDeep(array, target, depth = 0) {return array.reduce((combined, current) => {if (Array.isArray(current)) { return combined.concat(howDeep(current, target, depth + 1));} else if (current === target) { return combined.concat(depth);} else { return combined;}}, []);})(myNestedArray, 'deepest').length === 1 && (function howDeep(array, target, depth = 0) {return array.reduce((combined, current) => {if (Array.isArray(current)) { return combined.concat(howDeep(current, target, depth + 1));} else if (current === target) { return combined.concat(depth);} else { return combined;}}, []);})(myNestedArray, 'deepest')[0] === 4, 'myNestedArray
should contain exactly one occurrence of the string \"deepest\"
on an array nested 5 levels deep');"
+ "text":
+ "myNestedArray
should contain exactly one occurrence of the string \"deepest\"
on an array nested 5 levels deep",
+ "testString":
+ "assert((function howDeep(array, target, depth = 0) {return array.reduce((combined, current) => {if (Array.isArray(current)) { return combined.concat(howDeep(current, target, depth + 1));} else if (current === target) { return combined.concat(depth);} else { return combined;}}, []);})(myNestedArray, 'deepest').length === 1 && (function howDeep(array, target, depth = 0) {return array.reduce((combined, current) => {if (Array.isArray(current)) { return combined.concat(howDeep(current, target, depth + 1));} else if (current === target) { return combined.concat(depth);} else { return combined;}}, []);})(myNestedArray, 'deepest')[0] === 4, 'myNestedArray
should contain exactly one occurrence of the string \"deepest\"
on an array nested 5 levels deep');"
}
],
"releasedOn": "Feb 17, 2017",
@@ -641,7 +722,7 @@
"title": "Add Key-Value Pairs to JavaScript Objects",
"description": [
"At their most basic, objects are just collections of key-value pairs, or in other words, pieces of data mapped to unique identifiers that we call properties or keys. Let's take a look at a very simple example:",
- "let FCC_User = {
username: 'awesome_coder',
followers: 572,
points: 1741,
completedProjects: 15
};
",
+ "let FCC_User = {
username: 'awesome_coder',
followers: 572,
points: 1741,
completedProjects: 15
};
",
"The above code defines an object called FCC_User
that has four properties, each of which map to a specific value. If we wanted to know the number of followers
FCC_User
has, we can access that property by writing:",
"let userData = FCC_User.followers;
// userData equals 572
",
"This is called dot notation. Alternatively, we can also access the property with brackets, like so:",
@@ -653,23 +734,32 @@
"tests": [
{
"text": "foods
is an object",
- "testString": "assert(typeof foods === 'object', 'foods
is an object');"
+ "testString":
+ "assert(typeof foods === 'object', 'foods
is an object');"
},
{
- "text": "The foods
object has a key \"bananas\"
with a value of 13
",
- "testString": "assert(foods.bananas === 13, 'The foods
object has a key \"bananas\"
with a value of 13
');"
+ "text":
+ "The foods
object has a key \"bananas\"
with a value of 13
",
+ "testString":
+ "assert(foods.bananas === 13, 'The foods
object has a key \"bananas\"
with a value of 13
');"
},
{
- "text": "The foods
object has a key \"grapes\"
with a value of 35
",
- "testString": "assert(foods.grapes === 35, 'The foods
object has a key \"grapes\"
with a value of 35
');"
+ "text":
+ "The foods
object has a key \"grapes\"
with a value of 35
",
+ "testString":
+ "assert(foods.grapes === 35, 'The foods
object has a key \"grapes\"
with a value of 35
');"
},
{
- "text": "The foods
object has a key \"strawberries\"
with a value of 27
",
- "testString": "assert(foods.strawberries === 27, 'The foods
object has a key \"strawberries\"
with a value of 27
');"
+ "text":
+ "The foods
object has a key \"strawberries\"
with a value of 27
",
+ "testString":
+ "assert(foods.strawberries === 27, 'The foods
object has a key \"strawberries\"
with a value of 27
');"
},
{
- "text": "The key-value pairs should be set using dot or bracket notation",
- "testString": "assert(code.search(/bananas:/) === -1 && code.search(/grapes:/) === -1 && code.search(/strawberries:/) === -1, 'The key-value pairs should be set using dot or bracket notation');"
+ "text":
+ "The key-value pairs should be set using dot or bracket notation",
+ "testString":
+ "assert(code.search(/bananas:/) === -1 && code.search(/grapes:/) === -1 && code.search(/strawberries:/) === -1, 'The key-value pairs should be set using dot or bracket notation');"
}
],
"releasedOn": "Feb 17, 2017",
@@ -704,27 +794,35 @@
"title": "Modify an Object Nested Within an Object",
"description": [
"Now let's take a look at a slightly more complex object. Object properties can be nested to an arbitrary depth, and their values can be any type of data supported by JavaScript, including arrays and even other objects. Consider the following:",
- "let nestedObject = {
id: 28802695164,
date: 'December 31, 2016',
data: {
totalUsers: 99,
online: 80,
onlineStatus: {
active: 67,
away: 13
}
}
};
",
+ "let nestedObject = {
id: 28802695164,
date: 'December 31, 2016',
data: {
totalUsers: 99,
online: 80,
onlineStatus: {
active: 67,
away: 13
}
}
};
",
"nestedObject
has three unique keys: id
, whose value is a number, date
whose value is a string, and data
, whose value is an object which has yet another object nested within it. While structures can quickly become complex, we can still use the same notations to access the information we need.",
"
",
"Here we've defined an object, userActivity
, which includes another object nested within it. You can modify properties on this nested object in the same way you modified properties in the last challenge. Set the value of the online
key to 45
."
],
"tests": [
{
- "text": "userActivity
has id
, date
and data
properties",
- "testString": "assert('id' in userActivity && 'date' in userActivity && 'data' in userActivity, 'userActivity
has id
, date
and data
properties');"
+ "text":
+ "userActivity
has id
, date
and data
properties",
+ "testString":
+ "assert('id' in userActivity && 'date' in userActivity && 'data' in userActivity, 'userActivity
has id
, date
and data
properties');"
},
{
- "text": "userActivity
has a data
key set to an object with keys totalUsers
and online
",
- "testString": "assert('totalUsers' in userActivity.data && 'online' in userActivity.data, 'userActivity
has a data
key set to an object with keys totalUsers
and online
');"
+ "text":
+ "userActivity
has a data
key set to an object with keys totalUsers
and online
",
+ "testString":
+ "assert('totalUsers' in userActivity.data && 'online' in userActivity.data, 'userActivity
has a data
key set to an object with keys totalUsers
and online
');"
},
{
- "text": "The online
property nested in the data
key of userActivity
should be set to 45
",
- "testString": "assert(userActivity.data.online === 45, 'The online
property nested in the data
key of userActivity
should be set to 45
');"
+ "text":
+ "The online
property nested in the data
key of userActivity
should be set to 45
",
+ "testString":
+ "assert(userActivity.data.online === 45, 'The online
property nested in the data
key of userActivity
should be set to 45
');"
},
{
- "text": "The online
property is set using dot or bracket notation",
- "testString": "assert.strictEqual(code.search(/online: 45/), -1, 'The online
property is set using dot or bracket notation');"
+ "text":
+ "The online
property is set using dot or bracket notation",
+ "testString":
+ "assert.strictEqual(code.search(/online: 45/), -1, 'The online
property is set using dot or bracket notation');"
}
],
"releasedOn": "Feb 17, 2017",
@@ -770,23 +868,32 @@
"tests": [
{
"text": "checkInventory
is a function",
- "testString": "assert.strictEqual(typeof checkInventory, 'function', 'checkInventory
is a function');"
+ "testString":
+ "assert.strictEqual(typeof checkInventory, 'function', 'checkInventory
is a function');"
},
{
- "text": "The foods
object should have only the following key-value pairs: apples: 25
, oranges: 32
, plums: 28
, bananas: 13
, grapes: 35
, strawberries: 27
",
- "testString": "assert.deepEqual(foods, {apples: 25, oranges: 32, plums: 28, bananas: 13, grapes: 35, strawberries: 27}, 'The foods
object should have only the following key-value pairs: apples: 25
, oranges: 32
, plums: 28
, bananas: 13
, grapes: 35
, strawberries: 27
');"
+ "text":
+ "The foods
object should have only the following key-value pairs: apples: 25
, oranges: 32
, plums: 28
, bananas: 13
, grapes: 35
, strawberries: 27
",
+ "testString":
+ "assert.deepEqual(foods, {apples: 25, oranges: 32, plums: 28, bananas: 13, grapes: 35, strawberries: 27}, 'The foods
object should have only the following key-value pairs: apples: 25
, oranges: 32
, plums: 28
, bananas: 13
, grapes: 35
, strawberries: 27
');"
},
{
- "text": "checkInventory(\"apples\")
should return 25
",
- "testString": "assert.strictEqual(checkInventory('apples'), 25, 'checkInventory(\"apples\")
should return 25
');"
+ "text":
+ "checkInventory(\"apples\")
should return 25
",
+ "testString":
+ "assert.strictEqual(checkInventory('apples'), 25, 'checkInventory(\"apples\")
should return 25
');"
},
{
- "text": "checkInventory(\"bananas\")
should return 13
",
- "testString": "assert.strictEqual(checkInventory('bananas'), 13, 'checkInventory(\"bananas\")
should return 13
');"
+ "text":
+ "checkInventory(\"bananas\")
should return 13
",
+ "testString":
+ "assert.strictEqual(checkInventory('bananas'), 13, 'checkInventory(\"bananas\")
should return 13
');"
},
{
- "text": "checkInventory(\"strawberries\")
should return 27
",
- "testString": "assert.strictEqual(checkInventory('strawberries'), 27, 'checkInventory(\"strawberries\")
should return 27
');"
+ "text":
+ "checkInventory(\"strawberries\")
should return 27
",
+ "testString":
+ "assert.strictEqual(checkInventory('strawberries'), 27, 'checkInventory(\"strawberries\")
should return 27
');"
}
],
"releasedOn": "Feb 17, 2017",
@@ -835,12 +942,16 @@
],
"tests": [
{
- "text": "The foods
object only has three keys: apples
, grapes
, and bananas
",
- "testString": "assert(!foods.hasOwnProperty('oranges') && !foods.hasOwnProperty('plums') && !foods.hasOwnProperty('strawberries') && Object.keys(foods).length === 3, 'The foods
object only has three keys: apples
, grapes
, and bananas
');"
+ "text":
+ "The foods
object only has three keys: apples
, grapes
, and bananas
",
+ "testString":
+ "assert(!foods.hasOwnProperty('oranges') && !foods.hasOwnProperty('plums') && !foods.hasOwnProperty('strawberries') && Object.keys(foods).length === 3, 'The foods
object only has three keys: apples
, grapes
, and bananas
');"
},
{
- "text": "The oranges
, plums
, and strawberries
keys are removed using delete
",
- "testString": "assert(code.search(/oranges:/) !== -1 && code.search(/plums:/) !== -1 && code.search(/strawberries:/) !== -1, 'The oranges
, plums
, and strawberries
keys are removed using delete
');"
+ "text":
+ "The oranges
, plums
, and strawberries
keys are removed using delete
",
+ "testString":
+ "assert(code.search(/oranges:/) !== -1 && code.search(/plums:/) !== -1 && code.search(/strawberries:/) !== -1, 'The oranges
, plums
, and strawberries
keys are removed using delete
');"
}
],
"releasedOn": "Feb 17, 2017",
@@ -884,16 +995,22 @@
],
"tests": [
{
- "text": "The users
object only contains the keys Alan
, Jeff
, Sarah
, and Ryan
",
- "testString": "assert('Alan' in users && 'Jeff' in users && 'Sarah' in users && 'Ryan' in users && Object.keys(users).length === 4, 'The users
object only contains the keys Alan
, Jeff
, Sarah
, and Ryan
');"
+ "text":
+ "The users
object only contains the keys Alan
, Jeff
, Sarah
, and Ryan
",
+ "testString":
+ "assert('Alan' in users && 'Jeff' in users && 'Sarah' in users && 'Ryan' in users && Object.keys(users).length === 4, 'The users
object only contains the keys Alan
, Jeff
, Sarah
, and Ryan
');"
},
{
- "text": "The function isEveryoneHere
returns true
if Alan
, Jeff
, Sarah
, and Ryan
are properties on the users
object",
- "testString": "assert(isEveryoneHere(users) === true, 'The function isEveryoneHere
returns true
if Alan
, Jeff
, Sarah
, and Ryan
are properties on the users
object');"
+ "text":
+ "The function isEveryoneHere
returns true
if Alan
, Jeff
, Sarah
, and Ryan
are properties on the users
object",
+ "testString":
+ "assert(isEveryoneHere(users) === true, 'The function isEveryoneHere
returns true
if Alan
, Jeff
, Sarah
, and Ryan
are properties on the users
object');"
},
{
- "text": "The function isEveryoneHere
returns false
if Alan
, Jeff
, Sarah
, and Ryan
are not properties on the users
object",
- "testString": "assert((function() { delete users.Alan; delete users.Jeff; delete users.Sarah; delete users.Ryan; return isEveryoneHere(users) })() === false, 'The function isEveryoneHere
returns false
if Alan
, Jeff
, Sarah
, and Ryan
are not properties on the users
object');"
+ "text":
+ "The function isEveryoneHere
returns false
if Alan
, Jeff
, Sarah
, and Ryan
are not properties on the users
object",
+ "testString":
+ "assert((function() { delete users.Alan; delete users.Jeff; delete users.Sarah; delete users.Ryan; return isEveryoneHere(users) })() === false, 'The function isEveryoneHere
returns false
if Alan
, Jeff
, Sarah
, and Ryan
are not properties on the users
object');"
}
],
"releasedOn": "Feb 17, 2017",
@@ -940,10 +1057,11 @@
},
{
"id": "587d7b7d367417b2b2512b1d",
- "title": " Iterate Through the Keys of an Object with a for...in Statement",
+ "title":
+ " Iterate Through the Keys of an Object with a for...in Statement",
"description": [
"Sometimes you may need to iterate through all the keys within an object. This requires a specific syntax in JavaScript called a for...in statement. For our users
object, this could look like:",
- "for (let user in users) {
console.log(user);
};
// logs:
Alan
Jeff
Sarah
Ryan
",
+ "for (let user in users) {
console.log(user);
};
// logs:
Alan
Jeff
Sarah
Ryan
",
"In this statement, we defined a variable user
, and as you can see, this variable was reset during each iteration to each of the object's keys as the statement looped through the object, resulting in each user's name being printed to the console.",
"NOTE:
Objects do not maintain an ordering to stored keys like arrays do; thus a keys position on an object, or the relative order in which it appears, is irrelevant when referencing or accessing that key.",
"
",
@@ -951,12 +1069,16 @@
],
"tests": [
{
- "text": "The users
object contains users Jeff
and Ryan
with online
set to true
and users Alan
and Sarah
with online
set to false
",
- "testString": "assert(users.Alan.online === false && users.Jeff.online === true && users.Sarah.online === false && users.Ryan.online === true, 'The users
object contains users Jeff
and Ryan
with online
set to true
and users Alan
and Sarah
with online
set to false
');"
+ "text":
+ "The users
object contains users Jeff
and Ryan
with online
set to true
and users Alan
and Sarah
with online
set to false
",
+ "testString":
+ "assert(users.Alan.online === false && users.Jeff.online === true && users.Sarah.online === false && users.Ryan.online === true, 'The users
object contains users Jeff
and Ryan
with online
set to true
and users Alan
and Sarah
with online
set to false
');"
},
{
- "text": "The function countOnline
returns the number of users with the online
property set to true
",
- "testString": "assert((function() { users.Harry = {online: true}; users.Sam = {online: true}; users.Carl = {online: true}; return countOnline(users) })() === 5, 'The function countOnline
returns the number of users with the online
property set to true
');"
+ "text":
+ "The function countOnline
returns the number of users with the online
property set to true
",
+ "testString":
+ "assert((function() { users.Harry = {online: true}; users.Sam = {online: true}; users.Carl = {online: true}; return countOnline(users) })() === 5, 'The function countOnline
returns the number of users with the online
property set to true
');"
}
],
"releasedOn": "Feb 17, 2017",
@@ -1011,12 +1133,16 @@
],
"tests": [
{
- "text": "The users
object only contains the keys Alan
, Jeff
, Sarah
, and Ryan
",
- "testString": "assert('Alan' in users && 'Jeff' in users && 'Sarah' in users && 'Ryan' in users && Object.keys(users).length === 4, 'The users
object only contains the keys Alan
, Jeff
, Sarah
, and Ryan
');"
+ "text":
+ "The users
object only contains the keys Alan
, Jeff
, Sarah
, and Ryan
",
+ "testString":
+ "assert('Alan' in users && 'Jeff' in users && 'Sarah' in users && 'Ryan' in users && Object.keys(users).length === 4, 'The users
object only contains the keys Alan
, Jeff
, Sarah
, and Ryan
');"
},
{
- "text": "The getArrayOfUsers
function returns an array which contains all the keys in the users
object",
- "testString": "assert((function() { users.Sam = {}; users.Lewis = {}; let R = getArrayOfUsers(users); return (R.indexOf('Alan') !== -1 && R.indexOf('Jeff') !== -1 && R.indexOf('Sarah') !== -1 && R.indexOf('Ryan') !== -1 && R.indexOf('Sam') !== -1 && R.indexOf('Lewis') !== -1); })() === true, 'The getArrayOfUsers
function returns an array which contains all the keys in the users
object');"
+ "text":
+ "The getArrayOfUsers
function returns an array which contains all the keys in the users
object",
+ "testString":
+ "assert((function() { users.Sam = {}; users.Lewis = {}; let R = getArrayOfUsers(users); return (R.indexOf('Alan') !== -1 && R.indexOf('Jeff') !== -1 && R.indexOf('Sarah') !== -1 && R.indexOf('Ryan') !== -1 && R.indexOf('Sam') !== -1 && R.indexOf('Lewis') !== -1); })() === true, 'The getArrayOfUsers
function returns an array which contains all the keys in the users
object');"
}
],
"releasedOn": "Feb 17, 2017",
@@ -1071,16 +1197,22 @@
],
"tests": [
{
- "text": "The user
object has name
, age
, and data
keys",
- "testString": "assert('name' in user && 'age' in user && 'data' in user, 'The user
object has name
, age
, and data
keys');"
+ "text":
+ "The user
object has name
, age
, and data
keys",
+ "testString":
+ "assert('name' in user && 'age' in user && 'data' in user, 'The user
object has name
, age
, and data
keys');"
},
{
- "text": "The addFriend
function accepts a user
object and a friend
string as arguments and adds the friend to the array of friends
in the user
object",
- "testString": "assert((function() { let L1 = user.data.friends.length; addFriend(user, 'Sean'); let L2 = user.data.friends.length; return (L2 === L1 + 1); })(), 'The addFriend
function accepts a user
object and a friend
string as arguments and adds the friend to the array of friends
in the user
object');"
+ "text":
+ "The addFriend
function accepts a user
object and a friend
string as arguments and adds the friend to the array of friends
in the user
object",
+ "testString":
+ "assert((function() { let L1 = user.data.friends.length; addFriend(user, 'Sean'); let L2 = user.data.friends.length; return (L2 === L1 + 1); })(), 'The addFriend
function accepts a user
object and a friend
string as arguments and adds the friend to the array of friends
in the user
object');"
},
{
- "text": "addFriend(user, \"Pete\")
should return [\"Sam\", \"Kira\", \"Tomo\", \"Pete\"]
",
- "testString": "assert.deepEqual((function() { delete user.data.friends; user.data.friends = ['Sam', 'Kira', 'Tomo']; return addFriend(user, 'Pete') })(), ['Sam', 'Kira', 'Tomo', 'Pete'], 'addFriend(user, \"Pete\")
should return [\"Sam\", \"Kira\", \"Tomo\", \"Pete\"]
');"
+ "text":
+ "addFriend(user, \"Pete\")
should return [\"Sam\", \"Kira\", \"Tomo\", \"Pete\"]
",
+ "testString":
+ "assert.deepEqual((function() { delete user.data.friends; user.data.friends = ['Sam', 'Kira', 'Tomo']; return addFriend(user, 'Pete') })(), ['Sam', 'Kira', 'Tomo', 'Pete'], 'addFriend(user, \"Pete\")
should return [\"Sam\", \"Kira\", \"Tomo\", \"Pete\"]
');"
}
],
"releasedOn": "Feb 17, 2017",
@@ -1127,4 +1259,4 @@
}
}
]
-}
\ No newline at end of file
+}
diff --git a/challenges/02-javascript-algorithms-and-data-structures/basic-javascript.json b/challenges/02-javascript-algorithms-and-data-structures/basic-javascript.json
index 0a2a90a22..1589069b1 100644
--- a/challenges/02-javascript-algorithms-and-data-structures/basic-javascript.json
+++ b/challenges/02-javascript-algorithms-and-data-structures/basic-javascript.json
@@ -13,22 +13,24 @@
"Using //
will tell JavaScript to ignore the remainder of the text on the current line:",
"// This is an in-line comment.
",
"You can make a multi-line comment beginning with /*
and ending with */
:",
- "/* This is a
multi-line comment */
",
+ "/* This is a
multi-line comment */
",
"Best Practice
As you write code, you should regularly add comments to clarify the function of parts of your code. Good commenting can help communicate the intent of your code—both for others and for your future self.",
"
",
"Try creating one of each type of comment."
],
- "solutions": [
- "// Fake Comment\n/* Another Comment */"
- ],
+ "solutions": ["// Fake Comment\n/* Another Comment */"],
"tests": [
{
- "text": "Create a //
style comment that contains at least five letters.",
- "testString": "assert(code.match(/(\\/\\/)...../g), 'Create a //
style comment that contains at least five letters.');"
+ "text":
+ "Create a //
style comment that contains at least five letters.",
+ "testString":
+ "assert(code.match(/(\\/\\/)...../g), 'Create a //
style comment that contains at least five letters.');"
},
{
- "text": "Create a /* */
style comment that contains at least five letters.",
- "testString": "assert(code.match(/(\\/\\*)([^\\*\\/]{5,})(?=\\*\\/)/gm), 'Create a /* */
style comment that contains at least five letters.');"
+ "text":
+ "Create a /* */
style comment that contains at least five letters.",
+ "testString":
+ "assert(code.match(/(\\/\\*)([^\\*\\/]{5,})(?=\\*\\/)/gm), 'Create a /* */
style comment that contains at least five letters.');"
}
],
"challengeType": 1,
@@ -88,13 +90,13 @@
"Use the var
keyword to create a variable called myName
.",
"Hint
Look at the ourName
example if you get stuck."
],
- "solutions": [
- "var myName;"
- ],
+ "solutions": ["var myName;"],
"tests": [
{
- "text": "You should declare myName
with the var
keyword, ending with a semicolon",
- "testString": "assert(/var\\s+myName\\s*;/.test(code), 'You should declare myName
with the var
keyword, ending with a semicolon');"
+ "text":
+ "You should declare myName
with the var
keyword, ending with a semicolon",
+ "testString":
+ "assert(/var\\s+myName\\s*;/.test(code), 'You should declare myName
with the var
keyword, ending with a semicolon');"
}
],
"challengeType": 1,
@@ -160,25 +162,28 @@
"Assign the contents of a
to variable b
."
],
"releasedOn": "January 1, 2016",
- "solutions": [
- "var a;\nvar b = 2;\na = 7;\nb = a;"
- ],
+ "solutions": ["var a;\nvar b = 2;\na = 7;\nb = a;"],
"tests": [
{
"text": "Do not change code above the line",
- "testString": "assert(/var a;/.test(code) && /var b = 2;/.test(code), 'Do not change code above the line');"
+ "testString":
+ "assert(/var a;/.test(code) && /var b = 2;/.test(code), 'Do not change code above the line');"
},
{
"text": "a
should have a value of 7",
- "testString": "assert(typeof a === 'number' && a === 7, 'a
should have a value of 7');"
+ "testString":
+ "assert(typeof a === 'number' && a === 7, 'a
should have a value of 7');"
},
{
"text": "b
should have a value of 7",
- "testString": "assert(typeof b === 'number' && b === 7, 'b
should have a value of 7');"
+ "testString":
+ "assert(typeof b === 'number' && b === 7, 'b
should have a value of 7');"
},
{
- "text": "a
should be assigned to b
with =
",
- "testString": "assert(/b\\s*=\\s*a\\s*;/g.test(code), 'a
should be assigned to b
with =
');"
+ "text":
+ "a
should be assigned to b
with =
",
+ "testString":
+ "assert(/b\\s*=\\s*a\\s*;/g.test(code), 'a
should be assigned to b
with =
');"
}
],
"challengeType": 1,
@@ -236,13 +241,12 @@
"Define a variable a
with var
and initialize it to a value of 9
."
],
"releasedOn": "January 1, 2016",
- "solutions": [
- "var a = 9;"
- ],
+ "solutions": ["var a = 9;"],
"tests": [
{
"text": "Initialize a
to a value of 9
",
- "testString": "assert(/var\\s+a\\s*=\\s*9\\s*/.test(code), 'Initialize a
to a value of 9
');"
+ "testString":
+ "assert(/var\\s+a\\s*=\\s*9\\s*/.test(code), 'Initialize a
to a value of 9
');"
}
],
"challengeType": 1,
@@ -291,20 +295,27 @@
],
"tests": [
{
- "text": "a
should be defined and evaluated to have the value of 6
",
- "testString": "assert(typeof a === 'number' && a === 6, 'a
should be defined and evaluated to have the value of 6
');"
+ "text":
+ "a
should be defined and evaluated to have the value of 6
",
+ "testString":
+ "assert(typeof a === 'number' && a === 6, 'a
should be defined and evaluated to have the value of 6
');"
},
{
- "text": "b
should be defined and evaluated to have the value of 15
",
- "testString": "assert(typeof b === 'number' && b === 15, 'b
should be defined and evaluated to have the value of 15
');"
+ "text":
+ "b
should be defined and evaluated to have the value of 15
",
+ "testString":
+ "assert(typeof b === 'number' && b === 15, 'b
should be defined and evaluated to have the value of 15
');"
},
{
- "text": "c
should not contain undefined
and should have a value of \"I am a String!\"",
- "testString": "assert(!/undefined/.test(c) && c === \"I am a String!\", 'c
should not contain undefined
and should have a value of \"I am a String!\"');"
+ "text":
+ "c
should not contain undefined
and should have a value of \"I am a String!\"",
+ "testString":
+ "assert(!/undefined/.test(c) && c === \"I am a String!\", 'c
should not contain undefined
and should have a value of \"I am a String!\"');"
},
{
"text": "Do not change code below the line",
- "testString": "assert(/a = a \\+ 1;/.test(code) && /b = b \\+ 5;/.test(code) && /c = c \\+ \" String!\";/.test(code), 'Do not change code below the line');"
+ "testString":
+ "assert(/a = a \\+ 1;/.test(code) && /b = b \\+ 5;/.test(code) && /c = c \\+ \" String!\";/.test(code), 'Do not change code below the line');"
}
],
"challengeType": 1,
@@ -362,28 +373,40 @@
],
"tests": [
{
- "text": "studlyCapVar
is defined and has a value of 10
",
- "testString": "assert(typeof studlyCapVar !== 'undefined' && studlyCapVar === 10, 'studlyCapVar
is defined and has a value of 10
');"
+ "text":
+ "studlyCapVar
is defined and has a value of 10
",
+ "testString":
+ "assert(typeof studlyCapVar !== 'undefined' && studlyCapVar === 10, 'studlyCapVar
is defined and has a value of 10
');"
},
{
- "text": "properCamelCase
is defined and has a value of \"A String\"
",
- "testString": "assert(typeof properCamelCase !== 'undefined' && properCamelCase === \"A String\", 'properCamelCase
is defined and has a value of \"A String\"
');"
+ "text":
+ "properCamelCase
is defined and has a value of \"A String\"
",
+ "testString":
+ "assert(typeof properCamelCase !== 'undefined' && properCamelCase === \"A String\", 'properCamelCase
is defined and has a value of \"A String\"
');"
},
{
- "text": "titleCaseOver
is defined and has a value of 9000
",
- "testString": "assert(typeof titleCaseOver !== 'undefined' && titleCaseOver === 9000, 'titleCaseOver
is defined and has a value of 9000
');"
+ "text":
+ "titleCaseOver
is defined and has a value of 9000
",
+ "testString":
+ "assert(typeof titleCaseOver !== 'undefined' && titleCaseOver === 9000, 'titleCaseOver
is defined and has a value of 9000
');"
},
{
- "text": "studlyCapVar
should use camelCase in both declaration and assignment sections.",
- "testString": "assert(code.match(/studlyCapVar/g).length === 2, 'studlyCapVar
should use camelCase in both declaration and assignment sections.');"
+ "text":
+ "studlyCapVar
should use camelCase in both declaration and assignment sections.",
+ "testString":
+ "assert(code.match(/studlyCapVar/g).length === 2, 'studlyCapVar
should use camelCase in both declaration and assignment sections.');"
},
{
- "text": "properCamelCase
should use camelCase in both declaration and assignment sections.",
- "testString": "assert(code.match(/properCamelCase/g).length === 2, 'properCamelCase
should use camelCase in both declaration and assignment sections.');"
+ "text":
+ "properCamelCase
should use camelCase in both declaration and assignment sections.",
+ "testString":
+ "assert(code.match(/properCamelCase/g).length === 2, 'properCamelCase
should use camelCase in both declaration and assignment sections.');"
},
{
- "text": "titleCaseOver
should use camelCase in both declaration and assignment sections.",
- "testString": "assert(code.match(/titleCaseOver/g).length === 2, 'titleCaseOver
should use camelCase in both declaration and assignment sections.');"
+ "text":
+ "titleCaseOver
should use camelCase in both declaration and assignment sections.",
+ "testString":
+ "assert(code.match(/titleCaseOver/g).length === 2, 'titleCaseOver
should use camelCase in both declaration and assignment sections.');"
}
],
"challengeType": 1,
@@ -435,17 +458,17 @@
"
",
"Change the 0
so that sum will equal 20
."
],
- "solutions": [
- "var sum = 10 + 10;"
- ],
+ "solutions": ["var sum = 10 + 10;"],
"tests": [
{
"text": "sum
should equal 20
",
- "testString": "assert(sum === 20, 'sum
should equal 20
');"
+ "testString":
+ "assert(sum === 20, 'sum
should equal 20
');"
},
{
"text": "Use the +
operator",
- "testString": "assert(/\\+/.test(code), 'Use the +
operator');"
+ "testString":
+ "assert(/\\+/.test(code), 'Use the +
operator');"
}
],
"challengeType": 1,
@@ -464,14 +487,9 @@
"key": "indexjs",
"ext": "js",
"name": "index",
- "contents": [
- "var sum = 10 + 0;",
- ""
- ],
+ "contents": ["var sum = 10 + 0;", ""],
"head": [],
- "tail": [
- "(function(z){return 'sum = '+z;})(sum);"
- ]
+ "tail": ["(function(z){return 'sum = '+z;})(sum);"]
}
}
},
@@ -488,17 +506,17 @@
"
",
"Change the 0
so the difference is 12
."
],
- "solutions": [
- "var difference = 45 - 33;"
- ],
+ "solutions": ["var difference = 45 - 33;"],
"tests": [
{
"text": "Make the variable difference
equal 12.",
- "testString": "assert(difference === 12, 'Make the variable difference
equal 12.');"
+ "testString":
+ "assert(difference === 12, 'Make the variable difference
equal 12.');"
},
{
"text": "Only subtract one number from 45.",
- "testString": "assert(/var\\s*difference\\s*=\\s*45\\s*-\\s*[0-9]*;(?!\\s*[a-zA-Z0-9]+)/.test(code),'Only subtract one number from 45.');"
+ "testString":
+ "assert(/var\\s*difference\\s*=\\s*45\\s*-\\s*[0-9]*;(?!\\s*[a-zA-Z0-9]+)/.test(code),'Only subtract one number from 45.');"
}
],
"challengeType": 1,
@@ -517,15 +535,9 @@
"key": "indexjs",
"ext": "js",
"name": "index",
- "contents": [
- "var difference = 45 - 0;",
- "",
- ""
- ],
+ "contents": ["var difference = 45 - 0;", "", ""],
"head": [],
- "tail": [
- "(function(z){return 'difference = '+z;})(difference);"
- ]
+ "tail": ["(function(z){return 'difference = '+z;})(difference);"]
}
}
},
@@ -542,17 +554,17 @@
"
",
"Change the 0
so that product will equal 80
."
],
- "solutions": [
- "var product = 8 * 10;"
- ],
+ "solutions": ["var product = 8 * 10;"],
"tests": [
{
"text": "Make the variable product
equal 80",
- "testString": "assert(product === 80,'Make the variable product
equal 80');"
+ "testString":
+ "assert(product === 80,'Make the variable product
equal 80');"
},
{
"text": "Use the *
operator",
- "testString": "assert(/\\*/.test(code), 'Use the *
operator');"
+ "testString":
+ "assert(/\\*/.test(code), 'Use the *
operator');"
}
],
"challengeType": 1,
@@ -571,15 +583,9 @@
"key": "indexjs",
"ext": "js",
"name": "index",
- "contents": [
- "var product = 8 * 0;",
- "",
- ""
- ],
+ "contents": ["var product = 8 * 0;", "", ""],
"head": [],
- "tail": [
- "(function(z){return 'product = '+z;})(product);"
- ]
+ "tail": ["(function(z){return 'product = '+z;})(product);"]
}
}
},
@@ -596,17 +602,17 @@
"
",
"Change the 0
so that the quotient
is equal to 2
."
],
- "solutions": [
- "var quotient = 66 / 33;"
- ],
+ "solutions": ["var quotient = 66 / 33;"],
"tests": [
{
"text": "Make the variable quotient
equal to 2.",
- "testString": "assert(quotient === 2, 'Make the variable quotient
equal to 2.');"
+ "testString":
+ "assert(quotient === 2, 'Make the variable quotient
equal to 2.');"
},
{
"text": "Use the /
operator",
- "testString": "assert(/\\d+\\s*\\/\\s*\\d+/.test(code), 'Use the /
operator');"
+ "testString":
+ "assert(/\\d+\\s*\\/\\s*\\d+/.test(code), 'Use the /
operator');"
}
],
"challengeType": 1,
@@ -625,15 +631,9 @@
"key": "indexjs",
"ext": "js",
"name": "index",
- "contents": [
- "var quotient = 66 / 0;",
- "",
- ""
- ],
+ "contents": ["var quotient = 66 / 0;", "", ""],
"head": [],
- "tail": [
- "(function(z){return 'quotient = '+z;})(quotient);"
- ]
+ "tail": ["(function(z){return 'quotient = '+z;})(quotient);"]
}
}
},
@@ -651,25 +651,27 @@
"Hint
Learn more about Arithmetic operators - Increment (++)."
],
"releasedOn": "January 1, 2016",
- "solutions": [
- "var myVar = 87;\nmyVar++;"
- ],
+ "solutions": ["var myVar = 87;\nmyVar++;"],
"tests": [
{
"text": "myVar
should equal 88
",
- "testString": "assert(myVar === 88, 'myVar
should equal 88
');"
+ "testString":
+ "assert(myVar === 88, 'myVar
should equal 88
');"
},
{
"text": "myVar = myVar + 1;
should be changed",
- "testString": "assert(/var\\s*myVar\\s*=\\s*87;\\s*\\/*.*\\s*myVar\\+\\+;/.test(code), 'myVar = myVar + 1;
should be changed');"
+ "testString":
+ "assert(/var\\s*myVar\\s*=\\s*87;\\s*\\/*.*\\s*myVar\\+\\+;/.test(code), 'myVar = myVar + 1;
should be changed');"
},
{
"text": "Use the ++
operator",
- "testString": "assert(/[+]{2}\\s*myVar|myVar\\s*[+]{2}/.test(code), 'Use the ++
operator');"
+ "testString":
+ "assert(/[+]{2}\\s*myVar|myVar\\s*[+]{2}/.test(code), 'Use the ++
operator');"
},
{
"text": "Do not change code above the line",
- "testString": "assert(/var myVar = 87;/.test(code), 'Do not change code above the line');"
+ "testString":
+ "assert(/var myVar = 87;/.test(code), 'Do not change code above the line');"
}
],
"challengeType": 1,
@@ -700,9 +702,7 @@
""
],
"head": [],
- "tail": [
- "(function(z){return 'myVar = ' + z;})(myVar);"
- ]
+ "tail": ["(function(z){return 'myVar = ' + z;})(myVar);"]
}
}
},
@@ -719,25 +719,27 @@
"Change the code to use the --
operator on myVar
."
],
"releasedOn": "January 1, 2016",
- "solutions": [
- "var myVar = 11;\nmyVar--;"
- ],
+ "solutions": ["var myVar = 11;\nmyVar--;"],
"tests": [
{
"text": "myVar
should equal 10
",
- "testString": "assert(myVar === 10, 'myVar
should equal 10
');"
+ "testString":
+ "assert(myVar === 10, 'myVar
should equal 10
');"
},
{
"text": "myVar = myVar - 1;
should be changed",
- "testString": "assert(/var\\s*myVar\\s*=\\s*11;\\s*\\/*.*\\s*myVar--;/.test(code), 'myVar = myVar - 1;
should be changed');"
+ "testString":
+ "assert(/var\\s*myVar\\s*=\\s*11;\\s*\\/*.*\\s*myVar--;/.test(code), 'myVar = myVar - 1;
should be changed');"
},
{
"text": "Use the --
operator on myVar
",
- "testString": "assert(/[-]{2}\\s*myVar|myVar\\s*[-]{2}/.test(code), 'Use the --
operator on myVar
');"
+ "testString":
+ "assert(/[-]{2}\\s*myVar|myVar\\s*[-]{2}/.test(code), 'Use the --
operator on myVar
');"
},
{
"text": "Do not change code above the line",
- "testString": "assert(/var myVar = 11;/.test(code), 'Do not change code above the line');"
+ "testString":
+ "assert(/var myVar = 11;/.test(code), 'Do not change code above the line');"
}
],
"challengeType": 1,
@@ -768,9 +770,7 @@
""
],
"head": [],
- "tail": [
- "(function(z){return 'myVar = ' + z;})(myVar);"
- ]
+ "tail": ["(function(z){return 'myVar = ' + z;})(myVar);"]
}
}
},
@@ -783,17 +783,17 @@
"
",
"Create a variable myDecimal
and give it a decimal value with a fractional part (e.g. 5.7
)."
],
- "solutions": [
- "var myDecimal = 9.9;"
- ],
+ "solutions": ["var myDecimal = 9.9;"],
"tests": [
{
"text": "myDecimal
should be a number.",
- "testString": "assert(typeof myDecimal === \"number\", 'myDecimal
should be a number.');"
+ "testString":
+ "assert(typeof myDecimal === \"number\", 'myDecimal
should be a number.');"
},
{
"text": "myDecimal
should have a decimal point",
- "testString": "assert(myDecimal % 1 != 0, 'myDecimal
should have a decimal point'); "
+ "testString":
+ "assert(myDecimal % 1 != 0, 'myDecimal
should have a decimal point'); "
}
],
"challengeType": 1,
@@ -836,17 +836,18 @@
"
",
"Change the 0.0
so that product will equal 5.0
."
],
- "solutions": [
- "var product = 2.0 * 2.5;"
- ],
+ "solutions": ["var product = 2.0 * 2.5;"],
"tests": [
{
- "text": "The variable product
should equal 5.0
.",
- "testString": "assert(product === 5.0, 'The variable product
should equal 5.0
.');"
+ "text":
+ "The variable product
should equal 5.0
.",
+ "testString":
+ "assert(product === 5.0, 'The variable product
should equal 5.0
.');"
},
{
"text": "You should use the *
operator",
- "testString": "assert(/\\*/.test(code), 'You should use the *
operator');"
+ "testString":
+ "assert(/\\*/.test(code), 'You should use the *
operator');"
}
],
"challengeType": 1,
@@ -866,15 +867,9 @@
"key": "indexjs",
"ext": "js",
"name": "index",
- "contents": [
- "var product = 2.0 * 0.0;",
- "",
- ""
- ],
+ "contents": ["var product = 2.0 * 0.0;", "", ""],
"head": [],
- "tail": [
- "(function(y){return 'product = '+y;})(product);"
- ]
+ "tail": ["(function(y){return 'product = '+y;})(product);"]
}
}
},
@@ -889,16 +884,21 @@
"solutions": [],
"tests": [
{
- "text": "The variable quotient
should equal 2.2
",
- "testString": "assert(quotient === 2.2, 'The variable quotient
should equal 2.2
');"
+ "text":
+ "The variable quotient
should equal 2.2
",
+ "testString":
+ "assert(quotient === 2.2, 'The variable quotient
should equal 2.2
');"
},
{
- "text": "You should use the /
operator to divide 4.4 by 2",
- "testString": "assert(/4\\.40*\\s*\\/\\s*2\\.*0*/.test(code), 'You should use the /
operator to divide 4.4 by 2');"
+ "text":
+ "You should use the /
operator to divide 4.4 by 2",
+ "testString":
+ "assert(/4\\.40*\\s*\\/\\s*2\\.*0*/.test(code), 'You should use the /
operator to divide 4.4 by 2');"
},
{
"text": "The quotient variable should only be assigned once",
- "testString": "assert(code.match(/quotient/g).length === 1, 'The quotient variable should only be assigned once');"
+ "testString":
+ "assert(code.match(/quotient/g).length === 1, 'The quotient variable should only be assigned once');"
}
],
"challengeType": 1,
@@ -917,15 +917,9 @@
"key": "indexjs",
"ext": "js",
"name": "index",
- "contents": [
- "var quotient = 0.0 / 2.0; // Fix this line",
- "",
- ""
- ],
+ "contents": ["var quotient = 0.0 / 2.0; // Fix this line", "", ""],
"head": [],
- "tail": [
- "(function(y){return 'quotient = '+y;})(quotient);"
- ]
+ "tail": ["(function(y){return 'quotient = '+y;})(quotient);"]
}
}
},
@@ -943,21 +937,23 @@
"Set remainder
equal to the remainder of 11
divided by 3
using the remainder (%
) operator."
],
"releasedOn": "January 1, 2016",
- "solutions": [
- "var remainder = 11 % 3;"
- ],
+ "solutions": ["var remainder = 11 % 3;"],
"tests": [
{
"text": "The variable remainder
should be initialized",
- "testString": "assert(/var\\s+?remainder/.test(code), 'The variable remainder
should be initialized');"
+ "testString":
+ "assert(/var\\s+?remainder/.test(code), 'The variable remainder
should be initialized');"
},
{
- "text": "The value of remainder
should be 2
",
- "testString": "assert(remainder === 2, 'The value of remainder
should be 2
');"
+ "text":
+ "The value of remainder
should be 2
",
+ "testString":
+ "assert(remainder === 2, 'The value of remainder
should be 2
');"
},
{
"text": "You should use the %
operator",
- "testString": "assert(/\\s+?remainder\\s*?=\\s*?.*%.*;/.test(code), 'You should use the %
operator');"
+ "testString":
+ "assert(/\\s+?remainder\\s*?=\\s*?.*%.*;/.test(code), 'You should use the %
operator');"
}
],
"challengeType": 1,
@@ -988,9 +984,7 @@
""
],
"head": [],
- "tail": [
- "(function(y){return 'remainder = '+y;})(remainder);"
- ]
+ "tail": ["(function(y){return 'remainder = '+y;})(remainder);"]
}
}
},
@@ -1013,23 +1007,29 @@
"tests": [
{
"text": "a
should equal 15
",
- "testString": "assert(a === 15, 'a
should equal 15
');"
+ "testString":
+ "assert(a === 15, 'a
should equal 15
');"
},
{
"text": "b
should equal 26
",
- "testString": "assert(b === 26, 'b
should equal 26
');"
+ "testString":
+ "assert(b === 26, 'b
should equal 26
');"
},
{
"text": "c
should equal 19
",
- "testString": "assert(c === 19, 'c
should equal 19
');"
+ "testString":
+ "assert(c === 19, 'c
should equal 19
');"
},
{
- "text": "You should use the +=
operator for each variable",
- "testString": "assert(code.match(/\\+=/g).length === 3, 'You should use the +=
operator for each variable');"
+ "text":
+ "You should use the +=
operator for each variable",
+ "testString":
+ "assert(code.match(/\\+=/g).length === 3, 'You should use the +=
operator for each variable');"
},
{
"text": "Do not modify the code above the line",
- "testString": "assert(/var a = 3;/.test(code) && /var b = 17;/.test(code) && /var c = 12;/.test(code), 'Do not modify the code above the line');"
+ "testString":
+ "assert(/var a = 3;/.test(code) && /var b = 17;/.test(code) && /var c = 12;/.test(code), 'Do not modify the code above the line');"
}
],
"challengeType": 1,
@@ -1089,23 +1089,29 @@
"tests": [
{
"text": "a
should equal 5
",
- "testString": "assert(a === 5, 'a
should equal 5
');"
+ "testString":
+ "assert(a === 5, 'a
should equal 5
');"
},
{
"text": "b
should equal -6
",
- "testString": "assert(b === -6, 'b
should equal -6
');"
+ "testString":
+ "assert(b === -6, 'b
should equal -6
');"
},
{
"text": "c
should equal 2
",
- "testString": "assert(c === 2, 'c
should equal 2
');"
+ "testString":
+ "assert(c === 2, 'c
should equal 2
');"
},
{
- "text": "You should use the -=
operator for each variable",
- "testString": "assert(code.match(/-=/g).length === 3, 'You should use the -=
operator for each variable');"
+ "text":
+ "You should use the -=
operator for each variable",
+ "testString":
+ "assert(code.match(/-=/g).length === 3, 'You should use the -=
operator for each variable');"
},
{
"text": "Do not modify the code above the line",
- "testString": "assert(/var a = 11;/.test(code) && /var b = 9;/.test(code) && /var c = 3;/.test(code), 'Do not modify the code above the line');"
+ "testString":
+ "assert(/var a = 11;/.test(code) && /var b = 9;/.test(code) && /var c = 3;/.test(code), 'Do not modify the code above the line');"
}
],
"challengeType": 1,
@@ -1165,23 +1171,29 @@
"tests": [
{
"text": "a
should equal 25
",
- "testString": "assert(a === 25, 'a
should equal 25
');"
+ "testString":
+ "assert(a === 25, 'a
should equal 25
');"
},
{
"text": "b
should equal 36
",
- "testString": "assert(b === 36, 'b
should equal 36
');"
+ "testString":
+ "assert(b === 36, 'b
should equal 36
');"
},
{
"text": "c
should equal 46
",
- "testString": "assert(c === 46, 'c
should equal 46
');"
+ "testString":
+ "assert(c === 46, 'c
should equal 46
');"
},
{
- "text": "You should use the *=
operator for each variable",
- "testString": "assert(code.match(/\\*=/g).length === 3, 'You should use the *=
operator for each variable');"
+ "text":
+ "You should use the *=
operator for each variable",
+ "testString":
+ "assert(code.match(/\\*=/g).length === 3, 'You should use the *=
operator for each variable');"
},
{
"text": "Do not modify the code above the line",
- "testString": "assert(/var a = 5;/.test(code) && /var b = 12;/.test(code) && /var c = 4\\.6;/.test(code), 'Do not modify the code above the line');"
+ "testString":
+ "assert(/var a = 5;/.test(code) && /var b = 12;/.test(code) && /var c = 4\\.6;/.test(code), 'Do not modify the code above the line');"
}
],
"challengeType": 1,
@@ -1241,23 +1253,29 @@
"tests": [
{
"text": "a
should equal 4
",
- "testString": "assert(a === 4, 'a
should equal 4
');"
+ "testString":
+ "assert(a === 4, 'a
should equal 4
');"
},
{
"text": "b
should equal 27
",
- "testString": "assert(b === 27, 'b
should equal 27
');"
+ "testString":
+ "assert(b === 27, 'b
should equal 27
');"
},
{
"text": "c
should equal 3
",
- "testString": "assert(c === 3, 'c
should equal 3
');"
+ "testString":
+ "assert(c === 3, 'c
should equal 3
');"
},
{
- "text": "You should use the /=
operator for each variable",
- "testString": "assert(code.match(/\\/=/g).length === 3, 'You should use the /=
operator for each variable');"
+ "text":
+ "You should use the /=
operator for each variable",
+ "testString":
+ "assert(code.match(/\\/=/g).length === 3, 'You should use the /=
operator for each variable');"
},
{
"text": "Do not modify the code above the line",
- "testString": "assert(/var a = 48;/.test(code) && /var b = 108;/.test(code) && /var c = 33;/.test(code), 'Do not modify the code above the line');"
+ "testString":
+ "assert(/var a = 48;/.test(code) && /var b = 108;/.test(code) && /var c = 33;/.test(code), 'Do not modify the code above the line');"
}
],
"challengeType": 1,
@@ -1313,12 +1331,16 @@
],
"tests": [
{
- "text": "myFirstName
should be a string with at least one character in it.",
- "testString": "assert((function(){if(typeof myFirstName !== \"undefined\" && typeof myFirstName === \"string\" && myFirstName.length > 0){return true;}else{return false;}})(), 'myFirstName
should be a string with at least one character in it.');"
+ "text":
+ "myFirstName
should be a string with at least one character in it.",
+ "testString":
+ "assert((function(){if(typeof myFirstName !== \"undefined\" && typeof myFirstName === \"string\" && myFirstName.length > 0){return true;}else{return false;}})(), 'myFirstName
should be a string with at least one character in it.');"
},
{
- "text": "myLastName
should be a string with at least one character in it.",
- "testString": "assert((function(){if(typeof myLastName !== \"undefined\" && typeof myLastName === \"string\" && myLastName.length > 0){return true;}else{return false;}})(), 'myLastName
should be a string with at least one character in it.');"
+ "text":
+ "myLastName
should be a string with at least one character in it.",
+ "testString":
+ "assert((function(){if(typeof myLastName !== \"undefined\" && typeof myLastName === \"string\" && myLastName.length > 0){return true;}else{return false;}})(), 'myLastName
should be a string with at least one character in it.');"
}
],
"challengeType": 1,
@@ -1371,12 +1393,16 @@
],
"tests": [
{
- "text": "You should use two double quotes ("
) and four escaped double quotes (\"
).",
- "testString": "assert(code.match(/\\\\\"/g).length === 4 && code.match(/[^\\\\]\"/g).length === 2, 'You should use two double quotes ("
) and four escaped double quotes (\"
).');"
+ "text":
+ "You should use two double quotes ("
) and four escaped double quotes (\"
).",
+ "testString":
+ "assert(code.match(/\\\\\"/g).length === 4 && code.match(/[^\\\\]\"/g).length === 2, 'You should use two double quotes ("
) and four escaped double quotes (\"
).');"
},
{
- "text": "Variable myStr should contain the string: I am a \"double quoted\" string inside \"double quotes\".
",
- "testString": "assert(myStr === \"I am a \\\"double quoted\\\" string inside \\\"double quotes\\\".\", 'Variable myStr should contain the string: I am a \"double quoted\" string inside \"double quotes\".
');"
+ "text":
+ "Variable myStr should contain the string: I am a \"double quoted\" string inside \"double quotes\".
",
+ "testString":
+ "assert(myStr === \"I am a \\\"double quoted\\\" string inside \\\"double quotes\\\".\", 'Variable myStr should contain the string: I am a \"double quoted\" string inside \"double quotes\".
');"
}
],
"challengeType": 1,
@@ -1400,11 +1426,7 @@
"key": "indexjs",
"ext": "js",
"name": "index",
- "contents": [
- "var myStr = \"\"; // Change this line",
- "",
- ""
- ],
+ "contents": ["var myStr = \"\"; // Change this line", "", ""],
"head": [],
"tail": [
"(function(){",
@@ -1441,11 +1463,14 @@
"tests": [
{
"text": "Remove all the backslashes
(\\
)",
- "testString": "assert(!/\\\\/g.test(code) && myStr.match('\\\\s*\\\\s*Link\\\\s*\\\\s*'), 'Remove all the backslashes
(\\
)');"
+ "testString":
+ "assert(!/\\\\/g.test(code) && myStr.match('\\\\s*\\\\s*Link\\\\s*\\\\s*'), 'Remove all the backslashes
(\\
)');"
},
{
- "text": "You should have two single quotes '
and four double quotes "
",
- "testString": "assert(code.match(/\"/g).length === 4 && code.match(/'/g).length === 2, 'You should have two single quotes '
and four double quotes "
');"
+ "text":
+ "You should have two single quotes '
and four double quotes "
",
+ "testString":
+ "assert(code.match(/\"/g).length === 4 && code.match(/'/g).length === 2, 'You should have two single quotes '
and four double quotes "
');"
}
],
"challengeType": 1,
@@ -1473,9 +1498,7 @@
""
],
"head": [],
- "tail": [
- "(function() { return \"myStr = \" + myStr; })();"
- ]
+ "tail": ["(function() { return \"myStr = \" + myStr; })();"]
}
}
},
@@ -1500,27 +1523,38 @@
"tests": [
{
"text": "myStr
should not contain any spaces",
- "testString": "assert(!/ /.test(myStr), 'myStr
should not contain any spaces');"
+ "testString":
+ "assert(!/ /.test(myStr), 'myStr
should not contain any spaces');"
},
{
- "text": "myStr
should contain the strings FirstLine
, SecondLine
and ThirdLine
(remember case sensitivity)",
- "testString": "assert(/FirstLine/.test(myStr) && /SecondLine/.test(myStr) && /ThirdLine/.test(myStr), 'myStr
should contain the strings FirstLine
, SecondLine
and ThirdLine
(remember case sensitivity)');"
+ "text":
+ "myStr
should contain the strings FirstLine
, SecondLine
and ThirdLine
(remember case sensitivity)",
+ "testString":
+ "assert(/FirstLine/.test(myStr) && /SecondLine/.test(myStr) && /ThirdLine/.test(myStr), 'myStr
should contain the strings FirstLine
, SecondLine
and ThirdLine
(remember case sensitivity)');"
},
{
- "text": "FirstLine
should be followed by the newline character \\n
",
- "testString": "assert(/FirstLine\\n/.test(myStr), 'FirstLine
should be followed by the newline character \\n
');"
+ "text":
+ "FirstLine
should be followed by the newline character \\n
",
+ "testString":
+ "assert(/FirstLine\\n/.test(myStr), 'FirstLine
should be followed by the newline character \\n
');"
},
{
- "text": "myStr
should contain a tab character \\t
which follows a newline character",
- "testString": "assert(/\\n\\t/.test(myStr), 'myStr
should contain a tab character \\t
which follows a newline character');"
+ "text":
+ "myStr
should contain a tab character \\t
which follows a newline character",
+ "testString":
+ "assert(/\\n\\t/.test(myStr), 'myStr
should contain a tab character \\t
which follows a newline character');"
},
{
- "text": "SecondLine
should be preceded by the backslash character \\\\
",
- "testString": "assert(/\\SecondLine/.test(myStr), 'SecondLine
should be preceded by the backslash character \\\\
');"
+ "text":
+ "SecondLine
should be preceded by the backslash character \\\\
",
+ "testString":
+ "assert(/\\SecondLine/.test(myStr), 'SecondLine
should be preceded by the backslash character \\\\
');"
},
{
- "text": "There should be a newline character between SecondLine
and ThirdLine
",
- "testString": "assert(/SecondLine\\nThirdLine/.test(myStr), 'There should be a newline character between SecondLine
and ThirdLine
');"
+ "text":
+ "There should be a newline character between SecondLine
and ThirdLine
",
+ "testString":
+ "assert(/SecondLine\\nThirdLine/.test(myStr), 'There should be a newline character between SecondLine
and ThirdLine
');"
}
],
"challengeType": 1,
@@ -1541,11 +1575,7 @@
"key": "indexjs",
"ext": "js",
"name": "index",
- "contents": [
- "var myStr; // Change this line",
- "",
- ""
- ],
+ "contents": ["var myStr; // Change this line", "", ""],
"head": [],
"tail": [
"(function(){",
@@ -1572,20 +1602,27 @@
],
"tests": [
{
- "text": "myStr
should have a value of This is the start. This is the end.
",
- "testString": "assert(myStr === \"This is the start. This is the end.\", 'myStr
should have a value of This is the start. This is the end.
');"
+ "text":
+ "myStr
should have a value of This is the start. This is the end.
",
+ "testString":
+ "assert(myStr === \"This is the start. This is the end.\", 'myStr
should have a value of This is the start. This is the end.
');"
},
{
"text": "Use the +
operator to build myStr
",
- "testString": "assert(code.match(/([\"']).*([\"'])\\s*\\+\\s*([\"']).*([\"'])/g).length > 1, 'Use the +
operator to build myStr
');"
+ "testString":
+ "assert(code.match(/([\"']).*([\"'])\\s*\\+\\s*([\"']).*([\"'])/g).length > 1, 'Use the +
operator to build myStr
');"
},
{
- "text": "myStr
should be created using the var
keyword.",
- "testString": "assert(/var\\s+myStr/.test(code), 'myStr
should be created using the var
keyword.');"
+ "text":
+ "myStr
should be created using the var
keyword.",
+ "testString":
+ "assert(/var\\s+myStr/.test(code), 'myStr
should be created using the var
keyword.');"
},
{
- "text": "Make sure to assign the result to the myStr
variable.",
- "testString": "assert(/myStr\\s*=/.test(code), 'Make sure to assign the result to the myStr
variable.');"
+ "text":
+ "Make sure to assign the result to the myStr
variable.",
+ "testString":
+ "assert(/myStr\\s*=/.test(code), 'Make sure to assign the result to the myStr
variable.');"
}
],
"challengeType": 1,
@@ -1645,12 +1682,16 @@
],
"tests": [
{
- "text": "myStr
should have a value of This is the first sentence. This is the second sentence.
",
- "testString": "assert(myStr === \"This is the first sentence. This is the second sentence.\", 'myStr
should have a value of This is the first sentence. This is the second sentence.
');"
+ "text":
+ "myStr
should have a value of This is the first sentence. This is the second sentence.
",
+ "testString":
+ "assert(myStr === \"This is the first sentence. This is the second sentence.\", 'myStr
should have a value of This is the first sentence. This is the second sentence.
');"
},
{
- "text": "Use the +=
operator to build myStr
",
- "testString": "assert(code.match(/\\w\\s*\\+=\\s*[\"']/g).length > 1 && code.match(/\\w\\s*\\=\\s*[\"']/g).length > 1, 'Use the +=
operator to build myStr
');"
+ "text":
+ "Use the +=
operator to build myStr
",
+ "testString":
+ "assert(code.match(/\\w\\s*\\+=\\s*[\"']/g).length > 1 && code.match(/\\w\\s*\\=\\s*[\"']/g).length > 1, 'Use the +=
operator to build myStr
');"
}
],
"challengeType": 1,
@@ -1708,12 +1749,16 @@
],
"tests": [
{
- "text": "myName
should be set to a string at least 3 characters long",
- "testString": "assert(typeof myName !== 'undefined' && myName.length > 2, 'myName
should be set to a string at least 3 characters long');"
+ "text":
+ "myName
should be set to a string at least 3 characters long",
+ "testString":
+ "assert(typeof myName !== 'undefined' && myName.length > 2, 'myName
should be set to a string at least 3 characters long');"
},
{
- "text": "Use two +
operators to build myStr
with myName
inside it",
- "testString": "assert(code.match(/[\"']\\s*\\+\\s*myName\\s*\\+\\s*[\"']/g).length > 0, 'Use two +
operators to build myStr
with myName
inside it');"
+ "text":
+ "Use two +
operators to build myStr
with myName
inside it",
+ "testString":
+ "assert(code.match(/[\"']\\s*\\+\\s*myName\\s*\\+\\s*[\"']/g).length > 0, 'Use two +
operators to build myStr
with myName
inside it');"
}
],
"challengeType": 1,
@@ -1777,12 +1822,16 @@
],
"tests": [
{
- "text": "someAdjective
should be set to a string at least 3 characters long",
- "testString": "assert(typeof someAdjective !== 'undefined' && someAdjective.length > 2, 'someAdjective
should be set to a string at least 3 characters long');"
+ "text":
+ "someAdjective
should be set to a string at least 3 characters long",
+ "testString":
+ "assert(typeof someAdjective !== 'undefined' && someAdjective.length > 2, 'someAdjective
should be set to a string at least 3 characters long');"
},
{
- "text": "Append someAdjective
to myStr
using the +=
operator",
- "testString": "assert(code.match(/myStr\\s*\\+=\\s*someAdjective\\s*/).length > 0, 'Append someAdjective
to myStr
using the +=
operator');"
+ "text":
+ "Append someAdjective
to myStr
using the +=
operator",
+ "testString":
+ "assert(code.match(/myStr\\s*\\+=\\s*someAdjective\\s*/).length > 0, 'Append someAdjective
to myStr
using the +=
operator');"
}
],
"challengeType": 1,
@@ -1796,7 +1845,8 @@
]
}
},
- "guideUrl": "https://guide.freecodecamp.org/certificates/appending-variables-to-strings",
+ "guideUrl":
+ "https://guide.freecodecamp.org/certificates/appending-variables-to-strings",
"files": {
"indexjs": {
"key": "indexjs",
@@ -1850,17 +1900,21 @@
"tests": [
{
"text": "lastNameLength
should be equal to eight.",
- "testString": "assert((function(){if(typeof lastNameLength !== \"undefined\" && typeof lastNameLength === \"number\" && lastNameLength === 8){return true;}else{return false;}})(), 'lastNameLength
should be equal to eight.');"
+ "testString":
+ "assert((function(){if(typeof lastNameLength !== \"undefined\" && typeof lastNameLength === \"number\" && lastNameLength === 8){return true;}else{return false;}})(), 'lastNameLength
should be equal to eight.');"
},
{
- "text": "You should be getting the length of lastName
by using .length
like this: lastName.length
.",
- "testString": "assert((function(){if(code.match(/\\.length/gi) && code.match(/\\.length/gi).length >= 2 && code.match(/var lastNameLength \\= 0;/gi) && code.match(/var lastNameLength \\= 0;/gi).length >= 1){return true;}else{return false;}})(), 'You should be getting the length of lastName
by using .length
like this: lastName.length
.');"
+ "text":
+ "You should be getting the length of lastName
by using .length
like this: lastName.length
.",
+ "testString":
+ "assert((function(){if(code.match(/\\.length/gi) && code.match(/\\.length/gi).length >= 2 && code.match(/var lastNameLength \\= 0;/gi) && code.match(/var lastNameLength \\= 0;/gi).length >= 1){return true;}else{return false;}})(), 'You should be getting the length of lastName
by using .length
like this: lastName.length
.');"
}
],
"challengeType": 1,
"translations": {
"es": {
- "title": "Comprueba la propiedad longitud (length) de una variable tipo cadena",
+ "title":
+ "Comprueba la propiedad longitud (length) de una variable tipo cadena",
"description": [
"Las estructuras de datos
tienen propiedades
. Por ejemplo, las cadenas
tienen una propiedad llamada .length
que te dirá cuántos caracteres hay en la cadena.",
"Por ejemplo, si creamos una variable var firstName=\"Charles\"
, podemos averiguar la longitud de la cadena \"Charles\" usando la propiedad firstName.length
. ",
@@ -1913,18 +1967,22 @@
],
"tests": [
{
- "text": "The firstLetterOfLastName
variable should have the value of L
.",
- "testString": "assert(firstLetterOfLastName === 'L', 'The firstLetterOfLastName
variable should have the value of L
.');"
+ "text":
+ "The firstLetterOfLastName
variable should have the value of L
.",
+ "testString":
+ "assert(firstLetterOfLastName === 'L', 'The firstLetterOfLastName
variable should have the value of L
.');"
},
{
"text": "You should use bracket notation.",
- "testString": "assert(code.match(/firstLetterOfLastName\\s*?=\\s*?lastName\\[.*?\\]/), 'You should use bracket notation.');"
+ "testString":
+ "assert(code.match(/firstLetterOfLastName\\s*?=\\s*?lastName\\[.*?\\]/), 'You should use bracket notation.');"
}
],
"challengeType": 1,
"translations": {
"es": {
- "title": "Usa la notación de corchetes para encontrar el primer carácter de una cadena",
+ "title":
+ "Usa la notación de corchetes para encontrar el primer carácter de una cadena",
"description": [
"La notación de corchetes
es una forma de obtener el caracter en un índice
específico de una cadena.",
"Los computadoras no empiezan a contar desde 1 como hacen los humanos. Comienzan en 0 ",
@@ -1956,9 +2014,7 @@
""
],
"head": [],
- "tail": [
- "(function(v){return v;})(firstLetterOfLastName);"
- ]
+ "tail": ["(function(v){return v;})(firstLetterOfLastName);"]
}
}
},
@@ -1975,17 +2031,18 @@
"Correct the assignment to myStr
so it contains the string value of Hello World
using the approach shown in the example above."
],
"releasedOn": "January 1, 2016",
- "solutions": [
- "var myStr = \"Jello World\";\nmyStr = \"Hello World\";"
- ],
+ "solutions": ["var myStr = \"Jello World\";\nmyStr = \"Hello World\";"],
"tests": [
{
- "text": "myStr
should have a value of Hello World
",
- "testString": "assert(myStr === \"Hello World\", 'myStr
should have a value of Hello World
');"
+ "text":
+ "myStr
should have a value of Hello World
",
+ "testString":
+ "assert(myStr === \"Hello World\", 'myStr
should have a value of Hello World
');"
},
{
"text": "Do not change the code above the line",
- "testString": "assert(/myStr = \"Jello World\"/.test(code), 'Do not change the code above the line');"
+ "testString":
+ "assert(/myStr = \"Jello World\"/.test(code), 'Do not change the code above the line');"
}
],
"challengeType": 1,
@@ -2019,9 +2076,7 @@
""
],
"head": [],
- "tail": [
- "(function(v){return \"myStr = \" + v;})(myStr);"
- ]
+ "tail": ["(function(v){return \"myStr = \" + v;})(myStr);"]
}
}
},
@@ -2040,18 +2095,22 @@
],
"tests": [
{
- "text": "The thirdLetterOfLastName
variable should have the value of v
.",
- "testString": "assert(thirdLetterOfLastName === 'v', 'The thirdLetterOfLastName
variable should have the value of v
.');"
+ "text":
+ "The thirdLetterOfLastName
variable should have the value of v
.",
+ "testString":
+ "assert(thirdLetterOfLastName === 'v', 'The thirdLetterOfLastName
variable should have the value of v
.');"
},
{
"text": "You should use bracket notation.",
- "testString": "assert(code.match(/thirdLetterOfLastName\\s*?=\\s*?lastName\\[.*?\\]/), 'You should use bracket notation.');"
+ "testString":
+ "assert(code.match(/thirdLetterOfLastName\\s*?=\\s*?lastName\\[.*?\\]/), 'You should use bracket notation.');"
}
],
"challengeType": 1,
"translations": {
"es": {
- "title": "Usar la notación de corchetes para encontrar el n-ésimo caracter en una cadena",
+ "title":
+ "Usar la notación de corchetes para encontrar el n-ésimo caracter en una cadena",
"description": [
"También puede usar notación de corchetes
para obtener el caracter en otras posiciones dentro de una cadena.",
"Recuerda que los computadores empiezan a contar a 0, por lo que el primer caracter es en realidad el caracter cero.",
@@ -2080,9 +2139,7 @@
""
],
"head": [],
- "tail": [
- "(function(v){return v;})(thirdLetterOfLastName);"
- ]
+ "tail": ["(function(v){return v;})(thirdLetterOfLastName);"]
}
}
},
@@ -2102,17 +2159,21 @@
"tests": [
{
"text": "lastLetterOfLastName
should be \"e\".",
- "testString": "assert(lastLetterOfLastName === \"e\", 'lastLetterOfLastName
should be \"e\".');"
+ "testString":
+ "assert(lastLetterOfLastName === \"e\", 'lastLetterOfLastName
should be \"e\".');"
},
{
- "text": "You have to use .length
to get the last letter.",
- "testString": "assert(code.match(/\\.length/g).length === 2, 'You have to use .length
to get the last letter.');"
+ "text":
+ "You have to use .length
to get the last letter.",
+ "testString":
+ "assert(code.match(/\\.length/g).length === 2, 'You have to use .length
to get the last letter.');"
}
],
"challengeType": 1,
"translations": {
"es": {
- "title": "Usa notación de corchetes para encontrar el último caracter de una cadena",
+ "title":
+ "Usa notación de corchetes para encontrar el último caracter de una cadena",
"description": [
"Con el fin de conseguir la última letra de una cadena, puedes restar uno a la longitud de la cadena.",
"Por ejemplo, si var firstName = \"Charles\"
, se puede obtener la última letra usando firstName[firstName.length - 1]
. ",
@@ -2141,15 +2202,14 @@
""
],
"head": [],
- "tail": [
- "(function(v){return v;})(lastLetterOfLastName);"
- ]
+ "tail": ["(function(v){return v;})(lastLetterOfLastName);"]
}
}
},
{
"id": "bd7123c9c452eddfaeb5bdef",
- "title": "Use Bracket Notation to Find the Nth-to-Last Character in a String",
+ "title":
+ "Use Bracket Notation to Find the Nth-to-Last Character in a String",
"description": [
"You can use the same principle we just used to retrieve the last character in a string to retrieve the Nth-to-last character.",
"For example, you can get the value of the third-to-last letter of the var firstName = \"Charles\"
string by using firstName[firstName.length - 3]
",
@@ -2163,17 +2223,21 @@
"tests": [
{
"text": "secondToLastLetterOfLastName
should be \"c\".",
- "testString": "assert(secondToLastLetterOfLastName === 'c', 'secondToLastLetterOfLastName
should be \"c\".');"
+ "testString":
+ "assert(secondToLastLetterOfLastName === 'c', 'secondToLastLetterOfLastName
should be \"c\".');"
},
{
- "text": "You have to use .length
to get the second last letter.",
- "testString": "assert(code.match(/\\.length/g).length === 2, 'You have to use .length
to get the second last letter.');"
+ "text":
+ "You have to use .length
to get the second last letter.",
+ "testString":
+ "assert(code.match(/\\.length/g).length === 2, 'You have to use .length
to get the second last letter.');"
}
],
"challengeType": 1,
"translations": {
"es": {
- "title": "Usa notación de corchetes para encontrar el n-ésimo último caracter de una cadena",
+ "title":
+ "Usa notación de corchetes para encontrar el n-ésimo último caracter de una cadena",
"description": [
"Puede utilizar el mismo principio utilizamos para recuperar el último caracter de una cadena para recuperar el n-ésimo último caracter.",
"Por ejemplo, se puede obtener el valor de la tercera última letra de la cadena var firstName = \"Charles\"
utilizando firstName[firstName.length - 3]
",
@@ -2202,9 +2266,7 @@
""
],
"head": [],
- "tail": [
- "(function(v){return v;})(secondToLastLetterOfLastName);"
- ]
+ "tail": ["(function(v){return v;})(secondToLastLetterOfLastName);"]
}
}
},
@@ -2227,16 +2289,22 @@
],
"tests": [
{
- "text": "wordBlanks(\"\",\"\",\"\",\"\")
should return a string.",
- "testString": "assert(typeof wordBlanks(\"\",\"\",\"\",\"\") === 'string', 'wordBlanks(\"\",\"\",\"\",\"\")
should return a string.');"
+ "text":
+ "wordBlanks(\"\",\"\",\"\",\"\")
should return a string.",
+ "testString":
+ "assert(typeof wordBlanks(\"\",\"\",\"\",\"\") === 'string', 'wordBlanks(\"\",\"\",\"\",\"\")
should return a string.');"
},
{
- "text": "wordBlanks(\"dog\", \"big\", \"ran\", \"quickly\")
should contain all of the passed in words separated by non-word characters (and any additional words in your madlib).",
- "testString": "assert(/\\bdog\\b/.test(test1) && /\\bbig\\b/.test(test1) && /\\bran\\b/.test(test1) && /\\bquickly\\b/.test(test1),'wordBlanks(\"dog\", \"big\", \"ran\", \"quickly\")
should contain all of the passed in words separated by non-word characters (and any additional words in your madlib).');"
+ "text":
+ "wordBlanks(\"dog\", \"big\", \"ran\", \"quickly\")
should contain all of the passed in words separated by non-word characters (and any additional words in your madlib).",
+ "testString":
+ "assert(/\\bdog\\b/.test(test1) && /\\bbig\\b/.test(test1) && /\\bran\\b/.test(test1) && /\\bquickly\\b/.test(test1),'wordBlanks(\"dog\", \"big\", \"ran\", \"quickly\")
should contain all of the passed in words separated by non-word characters (and any additional words in your madlib).');"
},
{
- "text": "wordBlanks(\"cat\", \"little\", \"hit\", \"slowly\")
should contain all of the passed in words separated by non-word characters (and any additional words in your madlib).",
- "testString": "assert(/\\bcat\\b/.test(test2) && /\\blittle\\b/.test(test2) && /\\bhit\\b/.test(test2) && /\\bslowly\\b/.test(test2),'wordBlanks(\"cat\", \"little\", \"hit\", \"slowly\")
should contain all of the passed in words separated by non-word characters (and any additional words in your madlib).');"
+ "text":
+ "wordBlanks(\"cat\", \"little\", \"hit\", \"slowly\")
should contain all of the passed in words separated by non-word characters (and any additional words in your madlib).",
+ "testString":
+ "assert(/\\bcat\\b/.test(test2) && /\\blittle\\b/.test(test2) && /\\bhit\\b/.test(test2) && /\\bslowly\\b/.test(test2),'wordBlanks(\"cat\", \"little\", \"hit\", \"slowly\")
should contain all of the passed in words separated by non-word characters (and any additional words in your madlib).');"
}
],
"challengeType": 1,
@@ -2287,27 +2355,31 @@
"Modify the new array myArray
so that it contains both a string
and a number
(in that order).",
"Hint
Refer to the example code in the text editor if you get stuck."
],
- "solutions": [
- "var myArray = [\"The Answer\", 42];"
- ],
+ "solutions": ["var myArray = [\"The Answer\", 42];"],
"tests": [
{
"text": "myArray
should be an array
.",
- "testString": "assert(typeof myArray == 'object', 'myArray
should be an array
.');"
+ "testString":
+ "assert(typeof myArray == 'object', 'myArray
should be an array
.');"
},
{
- "text": "The first item in myArray
should be a string
.",
- "testString": "assert(typeof myArray[0] !== 'undefined' && typeof myArray[0] == 'string', 'The first item in myArray
should be a string
.');"
+ "text":
+ "The first item in myArray
should be a string
.",
+ "testString":
+ "assert(typeof myArray[0] !== 'undefined' && typeof myArray[0] == 'string', 'The first item in myArray
should be a string
.');"
},
{
- "text": "The second item in myArray
should be a number
.",
- "testString": "assert(typeof myArray[1] !== 'undefined' && typeof myArray[1] == 'number', 'The second item in myArray
should be a number
.');"
+ "text":
+ "The second item in myArray
should be a number
.",
+ "testString":
+ "assert(typeof myArray[1] !== 'undefined' && typeof myArray[1] == 'number', 'The second item in myArray
should be a number
.');"
}
],
"challengeType": 1,
"translations": {
"es": {
- "title": "Almacena múltiples valores en una variable utilizando vectores en JavaScript",
+ "title":
+ "Almacena múltiples valores en una variable utilizando vectores en JavaScript",
"description": [
"Con las variables tipo vector
(o en inglés array
) podemos almacenar diversos datos en un solo lugar.",
"Empiezas la declaración de un vector con un corchete de apertura, y terminas con un corchete de cierre, y pones una coma entre cada entrada, así: var sandwich = [\"mantequilla de maní\", \"jalea\" , \"pan\"]
. ",
@@ -2331,9 +2403,7 @@
""
],
"head": [],
- "tail": [
- "(function(z){return z;})(myArray);"
- ]
+ "tail": ["(function(z){return z;})(myArray);"]
}
}
},
@@ -2345,13 +2415,13 @@
"
",
"Create a nested array called myArray
."
],
- "solutions": [
- "var myArray = [[1,2,3]];"
- ],
+ "solutions": ["var myArray = [[1,2,3]];"],
"tests": [
{
- "text": "myArray
should have at least one array nested within another array.",
- "testString": "assert(Array.isArray(myArray) && myArray.some(Array.isArray), 'myArray
should have at least one array nested within another array.');"
+ "text":
+ "myArray
should have at least one array nested within another array.",
+ "testString":
+ "assert(Array.isArray(myArray) && myArray.some(Array.isArray), 'myArray
should have at least one array nested within another array.');"
}
],
"challengeType": 1,
@@ -2397,17 +2467,19 @@
"
",
"Create a variable called myData
and set it to equal the first value of myArray
using bracket notation."
],
- "solutions": [
- "var myArray = [50,60,70];\nvar myData = myArray[0];"
- ],
+ "solutions": ["var myArray = [50,60,70];\nvar myData = myArray[0];"],
"tests": [
{
- "text": "The variable myData
should equal the first value of myArray
.",
- "testString": "assert((function(){if(typeof myArray !== 'undefined' && typeof myData !== 'undefined' && myArray[0] === myData){return true;}else{return false;}})(), 'The variable myData
should equal the first value of myArray
.');"
+ "text":
+ "The variable myData
should equal the first value of myArray
.",
+ "testString":
+ "assert((function(){if(typeof myArray !== 'undefined' && typeof myData !== 'undefined' && myArray[0] === myData){return true;}else{return false;}})(), 'The variable myData
should equal the first value of myArray
.');"
},
{
- "text": "The data in variable myArray
should be accessed using bracket notation.",
- "testString": "assert((function(){if(code.match(/\\s*=\\s*myArray\\[0\\]/g)){return true;}else{return false;}})(), 'The data in variable myArray
should be accessed using bracket notation.');"
+ "text":
+ "The data in variable myArray
should be accessed using bracket notation.",
+ "testString":
+ "assert((function(){if(code.match(/\\s*=\\s*myArray\\[0\\]/g)){return true;}else{return false;}})(), 'The data in variable myArray
should be accessed using bracket notation.');"
}
],
"challengeType": 1,
@@ -2426,7 +2498,8 @@
]
}
},
- "guideUrl": "https://guide.freecodecamp.org/certificates/access-array-data-with-indexes",
+ "guideUrl":
+ "https://guide.freecodecamp.org/certificates/access-array-data-with-indexes",
"files": {
"indexjs": {
"key": "indexjs",
@@ -2461,17 +2534,18 @@
"
",
"Modify the data stored at index 0
of myArray
to a value of 45
."
],
- "solutions": [
- "var myArray = [18,64,99];\nmyArray[0] = 45;"
- ],
+ "solutions": ["var myArray = [18,64,99];\nmyArray[0] = 45;"],
"tests": [
{
"text": "myArray
should now be [45,64,99].",
- "testString": "assert((function(){if(typeof myArray != 'undefined' && myArray[0] == 45 && myArray[1] == 64 && myArray[2] == 99){return true;}else{return false;}})(), 'myArray
should now be [45,64,99].');"
+ "testString":
+ "assert((function(){if(typeof myArray != 'undefined' && myArray[0] == 45 && myArray[1] == 64 && myArray[2] == 99){return true;}else{return false;}})(), 'myArray
should now be [45,64,99].');"
},
{
- "text": "You should be using correct index to modify the value in myArray
.",
- "testString": "assert((function(){if(code.match(/myArray\\[0\\]\\s*=\\s*/g)){return true;}else{return false;}})(), 'You should be using correct index to modify the value in myArray
.');"
+ "text":
+ "You should be using correct index to modify the value in myArray
.",
+ "testString":
+ "assert((function(){if(code.match(/myArray\\[0\\]\\s*=\\s*/g)){return true;}else{return false;}})(), 'You should be using correct index to modify the value in myArray
.');"
}
],
"challengeType": 1,
@@ -2518,7 +2592,7 @@
"description": [
"One way to think of a multi-dimensional array, is as an array of arrays. When you use brackets to access your array, the first set of brackets refers to the entries in the outer-most (the first level) array, and each additional pair of brackets refers to the next level of entries inside.",
"Example",
- "var arr = [
[1,2,3],
[4,5,6],
[7,8,9],
[[10,11,12], 13, 14]
];
arr[3]; // equals [[10,11,12], 13, 14]
arr[3][0]; // equals [10,11,12]
arr[3][0][1]; // equals 11
",
+ "var arr = [
[1,2,3],
[4,5,6],
[7,8,9],
[[10,11,12], 13, 14]
];
arr[3]; // equals [[10,11,12], 13, 14]
arr[3][0]; // equals [10,11,12]
arr[3][0][1]; // equals 11
",
"Note
There shouldn't be any spaces between the array name and the square brackets, like array [0][0]
and even this array [0] [0]
is not allowed. Although JavaScript is able to process this correctly, this may confuse other programmers reading your code.",
"
",
"Using bracket notation select an element from myArray
such that myData
is equal to 8
."
@@ -2530,11 +2604,14 @@
"tests": [
{
"text": "myData
should be equal to 8
.",
- "testString": "assert(myData === 8, 'myData
should be equal to 8
.');"
+ "testString":
+ "assert(myData === 8, 'myData
should be equal to 8
.');"
},
{
- "text": "You should be using bracket notation to read the correct value from myArray
.",
- "testString": "assert(/myArray\\[2\\]\\[1\\]/g.test(code) && !/myData\\s*=\\s*(?:.*[-+*/%]|\\d)/g.test(code), 'You should be using bracket notation to read the correct value from myArray
.');"
+ "text":
+ "You should be using bracket notation to read the correct value from myArray
.",
+ "testString":
+ "assert(/myArray\\[2\\]\\[1\\]/g.test(code) && !/myData\\s*=\\s*(?:.*[-+*/%]|\\d)/g.test(code), 'You should be using bracket notation to read the correct value from myArray
.');"
}
],
"challengeType": 1,
@@ -2544,13 +2621,14 @@
"description": [
"Una manera de pensar un vector multi-dimensional, es como un vector de vectores. Cuando usas corchetes para acceder a tu vector, el primer conjunto de brackets se refiere a las entradas en el vector más externo y cada nivel subsecuente de brackets se refiere al siguiente nivel de vectores internos.",
"Ejemplo",
- "var vec = [
[1,2,3],
[4,5,6],
[7,8,9],
[[10,11,12], 13, 14]
];
vec[0]; // es igual [1,2,3]
vec[1][2]; // es igual 6
vec[3][0][1]; // es igual 11
",
+ "var vec = [
[1,2,3],
[4,5,6],
[7,8,9],
[[10,11,12], 13, 14]
];
vec[0]; // es igual [1,2,3]
vec[1][2]; // es igual 6
vec[3][0][1]; // es igual 11
",
"Instrucciones
",
"Lee de myArray
usando la notación corchete de modo que myData sea igual a 8
"
]
}
},
- "guideUrl": "https://guide.freecodecamp.org/certificates/access-array-data-with-indexes",
+ "guideUrl":
+ "https://guide.freecodecamp.org/certificates/access-array-data-with-indexes",
"files": {
"indexjs": {
"key": "indexjs",
@@ -2586,8 +2664,10 @@
],
"tests": [
{
- "text": "myArray
should now equal [[\"John\", 23], [\"cat\", 2], [\"dog\", 3]]
.",
- "testString": "assert((function(d){if(d[2] != undefined && d[0][0] == 'John' && d[0][1] === 23 && d[2][0] == 'dog' && d[2][1] === 3 && d[2].length == 2){return true;}else{return false;}})(myArray), 'myArray
should now equal [[\"John\", 23], [\"cat\", 2], [\"dog\", 3]]
.');"
+ "text":
+ "myArray
should now equal [[\"John\", 23], [\"cat\", 2], [\"dog\", 3]]
.",
+ "testString":
+ "assert((function(d){if(d[2] != undefined && d[0][0] == 'John' && d[0][1] === 23 && d[2][0] == 'dog' && d[2][1] === 3 && d[2].length == 2){return true;}else{return false;}})(myArray), 'myArray
should now equal [[\"John\", 23], [\"cat\", 2], [\"dog\", 3]]
.');"
}
],
"challengeType": 1,
@@ -2642,16 +2722,21 @@
],
"tests": [
{
- "text": "myArray
should only contain [[\"John\", 23]]
.",
- "testString": "assert((function(d){if(d[0][0] == 'John' && d[0][1] === 23 && d[1] == undefined){return true;}else{return false;}})(myArray), 'myArray
should only contain [[\"John\", 23]]
.');"
+ "text":
+ "myArray
should only contain [[\"John\", 23]]
.",
+ "testString":
+ "assert((function(d){if(d[0][0] == 'John' && d[0][1] === 23 && d[1] == undefined){return true;}else{return false;}})(myArray), 'myArray
should only contain [[\"John\", 23]]
.');"
},
{
"text": "Use pop()
on myArray
",
- "testString": "assert(/removedFromMyArray\\s*=\\s*myArray\\s*.\\s*pop\\s*(\\s*)/.test(code), 'Use pop()
on myArray
');"
+ "testString":
+ "assert(/removedFromMyArray\\s*=\\s*myArray\\s*.\\s*pop\\s*(\\s*)/.test(code), 'Use pop()
on myArray
');"
},
{
- "text": "removedFromMyArray
should only contain [\"cat\", 2]
.",
- "testString": "assert((function(d){if(d[0] == 'cat' && d[1] === 2 && d[2] == undefined){return true;}else{return false;}})(removedFromMyArray), 'removedFromMyArray
should only contain [\"cat\", 2]
.');"
+ "text":
+ "removedFromMyArray
should only contain [\"cat\", 2]
.",
+ "testString":
+ "assert((function(d){if(d[0] == 'cat' && d[1] === 2 && d[2] == undefined){return true;}else{return false;}})(removedFromMyArray), 'removedFromMyArray
should only contain [\"cat\", 2]
.');"
}
],
"challengeType": 1,
@@ -2707,12 +2792,16 @@
],
"tests": [
{
- "text": "myArray
should now equal [[\"dog\", 3]]
.",
- "testString": "assert((function(d){if(d[0][0] == 'dog' && d[0][1] === 3 && d[1] == undefined){return true;}else{return false;}})(myArray), 'myArray
should now equal [[\"dog\", 3]]
.');"
+ "text":
+ "myArray
should now equal [[\"dog\", 3]]
.",
+ "testString":
+ "assert((function(d){if(d[0][0] == 'dog' && d[0][1] === 3 && d[1] == undefined){return true;}else{return false;}})(myArray), 'myArray
should now equal [[\"dog\", 3]]
.');"
},
{
- "text": "removedFromMyArray
should contain [\"John\", 23]
.",
- "testString": "assert((function(d){if(d[0] == 'John' && d[1] === 23 && typeof removedFromMyArray === 'object'){return true;}else{return false;}})(removedFromMyArray), 'removedFromMyArray
should contain [\"John\", 23]
.');"
+ "text":
+ "removedFromMyArray
should contain [\"John\", 23]
.",
+ "testString":
+ "assert((function(d){if(d[0] == 'John' && d[1] === 23 && typeof removedFromMyArray === 'object'){return true;}else{return false;}})(removedFromMyArray), 'removedFromMyArray
should contain [\"John\", 23]
.');"
}
],
"challengeType": 1,
@@ -2767,8 +2856,10 @@
],
"tests": [
{
- "text": "myArray
should now have [[\"Paul\", 35], [\"dog\", 3]].",
- "testString": "assert((function(d){if(typeof d[0] === \"object\" && d[0][0] == 'Paul' && d[0][1] === 35 && d[1][0] != undefined && d[1][0] == 'dog' && d[1][1] != undefined && d[1][1] == 3){return true;}else{return false;}})(myArray), 'myArray
should now have [[\"Paul\", 35], [\"dog\", 3]].');"
+ "text":
+ "myArray
should now have [[\"Paul\", 35], [\"dog\", 3]].",
+ "testString":
+ "assert((function(d){if(typeof d[0] === \"object\" && d[0][0] == 'Paul' && d[0][1] === 35 && d[1][0] != undefined && d[1][0] == 'dog' && d[1][1] != undefined && d[1][1] == 3){return true;}else{return false;}})(myArray), 'myArray
should now have [[\"Paul\", 35], [\"dog\", 3]].');"
}
],
"challengeType": 1,
@@ -2826,19 +2917,25 @@
"tests": [
{
"text": "myList
should be an array",
- "testString": "assert(isArray, 'myList
should be an array');"
+ "testString":
+ "assert(isArray, 'myList
should be an array');"
},
{
- "text": "The first elements in each of your sub-arrays must all be strings",
- "testString": "assert(hasString, 'The first elements in each of your sub-arrays must all be strings');"
+ "text":
+ "The first elements in each of your sub-arrays must all be strings",
+ "testString":
+ "assert(hasString, 'The first elements in each of your sub-arrays must all be strings');"
},
{
- "text": "The second elements in each of your sub-arrays must all be numbers",
- "testString": "assert(hasNumber, 'The second elements in each of your sub-arrays must all be numbers');"
+ "text":
+ "The second elements in each of your sub-arrays must all be numbers",
+ "testString":
+ "assert(hasNumber, 'The second elements in each of your sub-arrays must all be numbers');"
},
{
"text": "You must have at least 5 items in your list",
- "testString": "assert(count > 4, 'You must have at least 5 items in your list');"
+ "testString":
+ "assert(count > 4, 'You must have at least 5 items in your list');"
}
],
"challengeType": 1,
@@ -2858,11 +2955,7 @@
"key": "indexjs",
"ext": "js",
"name": "index",
- "contents": [
- "var myList = [];",
- "",
- ""
- ],
+ "contents": ["var myList = [];", "", ""],
"head": [],
"tail": [
"var count = 0;",
@@ -2901,7 +2994,7 @@
"description": [
"In JavaScript, we can divide up our code into reusable parts called functions.",
"Here's an example of a function:",
- "function functionName() {
console.log(\"Hello World\");
}
",
+ "function functionName() {
console.log(\"Hello World\");
}
",
"You can call or invoke this function by using its name followed by parentheses, like this:",
"functionName();
",
"Each time the function is called it will print out the message \"Hello World\"
on the dev console. All of the code between the curly braces will be executed every time the function is called.",
@@ -2914,15 +3007,19 @@
"tests": [
{
"text": "reusableFunction
should be a function",
- "testString": "assert(typeof reusableFunction === 'function', 'reusableFunction
should be a function');"
+ "testString":
+ "assert(typeof reusableFunction === 'function', 'reusableFunction
should be a function');"
},
{
- "text": "reusableFunction
should output \"Hi World\" to the dev console",
- "testString": "assert(\"Hi World\" === logOutput, 'reusableFunction
should output \"Hi World\" to the dev console');"
+ "text":
+ "reusableFunction
should output \"Hi World\" to the dev console",
+ "testString":
+ "assert(\"Hi World\" === logOutput, 'reusableFunction
should output \"Hi World\" to the dev console');"
},
{
"text": "Call reusableFunction
after you define it",
- "testString": "assert(/^\\s*reusableFunction\\(\\)\\s*;/m.test(code), 'Call reusableFunction
after you define it');"
+ "testString":
+ "assert(/^\\s*reusableFunction\\(\\)\\s*;/m.test(code), 'Call reusableFunction
after you define it');"
}
],
"challengeType": 1,
@@ -2998,7 +3095,7 @@
"description": [
"Parameters are variables that act as placeholders for the values that are to be input to a function when it is called. When a function is defined, it is typically defined along with one or more parameters. The actual values that are input (or \"passed\") into a function when it is called are known as arguments.",
"Here is a function with two parameters, param1
and param2
:",
- "function testFun(param1, param2) {
console.log(param1, param2);
}
",
+ "function testFun(param1, param2) {
console.log(param1, param2);
}
",
"Then we can call testFun
:",
"testFun(\"Hello\", \"World\");
",
"We have passed two arguments, \"Hello\"
and \"World\"
. Inside the function, param1
will equal \"Hello\" and param2
will equal \"World\". Note that you could call testFun
again with different arguments and the parameters would take on the value of the new arguments.",
@@ -3012,19 +3109,26 @@
"tests": [
{
"text": "functionWithArgs
should be a function",
- "testString": "assert(typeof functionWithArgs === 'function', 'functionWithArgs
should be a function');"
+ "testString":
+ "assert(typeof functionWithArgs === 'function', 'functionWithArgs
should be a function');"
},
{
- "text": "functionWithArgs(1,2)
should output 3
",
- "testString": "if(typeof functionWithArgs === \"function\") { capture(); functionWithArgs(1,2); uncapture(); } assert(logOutput == 3, 'functionWithArgs(1,2)
should output 3
');"
+ "text":
+ "functionWithArgs(1,2)
should output 3
",
+ "testString":
+ "if(typeof functionWithArgs === \"function\") { capture(); functionWithArgs(1,2); uncapture(); } assert(logOutput == 3, 'functionWithArgs(1,2)
should output 3
');"
},
{
- "text": "functionWithArgs(7,9)
should output 16
",
- "testString": "if(typeof functionWithArgs === \"function\") { capture(); functionWithArgs(7,9); uncapture(); } assert(logOutput == 16, 'functionWithArgs(7,9)
should output 16
');"
+ "text":
+ "functionWithArgs(7,9)
should output 16
",
+ "testString":
+ "if(typeof functionWithArgs === \"function\") { capture(); functionWithArgs(7,9); uncapture(); } assert(logOutput == 16, 'functionWithArgs(7,9)
should output 16
');"
},
{
- "text": "Call functionWithArgs
with two numbers after you define it.",
- "testString": "assert(/^\\s*functionWithArgs\\s*\\(\\s*\\d+\\s*,\\s*\\d+\\s*\\)\\s*;/m.test(code), 'Call functionWithArgs
with two numbers after you define it.');"
+ "text":
+ "Call functionWithArgs
with two numbers after you define it.",
+ "testString":
+ "assert(/^\\s*functionWithArgs\\s*\\(\\s*\\d+\\s*,\\s*\\d+\\s*\\)\\s*;/m.test(code), 'Call functionWithArgs
with two numbers after you define it.');"
}
],
"challengeType": 1,
@@ -3034,7 +3138,7 @@
"description": [
"Los parámetros son variables que actúan como marcadores de lugar para los valores que han de ser entrada para una función cuando esta es llamada. Cuando una función es definida, es típicamente definida con uno o más parámetros. Los valores actuales que son entrada (or \"pasados\") dentro de una función cuando esta es llamada son concidos como argumentos.",
"Aquí hay una función con dos parámetros, param1
y param2
:",
- "function testFun(param1, param2) {
console.log(param1, param2);
}
",
+ "function testFun(param1, param2) {
console.log(param1, param2);
}
",
"Entonces nosotros podemos llamar testFun
:",
"testFun(\"Hello\", \"World\");
",
"Nosotros hemos pasado dos argumentos, \"Hello\"
y \"World\"
. Dentro de la función, param1
será igual a \"Hello\" y param2
será igual a \"World\". Nota que puedes llamar testFun
otra vez con argumentos diferentes y los parámetros asumirían el valor de los nuevos argumentos.",
@@ -3110,19 +3214,26 @@
"tests": [
{
"text": "myGlobal
should be defined",
- "testString": "assert(typeof myGlobal != \"undefined\", 'myGlobal
should be defined');"
+ "testString":
+ "assert(typeof myGlobal != \"undefined\", 'myGlobal
should be defined');"
},
{
- "text": "myGlobal
should have a value of 10
",
- "testString": "assert(myGlobal === 10, 'myGlobal
should have a value of 10
');"
+ "text":
+ "myGlobal
should have a value of 10
",
+ "testString":
+ "assert(myGlobal === 10, 'myGlobal
should have a value of 10
');"
},
{
- "text": "myGlobal
should be declared using the var
keyword",
- "testString": "assert(/var\\s+myGlobal/.test(code), 'myGlobal
should be declared using the var
keyword');"
+ "text":
+ "myGlobal
should be declared using the var
keyword",
+ "testString":
+ "assert(/var\\s+myGlobal/.test(code), 'myGlobal
should be declared using the var
keyword');"
},
{
- "text": "oopsGlobal
should be a global variable and have a value of 5
",
- "testString": "assert(typeof oopsGlobal != \"undefined\" && oopsGlobal === 5, 'oopsGlobal
should be a global variable and have a value of 5
');"
+ "text":
+ "oopsGlobal
should be a global variable and have a value of 5
",
+ "testString":
+ "assert(typeof oopsGlobal != \"undefined\" && oopsGlobal === 5, 'oopsGlobal
should be a global variable and have a value of 5
');"
}
],
"challengeType": 1,
@@ -3201,7 +3312,7 @@
"description": [
"Variables which are declared within a function, as well as the function parameters have local scope. That means, they are only visible within that function.",
"Here is a function myTest
with a local variable called loc
.",
- "function myTest() {
var loc = \"foo\";
console.log(loc);
}
myTest(); // logs \"foo\"
console.log(loc); // loc is not defined
",
+ "function myTest() {
var loc = \"foo\";
console.log(loc);
}
myTest(); // logs \"foo\"
console.log(loc); // loc is not defined
",
"loc
is not defined outside of the function.",
"
",
"Declare a local variable myVar
inside myLocalScope
. Run the tests and then follow the instructions commented out in the editor.",
@@ -3214,11 +3325,13 @@
"tests": [
{
"text": "No global myVar
variable",
- "testString": "assert(typeof myVar === 'undefined', 'No global myVar
variable');"
+ "testString":
+ "assert(typeof myVar === 'undefined', 'No global myVar
variable');"
},
{
"text": "Add a local myVar
variable",
- "testString": "assert(/var\\s+myVar/.test(code), 'Add a local myVar
variable');"
+ "testString":
+ "assert(/var\\s+myVar/.test(code), 'Add a local myVar
variable');"
}
],
"challengeType": 1,
@@ -3228,7 +3341,7 @@
"description": [
"Las variables que son declaradas dentro de una función, así como los parámetros de la función tienen alcance local. Eso significa que solo son visibles dentro de esa función.",
"Aquí está una función myTest
con una variable local llamada loc
.",
- "function myTest() {
var loc = \"foo\";
console.log(loc);
}
myTest(); // \"foo\"
console.log(loc); // \"undefined\"
",
+ "function myTest() {
var loc = \"foo\";
console.log(loc);
}
myTest(); // \"foo\"
console.log(loc); // \"undefined\"
",
"loc
no está definida fuera de la función.",
"Instrucciones
",
"Declara una variable local myVar
dentro de myLocalScope
"
@@ -3289,7 +3402,7 @@
"description": [
"It is possible to have both local and global variables with the same name. When you do this, the local
variable takes precedence over the global
variable.",
"In this example:",
- "var someVar = \"Hat\";
function myFun() {
var someVar = \"Head\";
return someVar;
}
",
+ "var someVar = \"Hat\";
function myFun() {
var someVar = \"Head\";
return someVar;
}
",
"The function myFun
will return \"Head\"
because the local
version of the variable is present.",
"
",
"Add a local variable to myOutfit
function to override the value of outerWear
with \"sweater\"
."
@@ -3300,16 +3413,21 @@
],
"tests": [
{
- "text": "Do not change the value of the global outerWear
",
- "testString": "assert(outerWear === \"T-Shirt\", 'Do not change the value of the global outerWear
');"
+ "text":
+ "Do not change the value of the global outerWear
",
+ "testString":
+ "assert(outerWear === \"T-Shirt\", 'Do not change the value of the global outerWear
');"
},
{
- "text": "myOutfit
should return \"sweater\"
",
- "testString": "assert(myOutfit() === \"sweater\", 'myOutfit
should return \"sweater\"
');"
+ "text":
+ "myOutfit
should return \"sweater\"
",
+ "testString":
+ "assert(myOutfit() === \"sweater\", 'myOutfit
should return \"sweater\"
');"
},
{
"text": "Do not change the return statement",
- "testString": "assert(/return outerWear/.test(code), 'Do not change the return statement');"
+ "testString":
+ "assert(/return outerWear/.test(code), 'Do not change the return statement');"
}
],
"challengeType": 1,
@@ -3319,7 +3437,7 @@
"description": [
"Es posible tener variables locales y globales con el mismo nombre. Cuando tu haces esto, la variable local
toma precedencia sobre la variable global
.",
"En este ejemplo:",
- "var algunaVar = \"Sombrero\";
function miFun() {
var algunaVar = \"Cabeza\";
return algunaVar;
}
",
+ "var algunaVar = \"Sombrero\";
function miFun() {
var algunaVar = \"Cabeza\";
return algunaVar;
}
",
"La función miFun
regresará \"Cabeza\"
porque la versión local
de la variable tiene precedencia.",
"Instrucciones
",
"Agrega una variable local a myOutfit
para sobreescribir el valor de outerWear
con \"sweater\"
."
@@ -3357,7 +3475,7 @@
"description": [
"We can pass values into a function with arguments. You can use a return
statement to send a value back out of a function.",
"Example",
- "function plusThree(num) {
return num + 3;
}
var answer = plusThree(5); // 8
",
+ "function plusThree(num) {
return num + 3;
}
var answer = plusThree(5); // 8
",
"plusThree
takes an argument for num
and returns a value equal to num + 3
.",
"
",
"Create a function timesFive
that accepts one argument, multiplies it by 5
, and returns the new value. See the last line in the editor for an example of how you can test your timesFive
function."
@@ -3369,23 +3487,29 @@
"tests": [
{
"text": "timesFive
should be a function",
- "testString": "assert(typeof timesFive === 'function', 'timesFive
should be a function');"
+ "testString":
+ "assert(typeof timesFive === 'function', 'timesFive
should be a function');"
},
{
- "text": "function timesFive
should be called with a number",
- "testString": "assert(code.match(/timesFive\\(\\s*\\d+\\s*\\)/g), 'function timesFive
should be called with a number');"
+ "text":
+ "function timesFive
should be called with a number",
+ "testString":
+ "assert(code.match(/timesFive\\(\\s*\\d+\\s*\\)/g), 'function timesFive
should be called with a number');"
},
{
"text": "timesFive(5)
should return 25
",
- "testString": "assert(timesFive(5) === 25, 'timesFive(5)
should return 25
');"
+ "testString":
+ "assert(timesFive(5) === 25, 'timesFive(5)
should return 25
');"
},
{
"text": "timesFive(2)
should return 10
",
- "testString": "assert(timesFive(2) === 10, 'timesFive(2)
should return 10
');"
+ "testString":
+ "assert(timesFive(2) === 10, 'timesFive(2)
should return 10
');"
},
{
"text": "timesFive(0)
should return 0
",
- "testString": "assert(timesFive(0) === 0, 'timesFive(0)
should return 0
');"
+ "testString":
+ "assert(timesFive(0) === 0, 'timesFive(0)
should return 0
');"
}
],
"challengeType": 1,
@@ -3395,7 +3519,7 @@
"description": [
"Podemos pasar valores a una función mediante los argumentos. Puedes usar una sentencia return
para enviar un valor de vuelta de una función.",
"Ejemplo",
- "function masTres(num) {
return num + 3;
}
var respuesta = masTres(5); // 8
",
+ "function masTres(num) {
return num + 3;
}
var respuesta = masTres(5); // 8
",
"masTres
toma un argumento que es num
y retorna un valor igual a num + 3
.",
"Instrucciones
",
"Crea una función timesFive
que acepte un argumento, lo multiplique por 5
y retorne el nuevo valor."
@@ -3430,31 +3554,35 @@
"description": [
"A function can include the return
statement but it does not have to. In the case that the function doesn't have a return
statement, when you call it, the function processes the inner code but the returned value is undefined
.",
"Example",
- "var sum = 0;
function addSum(num) {
sum = sum + num;
}
var returnedValue = addSum(3); // sum will be modified but returned value is undefined
",
+ "var sum = 0;
function addSum(num) {
sum = sum + num;
}
var returnedValue = addSum(3); // sum will be modified but returned value is undefined
",
"addSum
is a function without a return
statement. The function will change the global sum
variable but the returned value of the function is undefined
",
"
",
"Create a function addFive
without any arguments. This function adds 5 to the sum
variable, but its returned value is undefined
."
],
"releasedOn": "August 11, 2017",
- "solutions": [
- "function addFive() {\n sum = sum + 5;\n}"
- ],
+ "solutions": ["function addFive() {\n sum = sum + 5;\n}"],
"tests": [
{
"text": "addFive
should be a function",
- "testString": "assert(typeof addFive === 'function', 'addFive
should be a function');"
+ "testString":
+ "assert(typeof addFive === 'function', 'addFive
should be a function');"
},
{
"text": "sum
should be equal to 8",
- "testString": "assert(sum === 8, 'sum
should be equal to 8');"
+ "testString":
+ "assert(sum === 8, 'sum
should be equal to 8');"
},
{
- "text": "Returned value from addFive
should be undefined
",
- "testString": "assert(addFive() === undefined, 'Returned value from addFive
should be undefined
');"
+ "text":
+ "Returned value from addFive
should be undefined
",
+ "testString":
+ "assert(addFive() === undefined, 'Returned value from addFive
should be undefined
');"
},
{
- "text": "Inside of your functions, add 5 to the sum
variable",
- "testString": "assert(code.match(/(sum\\s*\\=\\s*sum\\s*\\+\\s*5)|(sum\\s*\\+\\=\\s*5)/g).length === 1, 'Inside of your functions, add 5 to the sum
variable');"
+ "text":
+ "Inside of your functions, add 5 to the sum
variable",
+ "testString":
+ "assert(code.match(/(sum\\s*\\=\\s*sum\\s*\\+\\s*5)|(sum\\s*\\+\\=\\s*5)/g).length === 1, 'Inside of your functions, add 5 to the sum
variable');"
}
],
"challengeType": 1,
@@ -3505,12 +3633,16 @@
],
"tests": [
{
- "text": "processed
should have a value of 2
",
- "testString": "assert(processed === 2, 'processed
should have a value of 2
');"
+ "text":
+ "processed
should have a value of 2
",
+ "testString":
+ "assert(processed === 2, 'processed
should have a value of 2
');"
},
{
- "text": "You should assign processArg
to processed
",
- "testString": "assert(/processed\\s*=\\s*processArg\\(\\s*7\\s*\\)\\s*;/.test(code), 'You should assign processArg
to processed
');"
+ "text":
+ "You should assign processArg
to processed
",
+ "testString":
+ "assert(/processed\\s*=\\s*processArg\\(\\s*7\\s*\\)\\s*;/.test(code), 'You should assign processArg
to processed
');"
}
],
"challengeType": 1,
@@ -3527,7 +3659,8 @@
]
}
},
- "guideUrl": "https://guide.freecodecamp.org/certificates/assignment-with-a-returned-value",
+ "guideUrl":
+ "https://guide.freecodecamp.org/certificates/assignment-with-a-returned-value",
"files": {
"indexjs": {
"key": "indexjs",
@@ -3555,9 +3688,7 @@
""
],
"head": [],
- "tail": [
- "(function(){return \"processed = \" + processed})();"
- ]
+ "tail": ["(function(){return \"processed = \" + processed})();"]
}
}
},
@@ -3577,23 +3708,31 @@
"tests": [
{
"text": "nextInLine([], 5)
should return a number.",
- "testString": "assert.isNumber(nextInLine([],5), 'nextInLine([], 5)
should return a number.');"
+ "testString":
+ "assert.isNumber(nextInLine([],5), 'nextInLine([], 5)
should return a number.');"
},
{
"text": "nextInLine([], 1)
should return 1
",
- "testString": "assert(nextInLine([],1) === 1, 'nextInLine([], 1)
should return 1
');"
+ "testString":
+ "assert(nextInLine([],1) === 1, 'nextInLine([], 1)
should return 1
');"
},
{
- "text": "nextInLine([2], 1)
should return 2
",
- "testString": "assert(nextInLine([2],1) === 2, 'nextInLine([2], 1)
should return 2
');"
+ "text":
+ "nextInLine([2], 1)
should return 2
",
+ "testString":
+ "assert(nextInLine([2],1) === 2, 'nextInLine([2], 1)
should return 2
');"
},
{
- "text": "nextInLine([5,6,7,8,9], 1)
should return 5
",
- "testString": "assert(nextInLine([5,6,7,8,9],1) === 5, 'nextInLine([5,6,7,8,9], 1)
should return 5
');"
+ "text":
+ "nextInLine([5,6,7,8,9], 1)
should return 5
",
+ "testString":
+ "assert(nextInLine([5,6,7,8,9],1) === 5, 'nextInLine([5,6,7,8,9], 1)
should return 5
');"
},
{
- "text": "After nextInLine(testArr, 10)
, testArr[4]
should be 10
",
- "testString": "nextInLine(testArr, 10); assert(testArr[4] === 10, 'After nextInLine(testArr, 10)
, testArr[4]
should be 10
');"
+ "text":
+ "After nextInLine(testArr, 10)
, testArr[4]
should be 10
",
+ "testString":
+ "nextInLine(testArr, 10); assert(testArr[4] === 10, 'After nextInLine(testArr, 10)
, testArr[4]
should be 10
');"
}
],
"challengeType": 1,
@@ -3670,12 +3809,15 @@
],
"tests": [
{
- "text": "The welcomeToBooleans()
function should return a boolean (true/false) value.",
- "testString": "assert(typeof welcomeToBooleans() === 'boolean', 'The welcomeToBooleans()
function should return a boolean (true/false) value.');"
+ "text":
+ "The welcomeToBooleans()
function should return a boolean (true/false) value.",
+ "testString":
+ "assert(typeof welcomeToBooleans() === 'boolean', 'The welcomeToBooleans()
function should return a boolean (true/false) value.');"
},
{
"text": "welcomeToBooleans()
should return true.",
- "testString": "assert(welcomeToBooleans() === true, 'welcomeToBooleans()
should return true.');"
+ "testString":
+ "assert(welcomeToBooleans() === true, 'welcomeToBooleans()
should return true.');"
}
],
"challengeType": 1,
@@ -3706,9 +3848,7 @@
"}"
],
"head": [],
- "tail": [
- "welcomeToBooleans();"
- ]
+ "tail": ["welcomeToBooleans();"]
}
}
},
@@ -3719,9 +3859,9 @@
"If
statements are used to make decisions in code. The keyword if
tells JavaScript to execute the code in the curly braces under certain conditions, defined in the parentheses. These conditions are known as Boolean
conditions and they may only be true
or false
.",
"When the condition evaluates to true
, the program executes the statement inside the curly braces. When the Boolean condition evaluates to false
, the statement inside the curly braces will not execute.",
"Pseudocode",
- "if (condition is true) {
statement is executed
}
",
+ "if (condition is true) {
statement is executed
}
",
"Example",
- "function test (myCondition) {
if (myCondition) {
return \"It was true\";
}
return \"It was false\";
}
test(true); // returns \"It was true\"
test(false); // returns \"It was false\"
",
+ "function test (myCondition) {
if (myCondition) {
return \"It was true\";
}
return \"It was false\";
}
test(true); // returns \"It was true\"
test(false); // returns \"It was false\"
",
"When test
is called with a value of true
, the if
statement evaluates myCondition
to see if it is true
or not. Since it is true
, the function returns \"It was true\"
. When we call test
with a value of false
, myCondition
is not true
and the statement in the curly braces is not executed and the function returns \"It was false\"
.",
"
",
"Create an if
statement inside the function to return \"Yes, that was true\"
if the parameter wasThatTrue
is true
and return \"No, that was false\"
otherwise."
@@ -3732,23 +3872,30 @@
"tests": [
{
"text": "trueOrFalse
should be a function",
- "testString": "assert(typeof trueOrFalse === \"function\", 'trueOrFalse
should be a function');"
+ "testString":
+ "assert(typeof trueOrFalse === \"function\", 'trueOrFalse
should be a function');"
},
{
"text": "trueOrFalse(true)
should return a string",
- "testString": "assert(typeof trueOrFalse(true) === \"string\", 'trueOrFalse(true)
should return a string');"
+ "testString":
+ "assert(typeof trueOrFalse(true) === \"string\", 'trueOrFalse(true)
should return a string');"
},
{
"text": "trueOrFalse(false)
should return a string",
- "testString": "assert(typeof trueOrFalse(false) === \"string\", 'trueOrFalse(false)
should return a string');"
+ "testString":
+ "assert(typeof trueOrFalse(false) === \"string\", 'trueOrFalse(false)
should return a string');"
},
{
- "text": "trueOrFalse(true)
should return \"Yes, that was true\"",
- "testString": "assert(trueOrFalse(true) === \"Yes, that was true\", 'trueOrFalse(true)
should return \"Yes, that was true\"');"
+ "text":
+ "trueOrFalse(true)
should return \"Yes, that was true\"",
+ "testString":
+ "assert(trueOrFalse(true) === \"Yes, that was true\", 'trueOrFalse(true)
should return \"Yes, that was true\"');"
},
{
- "text": "trueOrFalse(false)
should return \"No, that was false\"",
- "testString": "assert(trueOrFalse(false) === \"No, that was false\", 'trueOrFalse(false)
should return \"No, that was false\"');"
+ "text":
+ "trueOrFalse(false)
should return \"No, that was false\"",
+ "testString":
+ "assert(trueOrFalse(false) === \"No, that was false\", 'trueOrFalse(false)
should return \"No, that was false\"');"
}
],
"challengeType": 1,
@@ -3809,10 +3956,10 @@
"description": [
"There are many Comparison Operators in JavaScript. All of these operators return a boolean true
or false
value.",
"The most basic operator is the equality operator ==
. The equality operator compares two values and returns true
if they're equivalent or false
if they are not. Note that equality is different from assignment (=
), which assigns the value at the right of the operator to a variable in the left.",
- "function equalityTest(myVal) {
if (myVal == 10) {
return \"Equal\";
}
return \"Not Equal\";
}
",
+ "function equalityTest(myVal) {
if (myVal == 10) {
return \"Equal\";
}
return \"Not Equal\";
}
",
"If myVal
is equal to 10
, the equality operator returns true
, so the code in the curly braces will execute, and the function will return \"Equal\"
. Otherwise, the function will return \"Not Equal\"
.",
"In order for JavaScript to compare two different data types
(for example, numbers
and strings
), it must convert one type to another. This is known as \"Type Coercion\". Once it does, however, it can compare terms as follows:",
- " 1 == 1 // true
1 == 2 // false
1 == '1' // true
\"3\" == 3 // true
",
+ "1 == 1 // true
1 == 2 // false
1 == '1' // true
\"3\" == 3 // true
",
"
",
"Add the equality operator
to the indicated line so that the function will return \"Equal\" when val
is equivalent to 12
"
],
@@ -3823,19 +3970,23 @@
"tests": [
{
"text": "testEqual(10)
should return \"Not Equal\"",
- "testString": "assert(testEqual(10) === \"Not Equal\", 'testEqual(10)
should return \"Not Equal\"');"
+ "testString":
+ "assert(testEqual(10) === \"Not Equal\", 'testEqual(10)
should return \"Not Equal\"');"
},
{
"text": "testEqual(12)
should return \"Equal\"",
- "testString": "assert(testEqual(12) === \"Equal\", 'testEqual(12)
should return \"Equal\"');"
+ "testString":
+ "assert(testEqual(12) === \"Equal\", 'testEqual(12)
should return \"Equal\"');"
},
{
"text": "testEqual(\"12\")
should return \"Equal\"",
- "testString": "assert(testEqual(\"12\") === \"Equal\", 'testEqual(\"12\")
should return \"Equal\"');"
+ "testString":
+ "assert(testEqual(\"12\") === \"Equal\", 'testEqual(\"12\")
should return \"Equal\"');"
},
{
"text": "You should use the ==
operator",
- "testString": "assert(code.match(/==/g) && !code.match(/===/g), 'You should use the ==
operator');"
+ "testString":
+ "assert(code.match(/==/g) && !code.match(/===/g), 'You should use the ==
operator');"
}
],
"challengeType": 1,
@@ -3845,10 +3996,10 @@
"description": [
"Hay muchos Operadores de Comparación en JavaScript. Todos estos operadores retornan un valor booleano true
(verdadero) o false
(falso).",
"El operador más básico es el operador de igualdad ==
. El operador de igualdad compara dos valores y retorna true
si son equivalentes o false
si no lo son. Nota que la igualdad es diferente de la asignación (=
), la cual asigna el valor a la derecha del operador a la variable en la izquierda.",
- "function pruebaIgualdad(miVal) {
if (miVal == 10) {
return \"Igual\";
}
return \"No Es Igual\";
}
",
+ "function pruebaIgualdad(miVal) {
if (miVal == 10) {
return \"Igual\";
}
return \"No Es Igual\";
}
",
"Si miVal
es igual a 10
, el operador de igualdad retornará true
(verdadero), así el código entre llaves será ejecutado y la función retornará \"Equal\"
. De otra manera, la función retornará \"Not Equal\"
.",
"Para que JavaScript pueda comparar dos tipos de datos
diferentes (por ejemplo, números
y cadenas de texto
), debe convertir un tipo a otro. Una vez que lo hace, sin embargo, puede comparar términos de la siguiente manera:",
- " 1 == 1 // true
1 == 2 // false
1 == '1' // true
\"3\" == 3 // true
",
+ "1 == 1 // true
1 == 2 // false
1 == '1' // true
\"3\" == 3 // true
",
"Instrucciones
",
"Agrega el operador de igualdad
a la línea indicada de manera que la función retornará \"Equal\" cuando val
sea equivalente a 12
"
]
@@ -3895,19 +4046,23 @@
"tests": [
{
"text": "testStrict(10)
should return \"Not Equal\"",
- "testString": "assert(testStrict(10) === \"Not Equal\", 'testStrict(10)
should return \"Not Equal\"');"
+ "testString":
+ "assert(testStrict(10) === \"Not Equal\", 'testStrict(10)
should return \"Not Equal\"');"
},
{
"text": "testStrict(7)
should return \"Equal\"",
- "testString": "assert(testStrict(7) === \"Equal\", 'testStrict(7)
should return \"Equal\"');"
+ "testString":
+ "assert(testStrict(7) === \"Equal\", 'testStrict(7)
should return \"Equal\"');"
},
{
"text": "testStrict(\"7\")
should return \"Not Equal\"",
- "testString": "assert(testStrict(\"7\") === \"Not Equal\", 'testStrict(\"7\")
should return \"Not Equal\"');"
+ "testString":
+ "assert(testStrict(\"7\") === \"Not Equal\", 'testStrict(\"7\")
should return \"Not Equal\"');"
},
{
"text": "You should use the ===
operator",
- "testString": "assert(code.match(/(val\\s*===\\s*\\d+)|(\\d+\\s*===\\s*val)/g).length > 0, 'You should use the ===
operator');"
+ "testString":
+ "assert(code.match(/(val\\s*===\\s*\\d+)|(\\d+\\s*===\\s*val)/g).length > 0, 'You should use the ===
operator');"
}
],
"challengeType": 1,
@@ -3965,16 +4120,21 @@
],
"tests": [
{
- "text": "compareEquality(10, \"10\")
should return \"Not Equal\"",
- "testString": "assert(compareEquality(10, \"10\") === \"Not Equal\", 'compareEquality(10, \"10\")
should return \"Not Equal\"');"
+ "text":
+ "compareEquality(10, \"10\")
should return \"Not Equal\"",
+ "testString":
+ "assert(compareEquality(10, \"10\") === \"Not Equal\", 'compareEquality(10, \"10\")
should return \"Not Equal\"');"
},
{
- "text": "compareEquality(\"20\", 20)
should return \"Not Equal\"",
- "testString": "assert(compareEquality(\"20\", 20) === \"Not Equal\", 'compareEquality(\"20\", 20)
should return \"Not Equal\"');"
+ "text":
+ "compareEquality(\"20\", 20)
should return \"Not Equal\"",
+ "testString":
+ "assert(compareEquality(\"20\", 20) === \"Not Equal\", 'compareEquality(\"20\", 20)
should return \"Not Equal\"');"
},
{
"text": "You should use the ===
operator",
- "testString": "assert(code.match(/===/g), 'You should use the ===
operator');"
+ "testString":
+ "assert(code.match(/===/g), 'You should use the ===
operator');"
}
],
"challengeType": 1,
@@ -4018,27 +4178,35 @@
"tests": [
{
"text": "testNotEqual(99)
should return \"Equal\"",
- "testString": "assert(testNotEqual(99) === \"Equal\", 'testNotEqual(99)
should return \"Equal\"');"
+ "testString":
+ "assert(testNotEqual(99) === \"Equal\", 'testNotEqual(99)
should return \"Equal\"');"
},
{
"text": "testNotEqual(\"99\")
should return \"Equal\"",
- "testString": "assert(testNotEqual(\"99\") === \"Equal\", 'testNotEqual(\"99\")
should return \"Equal\"');"
+ "testString":
+ "assert(testNotEqual(\"99\") === \"Equal\", 'testNotEqual(\"99\")
should return \"Equal\"');"
},
{
"text": "testNotEqual(12)
should return \"Not Equal\"",
- "testString": "assert(testNotEqual(12) === \"Not Equal\", 'testNotEqual(12)
should return \"Not Equal\"');"
+ "testString":
+ "assert(testNotEqual(12) === \"Not Equal\", 'testNotEqual(12)
should return \"Not Equal\"');"
},
{
- "text": "testNotEqual(\"12\")
should return \"Not Equal\"",
- "testString": "assert(testNotEqual(\"12\") === \"Not Equal\", 'testNotEqual(\"12\")
should return \"Not Equal\"');"
+ "text":
+ "testNotEqual(\"12\")
should return \"Not Equal\"",
+ "testString":
+ "assert(testNotEqual(\"12\") === \"Not Equal\", 'testNotEqual(\"12\")
should return \"Not Equal\"');"
},
{
- "text": "testNotEqual(\"bob\")
should return \"Not Equal\"",
- "testString": "assert(testNotEqual(\"bob\") === \"Not Equal\", 'testNotEqual(\"bob\")
should return \"Not Equal\"');"
+ "text":
+ "testNotEqual(\"bob\")
should return \"Not Equal\"",
+ "testString":
+ "assert(testNotEqual(\"bob\") === \"Not Equal\", 'testNotEqual(\"bob\")
should return \"Not Equal\"');"
},
{
"text": "You should use the !=
operator",
- "testString": "assert(code.match(/(?!!==)!=/), 'You should use the !=
operator');"
+ "testString":
+ "assert(code.match(/(?!!==)!=/), 'You should use the !=
operator');"
}
],
"challengeType": 1,
@@ -4090,29 +4258,35 @@
"solutions": [
"function testStrictNotEqual(val) {\n if (val !== 17) {\n return \"Not Equal\";\n }\n return \"Equal\";\n}"
],
- "MDNlinks": [
- "Strict Inequality Operator"
- ],
+ "MDNlinks": ["Strict Inequality Operator"],
"tests": [
{
"text": "testStrictNotEqual(17)
should return \"Equal\"",
- "testString": "assert(testStrictNotEqual(17) === \"Equal\", 'testStrictNotEqual(17)
should return \"Equal\"');"
+ "testString":
+ "assert(testStrictNotEqual(17) === \"Equal\", 'testStrictNotEqual(17)
should return \"Equal\"');"
},
{
- "text": "testStrictNotEqual(\"17\")
should return \"Not Equal\"",
- "testString": "assert(testStrictNotEqual(\"17\") === \"Not Equal\", 'testStrictNotEqual(\"17\")
should return \"Not Equal\"');"
+ "text":
+ "testStrictNotEqual(\"17\")
should return \"Not Equal\"",
+ "testString":
+ "assert(testStrictNotEqual(\"17\") === \"Not Equal\", 'testStrictNotEqual(\"17\")
should return \"Not Equal\"');"
},
{
- "text": "testStrictNotEqual(12)
should return \"Not Equal\"",
- "testString": "assert(testStrictNotEqual(12) === \"Not Equal\", 'testStrictNotEqual(12)
should return \"Not Equal\"');"
+ "text":
+ "testStrictNotEqual(12)
should return \"Not Equal\"",
+ "testString":
+ "assert(testStrictNotEqual(12) === \"Not Equal\", 'testStrictNotEqual(12)
should return \"Not Equal\"');"
},
{
- "text": "testStrictNotEqual(\"bob\")
should return \"Not Equal\"",
- "testString": "assert(testStrictNotEqual(\"bob\") === \"Not Equal\", 'testStrictNotEqual(\"bob\")
should return \"Not Equal\"');"
+ "text":
+ "testStrictNotEqual(\"bob\")
should return \"Not Equal\"",
+ "testString":
+ "assert(testStrictNotEqual(\"bob\") === \"Not Equal\", 'testStrictNotEqual(\"bob\")
should return \"Not Equal\"');"
},
{
"text": "You should use the !==
operator",
- "testString": "assert(code.match(/(val\\s*!==\\s*\\d+)|(\\d+\\s*!==\\s*val)/g).length > 0, 'You should use the !==
operator');"
+ "testString":
+ "assert(code.match(/(val\\s*!==\\s*\\d+)|(\\d+\\s*!==\\s*val)/g).length > 0, 'You should use the !==
operator');"
}
],
"challengeType": 1,
@@ -4172,36 +4346,49 @@
],
"tests": [
{
- "text": "testGreaterThan(0)
should return \"10 or Under\"",
- "testString": "assert(testGreaterThan(0) === \"10 or Under\", 'testGreaterThan(0)
should return \"10 or Under\"');"
+ "text":
+ "testGreaterThan(0)
should return \"10 or Under\"",
+ "testString":
+ "assert(testGreaterThan(0) === \"10 or Under\", 'testGreaterThan(0)
should return \"10 or Under\"');"
},
{
- "text": "testGreaterThan(10)
should return \"10 or Under\"",
- "testString": "assert(testGreaterThan(10) === \"10 or Under\", 'testGreaterThan(10)
should return \"10 or Under\"');"
+ "text":
+ "testGreaterThan(10)
should return \"10 or Under\"",
+ "testString":
+ "assert(testGreaterThan(10) === \"10 or Under\", 'testGreaterThan(10)
should return \"10 or Under\"');"
},
{
"text": "testGreaterThan(11)
should return \"Over 10\"",
- "testString": "assert(testGreaterThan(11) === \"Over 10\", 'testGreaterThan(11)
should return \"Over 10\"');"
+ "testString":
+ "assert(testGreaterThan(11) === \"Over 10\", 'testGreaterThan(11)
should return \"Over 10\"');"
},
{
"text": "testGreaterThan(99)
should return \"Over 10\"",
- "testString": "assert(testGreaterThan(99) === \"Over 10\", 'testGreaterThan(99)
should return \"Over 10\"');"
+ "testString":
+ "assert(testGreaterThan(99) === \"Over 10\", 'testGreaterThan(99)
should return \"Over 10\"');"
},
{
"text": "testGreaterThan(100)
should return \"Over 10\"",
- "testString": "assert(testGreaterThan(100) === \"Over 10\", 'testGreaterThan(100)
should return \"Over 10\"');"
+ "testString":
+ "assert(testGreaterThan(100) === \"Over 10\", 'testGreaterThan(100)
should return \"Over 10\"');"
},
{
- "text": "testGreaterThan(101)
should return \"Over 100\"",
- "testString": "assert(testGreaterThan(101) === \"Over 100\", 'testGreaterThan(101)
should return \"Over 100\"');"
+ "text":
+ "testGreaterThan(101)
should return \"Over 100\"",
+ "testString":
+ "assert(testGreaterThan(101) === \"Over 100\", 'testGreaterThan(101)
should return \"Over 100\"');"
},
{
- "text": "testGreaterThan(150)
should return \"Over 100\"",
- "testString": "assert(testGreaterThan(150) === \"Over 100\", 'testGreaterThan(150)
should return \"Over 100\"');"
+ "text":
+ "testGreaterThan(150)
should return \"Over 100\"",
+ "testString":
+ "assert(testGreaterThan(150) === \"Over 100\", 'testGreaterThan(150)
should return \"Over 100\"');"
},
{
- "text": "You should use the >
operator at least twice",
- "testString": "assert(code.match(/val\\s*>\\s*('|\")*\\d+('|\")*/g).length > 1, 'You should use the >
operator at least twice');"
+ "text":
+ "You should use the >
operator at least twice",
+ "testString":
+ "assert(code.match(/val\\s*>\\s*('|\")*\\d+('|\")*/g).length > 1, 'You should use the >
operator at least twice');"
}
],
"challengeType": 1,
@@ -4261,36 +4448,52 @@
],
"tests": [
{
- "text": "testGreaterOrEqual(0)
should return \"Less than 10\"",
- "testString": "assert(testGreaterOrEqual(0) === \"Less than 10\", 'testGreaterOrEqual(0)
should return \"Less than 10\"');"
+ "text":
+ "testGreaterOrEqual(0)
should return \"Less than 10\"",
+ "testString":
+ "assert(testGreaterOrEqual(0) === \"Less than 10\", 'testGreaterOrEqual(0)
should return \"Less than 10\"');"
},
{
- "text": "testGreaterOrEqual(9)
should return \"Less than 10\"",
- "testString": "assert(testGreaterOrEqual(9) === \"Less than 10\", 'testGreaterOrEqual(9)
should return \"Less than 10\"');"
+ "text":
+ "testGreaterOrEqual(9)
should return \"Less than 10\"",
+ "testString":
+ "assert(testGreaterOrEqual(9) === \"Less than 10\", 'testGreaterOrEqual(9)
should return \"Less than 10\"');"
},
{
- "text": "testGreaterOrEqual(10)
should return \"10 or Over\"",
- "testString": "assert(testGreaterOrEqual(10) === \"10 or Over\", 'testGreaterOrEqual(10)
should return \"10 or Over\"');"
+ "text":
+ "testGreaterOrEqual(10)
should return \"10 or Over\"",
+ "testString":
+ "assert(testGreaterOrEqual(10) === \"10 or Over\", 'testGreaterOrEqual(10)
should return \"10 or Over\"');"
},
{
- "text": "testGreaterOrEqual(11)
should return \"10 or Over\"",
- "testString": "assert(testGreaterOrEqual(11) === \"10 or Over\", 'testGreaterOrEqual(11)
should return \"10 or Over\"');"
+ "text":
+ "testGreaterOrEqual(11)
should return \"10 or Over\"",
+ "testString":
+ "assert(testGreaterOrEqual(11) === \"10 or Over\", 'testGreaterOrEqual(11)
should return \"10 or Over\"');"
},
{
- "text": "testGreaterOrEqual(19)
should return \"10 or Over\"",
- "testString": "assert(testGreaterOrEqual(19) === \"10 or Over\", 'testGreaterOrEqual(19)
should return \"10 or Over\"');"
+ "text":
+ "testGreaterOrEqual(19)
should return \"10 or Over\"",
+ "testString":
+ "assert(testGreaterOrEqual(19) === \"10 or Over\", 'testGreaterOrEqual(19)
should return \"10 or Over\"');"
},
{
- "text": "testGreaterOrEqual(100)
should return \"20 or Over\"",
- "testString": "assert(testGreaterOrEqual(100) === \"20 or Over\", 'testGreaterOrEqual(100)
should return \"20 or Over\"');"
+ "text":
+ "testGreaterOrEqual(100)
should return \"20 or Over\"",
+ "testString":
+ "assert(testGreaterOrEqual(100) === \"20 or Over\", 'testGreaterOrEqual(100)
should return \"20 or Over\"');"
},
{
- "text": "testGreaterOrEqual(21)
should return \"20 or Over\"",
- "testString": "assert(testGreaterOrEqual(21) === \"20 or Over\", 'testGreaterOrEqual(21)
should return \"20 or Over\"');"
+ "text":
+ "testGreaterOrEqual(21)
should return \"20 or Over\"",
+ "testString":
+ "assert(testGreaterOrEqual(21) === \"20 or Over\", 'testGreaterOrEqual(21)
should return \"20 or Over\"');"
},
{
- "text": "You should use the >=
operator at least twice",
- "testString": "assert(code.match(/val\\s*>=\\s*('|\")*\\d+('|\")*/g).length > 1, 'You should use the >=
operator at least twice');"
+ "text":
+ "You should use the >=
operator at least twice",
+ "testString":
+ "assert(code.match(/val\\s*>=\\s*('|\")*\\d+('|\")*/g).length > 1, 'You should use the >=
operator at least twice');"
}
],
"challengeType": 1,
@@ -4339,7 +4542,7 @@
"description": [
"The less than operator (<
) compares the values of two numbers. If the number to the left is less than the number to the right, it returns true
. Otherwise, it returns false
. Like the equality operator, less than operator converts data types while comparing.",
"Examples",
- " 2 < 5 // true
'3' < 7 // true
5 < 5 // false
3 < 2 // false
'8' < 4 // false
",
+ "2 < 5 // true
'3' < 7 // true
5 < 5 // false
3 < 2 // false
'8' < 4 // false
",
"
",
"Add the less than
operator to the indicated lines so that the return statements make sense."
],
@@ -4350,31 +4553,39 @@
"tests": [
{
"text": "testLessThan(0)
should return \"Under 25\"",
- "testString": "assert(testLessThan(0) === \"Under 25\", 'testLessThan(0)
should return \"Under 25\"');"
+ "testString":
+ "assert(testLessThan(0) === \"Under 25\", 'testLessThan(0)
should return \"Under 25\"');"
},
{
"text": "testLessThan(24)
should return \"Under 25\"",
- "testString": "assert(testLessThan(24) === \"Under 25\", 'testLessThan(24)
should return \"Under 25\"');"
+ "testString":
+ "assert(testLessThan(24) === \"Under 25\", 'testLessThan(24)
should return \"Under 25\"');"
},
{
"text": "testLessThan(25)
should return \"Under 55\"",
- "testString": "assert(testLessThan(25) === \"Under 55\", 'testLessThan(25)
should return \"Under 55\"');"
+ "testString":
+ "assert(testLessThan(25) === \"Under 55\", 'testLessThan(25)
should return \"Under 55\"');"
},
{
"text": "testLessThan(54)
should return \"Under 55\"",
- "testString": "assert(testLessThan(54) === \"Under 55\", 'testLessThan(54)
should return \"Under 55\"');"
+ "testString":
+ "assert(testLessThan(54) === \"Under 55\", 'testLessThan(54)
should return \"Under 55\"');"
},
{
"text": "testLessThan(55)
should return \"55 or Over\"",
- "testString": "assert(testLessThan(55) === \"55 or Over\", 'testLessThan(55)
should return \"55 or Over\"');"
+ "testString":
+ "assert(testLessThan(55) === \"55 or Over\", 'testLessThan(55)
should return \"55 or Over\"');"
},
{
"text": "testLessThan(99)
should return \"55 or Over\"",
- "testString": "assert(testLessThan(99) === \"55 or Over\", 'testLessThan(99)
should return \"55 or Over\"');"
+ "testString":
+ "assert(testLessThan(99) === \"55 or Over\", 'testLessThan(99)
should return \"55 or Over\"');"
},
{
- "text": "You should use the <
operator at least twice",
- "testString": "assert(code.match(/val\\s*<\\s*('|\")*\\d+('|\")*/g).length > 1, 'You should use the <
operator at least twice');"
+ "text":
+ "You should use the <
operator at least twice",
+ "testString":
+ "assert(code.match(/val\\s*<\\s*('|\")*\\d+('|\")*/g).length > 1, 'You should use the <
operator at least twice');"
}
],
"challengeType": 1,
@@ -4384,7 +4595,7 @@
"description": [
"El operador menor que (<
) compara los valores de dos números. Si el número a la izquierda es menor que el número de la derecha, este retorna true
(verdadero). De otra manera, este retorna false
(falso). Como el operador de igualdad, el operador menor que convierte tipos de datos mientra compara.",
"Ejemplos",
- " 2 < 5 // true
'3' < 7 // true
5 < 5 // false
3 < 2 // false
'8' < 4 // false
",
+ "2 < 5 // true
'3' < 7 // true
5 < 5 // false
3 < 2 // false
'8' < 4 // false
",
"Instrucciones
",
"Agregar el operador menor que
a las líneas indicadas de modo que las sentencias de retorno tengan sentido."
]
@@ -4422,7 +4633,7 @@
"description": [
"The less than or equal to
operator (<=
) compares the values of two numbers. If the number to the left is less than or equal to the number to the right, it returns true
. If the number on the left is greater than the number on the right, it returns false
. Like the equality operator, less than or equal to
converts data types.",
"Examples",
- " 4 <= 5 // true
'7' <= 7 // true
5 <= 5 // true
3 <= 2 // false
'8' <= 4 // false
",
+ "4 <= 5 // true
'7' <= 7 // true
5 <= 5 // true
3 <= 2 // false
'8' <= 4 // false
",
"
",
"Add the less than or equal to
operator to the indicated lines so that the return statements make sense."
],
@@ -4432,36 +4643,52 @@
],
"tests": [
{
- "text": "testLessOrEqual(0)
should return \"Smaller Than or Equal to 12\"",
- "testString": "assert(testLessOrEqual(0) === \"Smaller Than or Equal to 12\", 'testLessOrEqual(0)
should return \"Smaller Than or Equal to 12\"');"
+ "text":
+ "testLessOrEqual(0)
should return \"Smaller Than or Equal to 12\"",
+ "testString":
+ "assert(testLessOrEqual(0) === \"Smaller Than or Equal to 12\", 'testLessOrEqual(0)
should return \"Smaller Than or Equal to 12\"');"
},
{
- "text": "testLessOrEqual(11)
should return \"Smaller Than or Equal to 12\"",
- "testString": "assert(testLessOrEqual(11) === \"Smaller Than or Equal to 12\", 'testLessOrEqual(11)
should return \"Smaller Than or Equal to 12\"');"
+ "text":
+ "testLessOrEqual(11)
should return \"Smaller Than or Equal to 12\"",
+ "testString":
+ "assert(testLessOrEqual(11) === \"Smaller Than or Equal to 12\", 'testLessOrEqual(11)
should return \"Smaller Than or Equal to 12\"');"
},
{
- "text": "testLessOrEqual(12)
should return \"Smaller Than or Equal to 12\"",
- "testString": "assert(testLessOrEqual(12) === \"Smaller Than or Equal to 12\", 'testLessOrEqual(12)
should return \"Smaller Than or Equal to 12\"');"
+ "text":
+ "testLessOrEqual(12)
should return \"Smaller Than or Equal to 12\"",
+ "testString":
+ "assert(testLessOrEqual(12) === \"Smaller Than or Equal to 12\", 'testLessOrEqual(12)
should return \"Smaller Than or Equal to 12\"');"
},
{
- "text": "testLessOrEqual(23)
should return \"Smaller Than or Equal to 24\"",
- "testString": "assert(testLessOrEqual(23) === \"Smaller Than or Equal to 24\", 'testLessOrEqual(23)
should return \"Smaller Than or Equal to 24\"');"
+ "text":
+ "testLessOrEqual(23)
should return \"Smaller Than or Equal to 24\"",
+ "testString":
+ "assert(testLessOrEqual(23) === \"Smaller Than or Equal to 24\", 'testLessOrEqual(23)
should return \"Smaller Than or Equal to 24\"');"
},
{
- "text": "testLessOrEqual(24)
should return \"Smaller Than or Equal to 24\"",
- "testString": "assert(testLessOrEqual(24) === \"Smaller Than or Equal to 24\", 'testLessOrEqual(24)
should return \"Smaller Than or Equal to 24\"');"
+ "text":
+ "testLessOrEqual(24)
should return \"Smaller Than or Equal to 24\"",
+ "testString":
+ "assert(testLessOrEqual(24) === \"Smaller Than or Equal to 24\", 'testLessOrEqual(24)
should return \"Smaller Than or Equal to 24\"');"
},
{
- "text": "testLessOrEqual(25)
should return \"More Than 24\"",
- "testString": "assert(testLessOrEqual(25) === \"More Than 24\", 'testLessOrEqual(25)
should return \"More Than 24\"');"
+ "text":
+ "testLessOrEqual(25)
should return \"More Than 24\"",
+ "testString":
+ "assert(testLessOrEqual(25) === \"More Than 24\", 'testLessOrEqual(25)
should return \"More Than 24\"');"
},
{
- "text": "testLessOrEqual(55)
should return \"More Than 24\"",
- "testString": "assert(testLessOrEqual(55) === \"More Than 24\", 'testLessOrEqual(55)
should return \"More Than 24\"');"
+ "text":
+ "testLessOrEqual(55)
should return \"More Than 24\"",
+ "testString":
+ "assert(testLessOrEqual(55) === \"More Than 24\", 'testLessOrEqual(55)
should return \"More Than 24\"');"
},
{
- "text": "You should use the <=
operator at least twice",
- "testString": "assert(code.match(/val\\s*<=\\s*('|\")*\\d+('|\")*/g).length > 1, 'You should use the <=
operator at least twice');"
+ "text":
+ "You should use the <=
operator at least twice",
+ "testString":
+ "assert(code.match(/val\\s*<=\\s*('|\")*\\d+('|\")*/g).length > 1, 'You should use the <=
operator at least twice');"
}
],
"challengeType": 1,
@@ -4471,7 +4698,7 @@
"description": [
"El operador menor o igual
(<=
) compara los valores de dos números. Si el número a la izquierda es menor o igual que el número de la derecha, este retorna true
(verdadero). Si el número a la izquierda es mayor que el número de la derecha, este retorna false
(falso). Al igual que el operador de igualdad, menor o igual
convierte tipos de datos.",
"Ejemplos",
- " 4 <= 5 // true
'7' <= 7 // true
5 <= 5 // true
3 <= 2 // false
'8' <= 4 // false
",
+ " 4 <= 5 // true
'7' <= 7 // true
5 <= 5 // true
3 <= 2 // false
'8' <= 4 // false
",
"Instrucciones
",
"Agrega el operador menor o igual
a las líneas indicadas de modo que las sentencias de retorno tengan sentido."
]
@@ -4510,9 +4737,9 @@
"description": [
"Sometimes you will need to test more than one thing at a time. The logical and operator (&&
) returns true
if and only if the operands to the left and right of it are true.",
"The same effect could be achieved by nesting an if statement inside another if:",
- "if (num > 5) {
if (num < 10) {
return \"Yes\";
}
}
return \"No\";
",
+ "if (num > 5) {
if (num < 10) {
return \"Yes\";
}
}
return \"No\";
",
"will only return \"Yes\" if num
is greater than 5
and less than 10
. The same logic can be written as:",
- "if (num > 5 && num < 10) {
return \"Yes\";
}
return \"No\";
",
+ "if (num > 5 && num < 10) {
return \"Yes\";
}
return \"No\";
",
"
",
"Combine the two if statements into one statement which will return \"Yes\"
if val
is less than or equal to 50
and greater than or equal to 25
. Otherwise, will return \"No\"
."
],
@@ -4523,43 +4750,53 @@
"tests": [
{
"text": "You should use the &&
operator once",
- "testString": "assert(code.match(/&&/g).length === 1, 'You should use the &&
operator once');"
+ "testString":
+ "assert(code.match(/&&/g).length === 1, 'You should use the &&
operator once');"
},
{
"text": "You should only have one if
statement",
- "testString": "assert(code.match(/if/g).length === 1, 'You should only have one if
statement');"
+ "testString":
+ "assert(code.match(/if/g).length === 1, 'You should only have one if
statement');"
},
{
"text": "testLogicalAnd(0)
should return \"No\"",
- "testString": "assert(testLogicalAnd(0) === \"No\", 'testLogicalAnd(0)
should return \"No\"');"
+ "testString":
+ "assert(testLogicalAnd(0) === \"No\", 'testLogicalAnd(0)
should return \"No\"');"
},
{
"text": "testLogicalAnd(24)
should return \"No\"",
- "testString": "assert(testLogicalAnd(24) === \"No\", 'testLogicalAnd(24)
should return \"No\"');"
+ "testString":
+ "assert(testLogicalAnd(24) === \"No\", 'testLogicalAnd(24)
should return \"No\"');"
},
{
"text": "testLogicalAnd(25)
should return \"Yes\"",
- "testString": "assert(testLogicalAnd(25) === \"Yes\", 'testLogicalAnd(25)
should return \"Yes\"');"
+ "testString":
+ "assert(testLogicalAnd(25) === \"Yes\", 'testLogicalAnd(25)
should return \"Yes\"');"
},
{
"text": "testLogicalAnd(30)
should return \"Yes\"",
- "testString": "assert(testLogicalAnd(30) === \"Yes\", 'testLogicalAnd(30)
should return \"Yes\"');"
+ "testString":
+ "assert(testLogicalAnd(30) === \"Yes\", 'testLogicalAnd(30)
should return \"Yes\"');"
},
{
"text": "testLogicalAnd(50)
should return \"Yes\"",
- "testString": "assert(testLogicalAnd(50) === \"Yes\", 'testLogicalAnd(50)
should return \"Yes\"');"
+ "testString":
+ "assert(testLogicalAnd(50) === \"Yes\", 'testLogicalAnd(50)
should return \"Yes\"');"
},
{
"text": "testLogicalAnd(51)
should return \"No\"",
- "testString": "assert(testLogicalAnd(51) === \"No\", 'testLogicalAnd(51)
should return \"No\"');"
+ "testString":
+ "assert(testLogicalAnd(51) === \"No\", 'testLogicalAnd(51)
should return \"No\"');"
},
{
"text": "testLogicalAnd(75)
should return \"No\"",
- "testString": "assert(testLogicalAnd(75) === \"No\", 'testLogicalAnd(75)
should return \"No\"');"
+ "testString":
+ "assert(testLogicalAnd(75) === \"No\", 'testLogicalAnd(75)
should return \"No\"');"
},
{
"text": "testLogicalAnd(80)
should return \"No\"",
- "testString": "assert(testLogicalAnd(80) === \"No\", 'testLogicalAnd(80)
should return \"No\"');"
+ "testString":
+ "assert(testLogicalAnd(80) === \"No\", 'testLogicalAnd(80)
should return \"No\"');"
}
],
"challengeType": 1,
@@ -4569,9 +4806,9 @@
"description": [
"A veces necesitarás probar más de una cosa a la vez. El operador lógico y (&&
) retorna true
(verdadero) si y solo si los operandos a la izquierda y derecha de este son verdaderos.",
"El mismo efecto podría lograrse anidando una sentencia if dentro de otro if:",
- "if (num > 5) {
if (num < 10) {
return \"Yes\";
}
}
return \"No\";
",
+ "if (num > 5) {
if (num < 10) {
return \"Yes\";
}
}
return \"No\";
",
"solo retornará \"Yes\" si num
está entre 6
y 9
(6 y 9 incluidos). La misma lógica puede ser escrita como:",
- "if (num > 5 && num < 10) {
return \"Yes\";
}
return \"No\";
",
+ "if (num > 5 && num < 10) {
return \"Yes\";
}
return \"No\";
",
"Instrucciones
",
"Combina las dos sentencias if dentro de una sentencia la cual retornará \"Yes\"
si val
es menor o igual a 50
y mayor o igual a 25
. De otra manera, retornará \"No\"
."
]
@@ -4611,9 +4848,9 @@
"The logical or operator (||
) returns true
if either of the operands is true
. Otherwise, it returns false
.",
"The logical or operator is composed of two pipe symbols (|
). This can typically be found between your Backspace and Enter keys.",
"The pattern below should look familiar from prior waypoints:",
- "if (num > 10) {
return \"No\";
}
if (num < 5) {
return \"No\";
}
return \"Yes\";
",
+ "if (num > 10) {
return \"No\";
}
if (num < 5) {
return \"No\";
}
return \"Yes\";
",
"will return \"Yes\" only if num
is between 5
and 10
(5 and 10 included). The same logic can be written as:",
- "if (num > 10 || num < 5) {
return \"No\";
}
return \"Yes\";
",
+ "if (num > 10 || num < 5) {
return \"No\";
}
return \"Yes\";
",
"
",
"Combine the two if
statements into one statement which returns \"Outside\"
if val
is not between 10
and 20
, inclusive. Otherwise, return \"Inside\"
."
],
@@ -4624,43 +4861,53 @@
"tests": [
{
"text": "You should use the ||
operator once",
- "testString": "assert(code.match(/\\|\\|/g).length === 1, 'You should use the ||
operator once');"
+ "testString":
+ "assert(code.match(/\\|\\|/g).length === 1, 'You should use the ||
operator once');"
},
{
"text": "You should only have one if
statement",
- "testString": "assert(code.match(/if/g).length === 1, 'You should only have one if
statement');"
+ "testString":
+ "assert(code.match(/if/g).length === 1, 'You should only have one if
statement');"
},
{
"text": "testLogicalOr(0)
should return \"Outside\"",
- "testString": "assert(testLogicalOr(0) === \"Outside\", 'testLogicalOr(0)
should return \"Outside\"');"
+ "testString":
+ "assert(testLogicalOr(0) === \"Outside\", 'testLogicalOr(0)
should return \"Outside\"');"
},
{
"text": "testLogicalOr(9)
should return \"Outside\"",
- "testString": "assert(testLogicalOr(9) === \"Outside\", 'testLogicalOr(9)
should return \"Outside\"');"
+ "testString":
+ "assert(testLogicalOr(9) === \"Outside\", 'testLogicalOr(9)
should return \"Outside\"');"
},
{
"text": "testLogicalOr(10)
should return \"Inside\"",
- "testString": "assert(testLogicalOr(10) === \"Inside\", 'testLogicalOr(10)
should return \"Inside\"');"
+ "testString":
+ "assert(testLogicalOr(10) === \"Inside\", 'testLogicalOr(10)
should return \"Inside\"');"
},
{
"text": "testLogicalOr(15)
should return \"Inside\"",
- "testString": "assert(testLogicalOr(15) === \"Inside\", 'testLogicalOr(15)
should return \"Inside\"');"
+ "testString":
+ "assert(testLogicalOr(15) === \"Inside\", 'testLogicalOr(15)
should return \"Inside\"');"
},
{
"text": "testLogicalOr(19)
should return \"Inside\"",
- "testString": "assert(testLogicalOr(19) === \"Inside\", 'testLogicalOr(19)
should return \"Inside\"');"
+ "testString":
+ "assert(testLogicalOr(19) === \"Inside\", 'testLogicalOr(19)
should return \"Inside\"');"
},
{
"text": "testLogicalOr(20)
should return \"Inside\"",
- "testString": "assert(testLogicalOr(20) === \"Inside\", 'testLogicalOr(20)
should return \"Inside\"');"
+ "testString":
+ "assert(testLogicalOr(20) === \"Inside\", 'testLogicalOr(20)
should return \"Inside\"');"
},
{
"text": "testLogicalOr(21)
should return \"Outside\"",
- "testString": "assert(testLogicalOr(21) === \"Outside\", 'testLogicalOr(21)
should return \"Outside\"');"
+ "testString":
+ "assert(testLogicalOr(21) === \"Outside\", 'testLogicalOr(21)
should return \"Outside\"');"
},
{
"text": "testLogicalOr(25)
should return \"Outside\"",
- "testString": "assert(testLogicalOr(25) === \"Outside\", 'testLogicalOr(25)
should return \"Outside\"');"
+ "testString":
+ "assert(testLogicalOr(25) === \"Outside\", 'testLogicalOr(25)
should return \"Outside\"');"
}
],
"challengeType": 1,
@@ -4670,9 +4917,9 @@
"description": [
"El operador lógico o (||
) retorna true
(verdadero) si cualquiera de los operandos es true
(verdadero). De otra manera, este retorna false
(falso).",
"El patrón de abajo debería ser familiar de los puntos de referencia anteriores:",
- "if (num > 10) {
return \"No\";
}
if (num < 5) {
return \"No\";
}
return \"Yes\";
",
+ "if (num > 10) {
return \"No\";
}
if (num < 5) {
return \"No\";
}
return \"Yes\";
",
"retornará \"Yes\" solo si num
está entre 5
y 10
(5 y 10 incluidos). La misma lógica puede ser escrita como:",
- "if (num > 10 || num < 5) {
return \"No\";
}
return \"Yes\";
",
+ "if (num > 10 || num < 5) {
return \"No\";
}
return \"Yes\";
",
"Instrucciones
",
"Combina las dos sentencias if
dentro de una sentencia la cual retorne \"Outside\"
si val
no está entre 10
y 20
, inclusive. De otra manera, retorna \"Inside\"
."
]
@@ -4712,7 +4959,7 @@
"title": "Introducing Else Statements",
"description": [
"When a condition for an if
statement is true, the block of code following it is executed. What about when that condition is false? Normally nothing would happen. With an else
statement, an alternate block of code can be executed.",
- "if (num > 10) {
return \"Bigger than 10\";
} else {
return \"10 or Less\";
}
",
+ "if (num > 10) {
return \"Bigger than 10\";
} else {
return \"10 or Less\";
}
",
"
",
"Combine the if
statements into a single if/else
statement."
],
@@ -4722,32 +4969,40 @@
],
"tests": [
{
- "text": "You should only have one if
statement in the editor",
- "testString": "assert(code.match(/if/g).length === 1, 'You should only have one if
statement in the editor');"
+ "text":
+ "You should only have one if
statement in the editor",
+ "testString":
+ "assert(code.match(/if/g).length === 1, 'You should only have one if
statement in the editor');"
},
{
"text": "You should use an else
statement",
- "testString": "assert(/else/g.test(code), 'You should use an else
statement');"
+ "testString":
+ "assert(/else/g.test(code), 'You should use an else
statement');"
},
{
"text": "testElse(4)
should return \"5 or Smaller\"",
- "testString": "assert(testElse(4) === \"5 or Smaller\", 'testElse(4)
should return \"5 or Smaller\"');"
+ "testString":
+ "assert(testElse(4) === \"5 or Smaller\", 'testElse(4)
should return \"5 or Smaller\"');"
},
{
"text": "testElse(5)
should return \"5 or Smaller\"",
- "testString": "assert(testElse(5) === \"5 or Smaller\", 'testElse(5)
should return \"5 or Smaller\"');"
+ "testString":
+ "assert(testElse(5) === \"5 or Smaller\", 'testElse(5)
should return \"5 or Smaller\"');"
},
{
"text": "testElse(6)
should return \"Bigger than 5\"",
- "testString": "assert(testElse(6) === \"Bigger than 5\", 'testElse(6)
should return \"Bigger than 5\"');"
+ "testString":
+ "assert(testElse(6) === \"Bigger than 5\", 'testElse(6)
should return \"Bigger than 5\"');"
},
{
"text": "testElse(10)
should return \"Bigger than 5\"",
- "testString": "assert(testElse(10) === \"Bigger than 5\", 'testElse(10)
should return \"Bigger than 5\"');"
+ "testString":
+ "assert(testElse(10) === \"Bigger than 5\", 'testElse(10)
should return \"Bigger than 5\"');"
},
{
"text": "Do not change the code above or below the lines.",
- "testString": "assert(/var result = \"\";/.test(code) && /return result;/.test(code), 'Do not change the code above or below the lines.');"
+ "testString":
+ "assert(/var result = \"\";/.test(code) && /return result;/.test(code), 'Do not change the code above or below the lines.');"
}
],
"challengeType": 1,
@@ -4756,7 +5011,7 @@
"title": "Introducción de las sentencias else",
"description": [
"Cuando una condición de una sentencia if
es verdadera, el siguiente bloque de código es ejecutado. ¿Y cuando esa condición es falsa? Normalmente nada pasaría. Con una sentencia else
(además), un bloque alternativo de código puede ser ejecutado.",
- "if (num > 10) {
return \"Más grande que 10\";
} else {
return \"10 o Menos\";
}
",
+ "if (num > 10) {
return \"Más grande que 10\";
} else {
return \"10 o Menos\";
}
",
"Instrucciones
",
"Combina las sentencias if
dentro de una sola sentencia if/else
."
]
@@ -4798,7 +5053,7 @@
"title": "Introducing Else If Statements",
"description": [
"If you have multiple conditions that need to be addressed, you can chain if
statements together with else if
statements.",
- "if (num > 15) {
return \"Bigger than 15\";
} else if (num < 5) {
return \"Smaller than 5\";
} else {
return \"Between 5 and 15\";
}
",
+ "if (num > 15) {
return \"Bigger than 15\";
} else if (num < 5) {
return \"Smaller than 5\";
} else {
return \"Between 5 and 15\";
}
",
"
",
"Convert the logic to use else if
statements."
],
@@ -4809,31 +5064,42 @@
"tests": [
{
"text": "You should have at least two else
statements",
- "testString": "assert(code.match(/else/g).length > 1, 'You should have at least two else
statements');"
+ "testString":
+ "assert(code.match(/else/g).length > 1, 'You should have at least two else
statements');"
},
{
"text": "You should have at least two if
statements",
- "testString": "assert(code.match(/if/g).length > 1, 'You should have at least two if
statements');"
+ "testString":
+ "assert(code.match(/if/g).length > 1, 'You should have at least two if
statements');"
},
{
"text": "testElseIf(0)
should return \"Smaller than 5\"",
- "testString": "assert(testElseIf(0) === \"Smaller than 5\", 'testElseIf(0)
should return \"Smaller than 5\"');"
+ "testString":
+ "assert(testElseIf(0) === \"Smaller than 5\", 'testElseIf(0)
should return \"Smaller than 5\"');"
},
{
- "text": "testElseIf(5)
should return \"Between 5 and 10\"",
- "testString": "assert(testElseIf(5) === \"Between 5 and 10\", 'testElseIf(5)
should return \"Between 5 and 10\"');"
+ "text":
+ "testElseIf(5)
should return \"Between 5 and 10\"",
+ "testString":
+ "assert(testElseIf(5) === \"Between 5 and 10\", 'testElseIf(5)
should return \"Between 5 and 10\"');"
},
{
- "text": "testElseIf(7)
should return \"Between 5 and 10\"",
- "testString": "assert(testElseIf(7) === \"Between 5 and 10\", 'testElseIf(7)
should return \"Between 5 and 10\"');"
+ "text":
+ "testElseIf(7)
should return \"Between 5 and 10\"",
+ "testString":
+ "assert(testElseIf(7) === \"Between 5 and 10\", 'testElseIf(7)
should return \"Between 5 and 10\"');"
},
{
- "text": "testElseIf(10)
should return \"Between 5 and 10\"",
- "testString": "assert(testElseIf(10) === \"Between 5 and 10\", 'testElseIf(10)
should return \"Between 5 and 10\"');"
+ "text":
+ "testElseIf(10)
should return \"Between 5 and 10\"",
+ "testString":
+ "assert(testElseIf(10) === \"Between 5 and 10\", 'testElseIf(10)
should return \"Between 5 and 10\"');"
},
{
- "text": "testElseIf(12)
should return \"Greater than 10\"",
- "testString": "assert(testElseIf(12) === \"Greater than 10\", 'testElseIf(12)
should return \"Greater than 10\"');"
+ "text":
+ "testElseIf(12)
should return \"Greater than 10\"",
+ "testString":
+ "assert(testElseIf(12) === \"Greater than 10\", 'testElseIf(12)
should return \"Greater than 10\"');"
}
],
"challengeType": 1,
@@ -4842,7 +5108,7 @@
"title": "Introducción de las sentencias else if",
"description": [
"Si tienes múltiples condiciones que deben abordarse, puedes encadenar sentencias if
juntas con sentencias else if
.",
- "if (num > 15) {
return \"Más grande que 15\";
} else if (num < 5) {
return \"Más pequeño que 5\";
} else {
return \"Entre 5 y 15\";
}
",
+ "if (num > 15) {
return \"Más grande que 15\";
} else if (num < 5) {
return \"Más pequeño que 5\";
} else {
return \"Entre 5 y 15\";
}
",
"Instrucciones
",
"Convierte la lógica para usar sentencias else if
."
]
@@ -4883,9 +5149,9 @@
"The function is executed from top to bottom so you will want to be careful of what statement comes first.",
"Take these two functions as an example.",
"Here's the first:",
- "function foo(x) {
if (x < 1) {
return \"Less than one\";
} else if (x < 2) {
return \"Less than two\";
} else {
return \"Greater than or equal to two\";
}
}
",
+ "function foo(x) {
if (x < 1) {
return \"Less than one\";
} else if (x < 2) {
return \"Less than two\";
} else {
return \"Greater than or equal to two\";
}
}
",
"And the second just switches the order of the statements:",
- "function bar(x) {
if (x < 2) {
return \"Less than two\";
} else if (x < 1) {
return \"Less than one\";
} else {
return \"Greater than or equal to two\";
}
}
",
+ "function bar(x) {
if (x < 2) {
return \"Less than two\";
} else if (x < 1) {
return \"Less than one\";
} else {
return \"Greater than or equal to two\";
}
}
",
"While these two functions look nearly identical if we pass a number to both we get different outputs.",
"foo(0) // \"Less than one\"
bar(0) // \"Less than two\"
",
"
",
@@ -4897,15 +5163,19 @@
"tests": [
{
"text": "orderMyLogic(4)
should return \"Less than 5\"",
- "testString": "assert(orderMyLogic(4) === \"Less than 5\", 'orderMyLogic(4)
should return \"Less than 5\"');"
+ "testString":
+ "assert(orderMyLogic(4) === \"Less than 5\", 'orderMyLogic(4)
should return \"Less than 5\"');"
},
{
"text": "orderMyLogic(6)
should return \"Less than 10\"",
- "testString": "assert(orderMyLogic(6) === \"Less than 10\", 'orderMyLogic(6)
should return \"Less than 10\"');"
+ "testString":
+ "assert(orderMyLogic(6) === \"Less than 10\", 'orderMyLogic(6)
should return \"Less than 10\"');"
},
{
- "text": "orderMyLogic(11)
should return \"Greater than or equal to 10\"",
- "testString": "assert(orderMyLogic(11) === \"Greater than or equal to 10\", 'orderMyLogic(11)
should return \"Greater than or equal to 10\"');"
+ "text":
+ "orderMyLogic(11)
should return \"Greater than or equal to 10\"",
+ "testString":
+ "assert(orderMyLogic(11) === \"Greater than or equal to 10\", 'orderMyLogic(11)
should return \"Greater than or equal to 10\"');"
}
],
"challengeType": 1,
@@ -4917,9 +5187,9 @@
"El ciclo es ejecutado de arriba hacia abajo por lo que tendrás que ser cuidadoso de cual sentencia va primero.",
"Toma estas dos funciones como ejemplo.",
"Aquí está la primera:",
- "function foo(x) {
if (x < 1) {
return \"Menor que uno\";
} else if (x < 2) {
return \"Menor que dos\";
} else {
return \"Mayor o igual a dos\";
}
}
",
+ "function foo(x) {
if (x < 1) {
return \"Menor que uno\";
} else if (x < 2) {
return \"Menor que dos\";
} else {
return \"Mayor o igual a dos\";
}
}
",
"Y el segundo solo cambia el orden de las sentencias:",
- "function bar(x) {
if (x < 2) {
return \"Menor que dos\";
} else if (x < 1) {
return \"Menor que uno\";
} else {
return \"Mayor o igual a dos\";
}
}
",
+ "function bar(x) {
if (x < 2) {
return \"Menor que dos\";
} else if (x < 1) {
return \"Menor que uno\";
} else {
return \"Mayor o igual a dos\";
}
}
",
"Mientras esas dos funciones parecen casi idénticas, si nosotros pasamos un número a ambas obtendremos diferentes salidas.",
"foo(0) // \"Menor que uno\"
bar(0) // \"Menor que dos\"
",
"Instrucciones
",
@@ -4956,7 +5226,7 @@
"title": "Chaining If Else Statements",
"description": [
"if/else
statements can be chained together for complex logic. Here is pseudocode of multiple chained if
/ else if
statements:",
- "if (condition1) {
statement1
} else if (condition2) {
statement2
} else if (condition3) {
statement3
. . .
} else {
statementN
}
",
+ "if (condition1) {
statement1
} else if (condition2) {
statement2
} else if (condition3) {
statement3
. . .
} else {
statementN
}
",
"
",
"Write chained if
/else if
statements to fulfill the following conditions:",
"num < 5
- return \"Tiny\"
num < 10
- return \"Small\"
num < 15
- return \"Medium\"
num < 20
- return \"Large\"
num >= 20
- return \"Huge\""
@@ -4968,55 +5238,68 @@
"tests": [
{
"text": "You should have at least four else
statements",
- "testString": "assert(code.match(/else/g).length > 3, 'You should have at least four else
statements');"
+ "testString":
+ "assert(code.match(/else/g).length > 3, 'You should have at least four else
statements');"
},
{
"text": "You should have at least four if
statements",
- "testString": "assert(code.match(/if/g).length > 3, 'You should have at least four if
statements');"
+ "testString":
+ "assert(code.match(/if/g).length > 3, 'You should have at least four if
statements');"
},
{
"text": "You should have at least one return
statement",
- "testString": "assert(code.match(/return/g).length >= 1, 'You should have at least one return
statement');"
+ "testString":
+ "assert(code.match(/return/g).length >= 1, 'You should have at least one return
statement');"
},
{
"text": "testSize(0)
should return \"Tiny\"",
- "testString": "assert(testSize(0) === \"Tiny\", 'testSize(0)
should return \"Tiny\"');"
+ "testString":
+ "assert(testSize(0) === \"Tiny\", 'testSize(0)
should return \"Tiny\"');"
},
{
"text": "testSize(4)
should return \"Tiny\"",
- "testString": "assert(testSize(4) === \"Tiny\", 'testSize(4)
should return \"Tiny\"');"
+ "testString":
+ "assert(testSize(4) === \"Tiny\", 'testSize(4)
should return \"Tiny\"');"
},
{
"text": "testSize(5)
should return \"Small\"",
- "testString": "assert(testSize(5) === \"Small\", 'testSize(5)
should return \"Small\"');"
+ "testString":
+ "assert(testSize(5) === \"Small\", 'testSize(5)
should return \"Small\"');"
},
{
"text": "testSize(8)
should return \"Small\"",
- "testString": "assert(testSize(8) === \"Small\", 'testSize(8)
should return \"Small\"');"
+ "testString":
+ "assert(testSize(8) === \"Small\", 'testSize(8)
should return \"Small\"');"
},
{
"text": "testSize(10)
should return \"Medium\"",
- "testString": "assert(testSize(10) === \"Medium\", 'testSize(10)
should return \"Medium\"');"
+ "testString":
+ "assert(testSize(10) === \"Medium\", 'testSize(10)
should return \"Medium\"');"
},
{
"text": "testSize(14)
should return \"Medium\"",
- "testString": "assert(testSize(14) === \"Medium\", 'testSize(14)
should return \"Medium\"');"
+ "testString":
+ "assert(testSize(14) === \"Medium\", 'testSize(14)
should return \"Medium\"');"
},
{
"text": "testSize(15)
should return \"Large\"",
- "testString": "assert(testSize(15) === \"Large\", 'testSize(15)
should return \"Large\"');"
+ "testString":
+ "assert(testSize(15) === \"Large\", 'testSize(15)
should return \"Large\"');"
},
{
"text": "testSize(17)
should return \"Large\"",
- "testString": "assert(testSize(17) === \"Large\", 'testSize(17)
should return \"Large\"');"
+ "testString":
+ "assert(testSize(17) === \"Large\", 'testSize(17)
should return \"Large\"');"
},
{
"text": "testSize(20)
should return \"Huge\"",
- "testString": "assert(testSize(20) === \"Huge\", 'testSize(20)
should return \"Huge\"');"
+ "testString":
+ "assert(testSize(20) === \"Huge\", 'testSize(20)
should return \"Huge\"');"
},
{
"text": "testSize(25)
should return \"Huge\"",
- "testString": "assert(testSize(25) === \"Huge\", 'testSize(25)
should return \"Huge\"');"
+ "testString":
+ "assert(testSize(25) === \"Huge\", 'testSize(25)
should return \"Huge\"');"
}
],
"challengeType": 1,
@@ -5025,7 +5308,7 @@
"title": "Encadenamiento de sentencias else if",
"description": [
"Las sentencias if/else
(si/de lo contrario) pueden ser encadenadas juntas por una lógica compleja. Aquí está el pseudocódigo de múltiples sentencias if
/ else if
encadenadas:",
- "if (condicion1) {
sentencias1
} else if (condicion2) {
sentencias2
} else if (condicion3) {
sentencias3
. . .
} else {
sentenciasN
}
",
+ "if (condicion1) {
sentencias1
} else if (condicion2) {
sentencias2
} else if (condicion3) {
sentencias3
. . .
} else {
sentenciasN
}
",
"Instrucciones
",
"Escribe sentencias if
/else if
encadenadas para cumplir las siguientes condiciones:",
"num < 5
- retorna \"Tiny\"
num < 10
- retorna \"Small\"
num < 15
- retorna \"Medium\"
num < 20
- retorna \"Large\"
num >= 20
- retorna \"Huge\""
@@ -5070,47 +5353,58 @@
"tests": [
{
"text": "golfScore(4, 1)
should return \"Hole-in-one!\"",
- "testString": "assert(golfScore(4, 1) === \"Hole-in-one!\", 'golfScore(4, 1)
should return \"Hole-in-one!\"');"
+ "testString":
+ "assert(golfScore(4, 1) === \"Hole-in-one!\", 'golfScore(4, 1)
should return \"Hole-in-one!\"');"
},
{
"text": "golfScore(4, 2)
should return \"Eagle\"",
- "testString": "assert(golfScore(4, 2) === \"Eagle\", 'golfScore(4, 2)
should return \"Eagle\"');"
+ "testString":
+ "assert(golfScore(4, 2) === \"Eagle\", 'golfScore(4, 2)
should return \"Eagle\"');"
},
{
"text": "golfScore(5, 2)
should return \"Eagle\"",
- "testString": "assert(golfScore(5, 2) === \"Eagle\", 'golfScore(5, 2)
should return \"Eagle\"');"
+ "testString":
+ "assert(golfScore(5, 2) === \"Eagle\", 'golfScore(5, 2)
should return \"Eagle\"');"
},
{
"text": "golfScore(4, 3)
should return \"Birdie\"",
- "testString": "assert(golfScore(4, 3) === \"Birdie\", 'golfScore(4, 3)
should return \"Birdie\"');"
+ "testString":
+ "assert(golfScore(4, 3) === \"Birdie\", 'golfScore(4, 3)
should return \"Birdie\"');"
},
{
"text": "golfScore(4, 4)
should return \"Par\"",
- "testString": "assert(golfScore(4, 4) === \"Par\", 'golfScore(4, 4)
should return \"Par\"');"
+ "testString":
+ "assert(golfScore(4, 4) === \"Par\", 'golfScore(4, 4)
should return \"Par\"');"
},
{
"text": "golfScore(1, 1)
should return \"Hole-in-one!\"",
- "testString": "assert(golfScore(1, 1) === \"Hole-in-one!\", 'golfScore(1, 1)
should return \"Hole-in-one!\"');"
+ "testString":
+ "assert(golfScore(1, 1) === \"Hole-in-one!\", 'golfScore(1, 1)
should return \"Hole-in-one!\"');"
},
{
"text": "golfScore(5, 5)
should return \"Par\"",
- "testString": "assert(golfScore(5, 5) === \"Par\", 'golfScore(5, 5)
should return \"Par\"');"
+ "testString":
+ "assert(golfScore(5, 5) === \"Par\", 'golfScore(5, 5)
should return \"Par\"');"
},
{
"text": "golfScore(4, 5)
should return \"Bogey\"",
- "testString": "assert(golfScore(4, 5) === \"Bogey\", 'golfScore(4, 5)
should return \"Bogey\"');"
+ "testString":
+ "assert(golfScore(4, 5) === \"Bogey\", 'golfScore(4, 5)
should return \"Bogey\"');"
},
{
"text": "golfScore(4, 6)
should return \"Double Bogey\"",
- "testString": "assert(golfScore(4, 6) === \"Double Bogey\", 'golfScore(4, 6)
should return \"Double Bogey\"');"
+ "testString":
+ "assert(golfScore(4, 6) === \"Double Bogey\", 'golfScore(4, 6)
should return \"Double Bogey\"');"
},
{
"text": "golfScore(4, 7)
should return \"Go Home!\"",
- "testString": "assert(golfScore(4, 7) === \"Go Home!\", 'golfScore(4, 7)
should return \"Go Home!\"');"
+ "testString":
+ "assert(golfScore(4, 7) === \"Go Home!\", 'golfScore(4, 7)
should return \"Go Home!\"');"
},
{
"text": "golfScore(5, 9)
should return \"Go Home!\"",
- "testString": "assert(golfScore(5, 9) === \"Go Home!\", 'golfScore(5, 9)
should return \"Go Home!\"');"
+ "testString":
+ "assert(golfScore(5, 9) === \"Go Home!\", 'golfScore(5, 9)
should return \"Go Home!\"');"
}
],
"challengeType": 1,
@@ -5154,7 +5448,7 @@
"description": [
"If you have many options to choose from, use a switch
statement. A switch
statement tests a value and can have many case
statements which define various possible values. Statements are executed from the first matched case
value until a break
is encountered.",
"Here is a pseudocode example:",
- "switch(num) {
case value1:
statement1;
break;
case value2:
statement2;
break;
...
case valueN:
statementN;
break;
}
",
+ "switch(num) {
case value1:
statement1;
break;
case value2:
statement2;
break;
...
case valueN:
statementN;
break;
}
",
"case
values are tested with strict equality (===
). The break
tells JavaScript to stop executing statements. If the break
is omitted, the next statement will be executed.",
"
",
"Write a switch statement which tests val
and sets answer
for the following conditions:
1
- \"alpha\"
2
- \"beta\"
3
- \"gamma\"
4
- \"delta\""
@@ -5165,41 +5459,51 @@
],
"tests": [
{
- "text": "caseInSwitch(1)
should have a value of \"alpha\"",
- "testString": "assert(caseInSwitch(1) === \"alpha\", 'caseInSwitch(1)
should have a value of \"alpha\"');"
+ "text":
+ "caseInSwitch(1)
should have a value of \"alpha\"",
+ "testString":
+ "assert(caseInSwitch(1) === \"alpha\", 'caseInSwitch(1)
should have a value of \"alpha\"');"
},
{
- "text": "caseInSwitch(2)
should have a value of \"beta\"",
- "testString": "assert(caseInSwitch(2) === \"beta\", 'caseInSwitch(2)
should have a value of \"beta\"');"
+ "text":
+ "caseInSwitch(2)
should have a value of \"beta\"",
+ "testString":
+ "assert(caseInSwitch(2) === \"beta\", 'caseInSwitch(2)
should have a value of \"beta\"');"
},
{
- "text": "caseInSwitch(3)
should have a value of \"gamma\"",
- "testString": "assert(caseInSwitch(3) === \"gamma\", 'caseInSwitch(3)
should have a value of \"gamma\"');"
+ "text":
+ "caseInSwitch(3)
should have a value of \"gamma\"",
+ "testString":
+ "assert(caseInSwitch(3) === \"gamma\", 'caseInSwitch(3)
should have a value of \"gamma\"');"
},
{
- "text": "caseInSwitch(4)
should have a value of \"delta\"",
- "testString": "assert(caseInSwitch(4) === \"delta\", 'caseInSwitch(4)
should have a value of \"delta\"');"
+ "text":
+ "caseInSwitch(4)
should have a value of \"delta\"",
+ "testString":
+ "assert(caseInSwitch(4) === \"delta\", 'caseInSwitch(4)
should have a value of \"delta\"');"
},
{
- "text": "You should not use any if
or else
statements",
- "testString": "assert(!/else/g.test(code) || !/if/g.test(code), 'You should not use any if
or else
statements');"
+ "text":
+ "You should not use any if
or else
statements",
+ "testString":
+ "assert(!/else/g.test(code) || !/if/g.test(code), 'You should not use any if
or else
statements');"
},
{
"text": "You should have at least 3 break
statements",
- "testString": "assert(code.match(/break/g).length > 2, 'You should have at least 3 break
statements');"
+ "testString":
+ "assert(code.match(/break/g).length > 2, 'You should have at least 3 break
statements');"
}
],
- "MDNlinks": [
- "Switch Statement"
- ],
+ "MDNlinks": ["Switch Statement"],
"challengeType": 1,
"translations": {
"es": {
- "title": "Seleccionar desde diferentes opciones con la sentencia switch",
+ "title":
+ "Seleccionar desde diferentes opciones con la sentencia switch",
"description": [
"Si tienes varias opciones para elegir, usa una sentencia switch
. Una sentencia switch
prueba un valor y puede tener varias sentencias case
las cuales definen varios posibles valores. Las sentencias son ejecutadas desde el primer valor case
igualado hasta que se encuentr un break
.",
"Aquí hay un pseudocódigo de ejemplo:",
- "switch(num) {
case valor1:
sentencia1;
break;
case valor2:
sentencia2;
break;
...
case valorN:
sentenciaN;
break;
}
",
+ "switch(num) {
case valor1:
sentencia1;
break;
case valor2:
sentencia2;
break;
...
case valorN:
sentenciaN;
break;
}
",
"Los valores case
son probados con estricta igualdad (===
). El break
le dice a JavaScript que pare la ejecución del bloque de sentencias en el que está. Si se omite break
, se ejecutará la siguiente sentencia.",
"Instrucciones
",
"Escribe una sentencia switch
que pruebe val
y establezca answer
para las siguientes condiciones:
1
- \"alpha\"
2
- \"beta\"
3
- \"gamma\"
4
- \"delta\""
@@ -5237,7 +5541,7 @@
"description": [
"In a switch
statement you may not be able to specify all possible values as case
statements. Instead, you can add the default
statement which will be executed if no matching case
statements are found. Think of it like the final else
statement in an if/else
chain.",
"A default
statement should be the last case.",
- "switch (num) {
case value1:
statement1;
break;
case value2:
statement2;
break;
...
default:
defaultStatement;
break;
}
",
+ "switch (num) {
case value1:
statement1;
break;
case value2:
statement2;
break;
...
default:
defaultStatement;
break;
}
",
"
",
"Write a switch statement to set answer
for the following conditions:
\"a\"
- \"apple\"
\"b\"
- \"bird\"
\"c\"
- \"cat\"
default
- \"stuff\""
],
@@ -5247,52 +5551,68 @@
],
"tests": [
{
- "text": "switchOfStuff(\"a\")
should have a value of \"apple\"",
- "testString": "assert(switchOfStuff(\"a\") === \"apple\", 'switchOfStuff(\"a\")
should have a value of \"apple\"');"
+ "text":
+ "switchOfStuff(\"a\")
should have a value of \"apple\"",
+ "testString":
+ "assert(switchOfStuff(\"a\") === \"apple\", 'switchOfStuff(\"a\")
should have a value of \"apple\"');"
},
{
- "text": "switchOfStuff(\"b\")
should have a value of \"bird\"",
- "testString": "assert(switchOfStuff(\"b\") === \"bird\", 'switchOfStuff(\"b\")
should have a value of \"bird\"');"
+ "text":
+ "switchOfStuff(\"b\")
should have a value of \"bird\"",
+ "testString":
+ "assert(switchOfStuff(\"b\") === \"bird\", 'switchOfStuff(\"b\")
should have a value of \"bird\"');"
},
{
- "text": "switchOfStuff(\"c\")
should have a value of \"cat\"",
- "testString": "assert(switchOfStuff(\"c\") === \"cat\", 'switchOfStuff(\"c\")
should have a value of \"cat\"');"
+ "text":
+ "switchOfStuff(\"c\")
should have a value of \"cat\"",
+ "testString":
+ "assert(switchOfStuff(\"c\") === \"cat\", 'switchOfStuff(\"c\")
should have a value of \"cat\"');"
},
{
- "text": "switchOfStuff(\"d\")
should have a value of \"stuff\"",
- "testString": "assert(switchOfStuff(\"d\") === \"stuff\", 'switchOfStuff(\"d\")
should have a value of \"stuff\"');"
+ "text":
+ "switchOfStuff(\"d\")
should have a value of \"stuff\"",
+ "testString":
+ "assert(switchOfStuff(\"d\") === \"stuff\", 'switchOfStuff(\"d\")
should have a value of \"stuff\"');"
},
{
- "text": "switchOfStuff(4)
should have a value of \"stuff\"",
- "testString": "assert(switchOfStuff(4) === \"stuff\", 'switchOfStuff(4)
should have a value of \"stuff\"');"
+ "text":
+ "switchOfStuff(4)
should have a value of \"stuff\"",
+ "testString":
+ "assert(switchOfStuff(4) === \"stuff\", 'switchOfStuff(4)
should have a value of \"stuff\"');"
},
{
- "text": "You should not use any if
or else
statements",
- "testString": "assert(!/else/g.test(code) || !/if/g.test(code), 'You should not use any if
or else
statements');"
+ "text":
+ "You should not use any if
or else
statements",
+ "testString":
+ "assert(!/else/g.test(code) || !/if/g.test(code), 'You should not use any if
or else
statements');"
},
{
"text": "You should use a default
statement",
- "testString": "assert(switchOfStuff(\"string-to-trigger-default-case\") === \"stuff\", 'You should use a default
statement');"
+ "testString":
+ "assert(switchOfStuff(\"string-to-trigger-default-case\") === \"stuff\", 'You should use a default
statement');"
},
{
"text": "You should have at least 3 break
statements",
- "testString": "assert(code.match(/break/g).length > 2, 'You should have at least 3 break
statements');"
+ "testString":
+ "assert(code.match(/break/g).length > 2, 'You should have at least 3 break
statements');"
}
],
"challengeType": 1,
"translations": {
"es": {
- "title": "Agregar una opción por omisión (default) en una sentencia switch",
+ "title":
+ "Agregar una opción por omisión (default) en una sentencia switch",
"description": [
"En una sentencia switch
puede que no seas capaz de especificar todos los posibles valores en las sentencias case
. En su lugar, puedes agregar la sentencia default
la cual será ejecutada si no es encontrada ninguna coincidencia con alguna sentencia case
. Piensa en esto como la última sentencia else
en una cadena if/else
.",
"Una sentencia default
debería ser el último caso.",
- "switch(num) {
case valor1:
sentencia1;
break;
case valor2:
sentencia2;
break;
...
default:
sentenciaDefault;
}
",
+ "switch(num) {
case valor1:
sentencia1;
break;
case valor2:
sentencia2;
break;
...
default:
sentenciaDefault;
}
",
"Instrucciones
",
"Escribe una sentencia switch para establecer answer
para las siguientes condiciones:
\"a\"
- \"apple\"
\"b\"
- \"bird\"
\"c\"
- \"cat\"
default
- \"stuff\""
]
}
},
- "guideUrl": "https://guide.freecodecamp.org/certificates/adding-a-default-option-in-switch-statements",
+ "guideUrl":
+ "https://guide.freecodecamp.org/certificates/adding-a-default-option-in-switch-statements",
"files": {
"indexjs": {
"key": "indexjs",
@@ -5323,7 +5643,7 @@
"title": "Multiple Identical Options in Switch Statements",
"description": [
"If the break
statement is omitted from a switch
statement's case
, the following case
statement(s) are executed until a break
is encountered. If you have multiple inputs with the same output, you can represent them in a switch
statement like this:",
- "switch(val) {
case 1:
case 2:
case 3:
result = \"1, 2, or 3\";
break;
case 4:
result = \"4 alone\";
}
",
+ "switch(val) {
case 1:
case 2:
case 3:
result = \"1, 2, or 3\";
break;
case 4:
result = \"4 alone\";
}
",
"Cases for 1, 2, and 3 will all produce the same result.",
"
",
"Write a switch statement to set answer
for the following ranges:
1-3
- \"Low\"
4-6
- \"Mid\"
7-9
- \"High\"",
@@ -5336,47 +5656,59 @@
"tests": [
{
"text": "sequentialSizes(1)
should return \"Low\"",
- "testString": "assert(sequentialSizes(1) === \"Low\", 'sequentialSizes(1)
should return \"Low\"');"
+ "testString":
+ "assert(sequentialSizes(1) === \"Low\", 'sequentialSizes(1)
should return \"Low\"');"
},
{
"text": "sequentialSizes(2)
should return \"Low\"",
- "testString": "assert(sequentialSizes(2) === \"Low\", 'sequentialSizes(2)
should return \"Low\"');"
+ "testString":
+ "assert(sequentialSizes(2) === \"Low\", 'sequentialSizes(2)
should return \"Low\"');"
},
{
"text": "sequentialSizes(3)
should return \"Low\"",
- "testString": "assert(sequentialSizes(3) === \"Low\", 'sequentialSizes(3)
should return \"Low\"');"
+ "testString":
+ "assert(sequentialSizes(3) === \"Low\", 'sequentialSizes(3)
should return \"Low\"');"
},
{
"text": "sequentialSizes(4)
should return \"Mid\"",
- "testString": "assert(sequentialSizes(4) === \"Mid\", 'sequentialSizes(4)
should return \"Mid\"');"
+ "testString":
+ "assert(sequentialSizes(4) === \"Mid\", 'sequentialSizes(4)
should return \"Mid\"');"
},
{
"text": "sequentialSizes(5)
should return \"Mid\"",
- "testString": "assert(sequentialSizes(5) === \"Mid\", 'sequentialSizes(5)
should return \"Mid\"');"
+ "testString":
+ "assert(sequentialSizes(5) === \"Mid\", 'sequentialSizes(5)
should return \"Mid\"');"
},
{
"text": "sequentialSizes(6)
should return \"Mid\"",
- "testString": "assert(sequentialSizes(6) === \"Mid\", 'sequentialSizes(6)
should return \"Mid\"');"
+ "testString":
+ "assert(sequentialSizes(6) === \"Mid\", 'sequentialSizes(6)
should return \"Mid\"');"
},
{
"text": "sequentialSizes(7)
should return \"High\"",
- "testString": "assert(sequentialSizes(7) === \"High\", 'sequentialSizes(7)
should return \"High\"');"
+ "testString":
+ "assert(sequentialSizes(7) === \"High\", 'sequentialSizes(7)
should return \"High\"');"
},
{
"text": "sequentialSizes(8)
should return \"High\"",
- "testString": "assert(sequentialSizes(8) === \"High\", 'sequentialSizes(8)
should return \"High\"');"
+ "testString":
+ "assert(sequentialSizes(8) === \"High\", 'sequentialSizes(8)
should return \"High\"');"
},
{
"text": "sequentialSizes(9)
should return \"High\"",
- "testString": "assert(sequentialSizes(9) === \"High\", 'sequentialSizes(9)
should return \"High\"');"
+ "testString":
+ "assert(sequentialSizes(9) === \"High\", 'sequentialSizes(9)
should return \"High\"');"
},
{
- "text": "You should not use any if
or else
statements",
- "testString": "assert(!/else/g.test(code) || !/if/g.test(code), 'You should not use any if
or else
statements');"
+ "text":
+ "You should not use any if
or else
statements",
+ "testString":
+ "assert(!/else/g.test(code) || !/if/g.test(code), 'You should not use any if
or else
statements');"
},
{
"text": "You should have nine case
statements",
- "testString": "assert(code.match(/case/g).length === 9, 'You should have nine case
statements');"
+ "testString":
+ "assert(code.match(/case/g).length === 9, 'You should have nine case
statements');"
}
],
"challengeType": 1,
@@ -5385,7 +5717,7 @@
"title": "Múltiples opciones idénticas en una sentencias switch",
"description": [
"Si la sentencia break
es omitida de una sentencia case
de un switch
, las siguientes sentencias case
son ejecutadas hasta que sea encontrado un break
. Si tienes multiples entradas con la misma salida, puede representarlas en una sentencia switch
así:",
- "switch(val) {
case 1:
case 2:
case 3:
result = \"1, 2, or 3\";
break;
case 4:
result = \"4 alone\";
}
",
+ "switch(val) {
case 1:
case 2:
case 3:
result = \"1, 2, or 3\";
break;
case 4:
result = \"4 alone\";
}
",
"Los casos 1, 2, y 3 producirán el mismo resultado.",
"Instrucciones
",
"Escribe una sentencia switch
para establecer answer
para los siguientes rangos:
1-3
- \"Low\"
4-6
- \"Mid\"
7-9
- \"High\"",
@@ -5423,9 +5755,9 @@
"title": "Replacing If Else Chains with Switch",
"description": [
"If you have many options to choose from, a switch
statement can be easier to write than many chained if
/else if
statements. The following:",
- "if (val === 1) {
answer = \"a\";
} else if (val === 2) {
answer = \"b\";
} else {
answer = \"c\";
}
",
+ "if (val === 1) {
answer = \"a\";
} else if (val === 2) {
answer = \"b\";
} else {
answer = \"c\";
}
",
"can be replaced with:",
- "switch(val) {
case 1:
answer = \"a\";
break;
case 2:
answer = \"b\";
break;
default:
answer = \"c\";
}
",
+ "switch(val) {
case 1:
answer = \"a\";
break;
case 2:
answer = \"b\";
break;
default:
answer = \"c\";
}
",
"
",
"Change the chained if
/else if
statements into a switch
statement."
],
@@ -5435,44 +5767,59 @@
],
"tests": [
{
- "text": "You should not use any else
statements anywhere in the editor",
- "testString": "assert(!/else/g.test(code), 'You should not use any else
statements anywhere in the editor');"
+ "text":
+ "You should not use any else
statements anywhere in the editor",
+ "testString":
+ "assert(!/else/g.test(code), 'You should not use any else
statements anywhere in the editor');"
},
{
- "text": "You should not use any if
statements anywhere in the editor",
- "testString": "assert(!/if/g.test(code), 'You should not use any if
statements anywhere in the editor');"
+ "text":
+ "You should not use any if
statements anywhere in the editor",
+ "testString":
+ "assert(!/if/g.test(code), 'You should not use any if
statements anywhere in the editor');"
},
{
"text": "You should have at least four break
statements",
- "testString": "assert(code.match(/break/g).length >= 4, 'You should have at least four break
statements');"
+ "testString":
+ "assert(code.match(/break/g).length >= 4, 'You should have at least four break
statements');"
},
{
"text": "chainToSwitch(\"bob\")
should be \"Marley\"",
- "testString": "assert(chainToSwitch(\"bob\") === \"Marley\", 'chainToSwitch(\"bob\")
should be \"Marley\"');"
+ "testString":
+ "assert(chainToSwitch(\"bob\") === \"Marley\", 'chainToSwitch(\"bob\")
should be \"Marley\"');"
},
{
"text": "chainToSwitch(42)
should be \"The Answer\"",
- "testString": "assert(chainToSwitch(42) === \"The Answer\", 'chainToSwitch(42)
should be \"The Answer\"');"
+ "testString":
+ "assert(chainToSwitch(42) === \"The Answer\", 'chainToSwitch(42)
should be \"The Answer\"');"
},
{
"text": "chainToSwitch(1)
should be \"There is no #1\"",
- "testString": "assert(chainToSwitch(1) === \"There is no #1\", 'chainToSwitch(1)
should be \"There is no #1\"');"
+ "testString":
+ "assert(chainToSwitch(1) === \"There is no #1\", 'chainToSwitch(1)
should be \"There is no #1\"');"
},
{
- "text": "chainToSwitch(99)
should be \"Missed me by this much!\"",
- "testString": "assert(chainToSwitch(99) === \"Missed me by this much!\", 'chainToSwitch(99)
should be \"Missed me by this much!\"');"
+ "text":
+ "chainToSwitch(99)
should be \"Missed me by this much!\"",
+ "testString":
+ "assert(chainToSwitch(99) === \"Missed me by this much!\", 'chainToSwitch(99)
should be \"Missed me by this much!\"');"
},
{
"text": "chainToSwitch(7)
should be \"Ate Nine\"",
- "testString": "assert(chainToSwitch(7) === \"Ate Nine\", 'chainToSwitch(7)
should be \"Ate Nine\"');"
+ "testString":
+ "assert(chainToSwitch(7) === \"Ate Nine\", 'chainToSwitch(7)
should be \"Ate Nine\"');"
},
{
- "text": "chainToSwitch(\"John\")
should be \"\" (empty string)",
- "testString": "assert(chainToSwitch(\"John\") === \"\", 'chainToSwitch(\"John\")
should be \"\" (empty string)');"
+ "text":
+ "chainToSwitch(\"John\")
should be \"\" (empty string)",
+ "testString":
+ "assert(chainToSwitch(\"John\") === \"\", 'chainToSwitch(\"John\")
should be \"\" (empty string)');"
},
{
- "text": "chainToSwitch(156)
should be \"\" (empty string)",
- "testString": "assert(chainToSwitch(156) === \"\", 'chainToSwitch(156)
should be \"\" (empty string)');"
+ "text":
+ "chainToSwitch(156)
should be \"\" (empty string)",
+ "testString":
+ "assert(chainToSwitch(156) === \"\", 'chainToSwitch(156)
should be \"\" (empty string)');"
}
],
"challengeType": 1,
@@ -5481,9 +5828,9 @@
"title": "Reemplazar cadenas if else con switch",
"description": [
"Si tienes varias opciones para elegir, una sentencia switch
puede ser más fácil de escribir que varias sentencias if
/if else
anidadas. Lo siguiente:",
- "if (val === 1) {
respuesta = \"a\";
} else if (val === 2) {
respuesta = \"b\";
} else {
respuesta = \"c\";
}
",
+ "if (val === 1) {
respuesta = \"a\";
} else if (val === 2) {
respuesta = \"b\";
} else {
respuesta = \"c\";
}
",
"puede ser reemplazado con:",
- "switch(val) {
case 1:
respuesta = \"a\";
break;
case 2:
respuesta = \"b\";
break;
default:
respuesta = \"c\";
}
",
+ "switch(val) {
case 1:
respuesta = \"a\";
break;
case 2:
respuesta = \"b\";
break;
default:
respuesta = \"c\";
}
",
"Instrucciones
",
"Cambia las sentencias if
/if else
anidadas dentro de una sentencia switch
."
]
@@ -5530,28 +5877,30 @@
"description": [
"You may recall from Comparison with the Equality Operator that all comparison operators return a boolean true
or false
value.",
"Sometimes people use an if/else statement to do a comparison, like this:",
- "function isEqual(a,b) {
if (a === b) {
return true;
} else {
return false;
}
}
",
+ "function isEqual(a,b) {
if (a === b) {
return true;
} else {
return false;
}
}
",
"But there's a better way to do this. Since ===
returns true
or false
, we can return the result of the comparison:",
- "function isEqual(a,b) {
return a === b;
}
",
+ "function isEqual(a,b) {
return a === b;
}
",
"
",
"Fix the function isLess
to remove the if/else
statements."
],
"releasedOn": "January 1, 2016",
- "solutions": [
- "function isLess(a, b) {\n return a < b;\n}"
- ],
+ "solutions": ["function isLess(a, b) {\n return a < b;\n}"],
"tests": [
{
"text": "isLess(10,15)
should return true
",
- "testString": "assert(isLess(10,15) === true, 'isLess(10,15)
should return true
');"
+ "testString":
+ "assert(isLess(10,15) === true, 'isLess(10,15)
should return true
');"
},
{
"text": "isLess(15,10)
should return false
",
- "testString": "assert(isLess(15, 10) === false, 'isLess(15,10)
should return false
');"
+ "testString":
+ "assert(isLess(15, 10) === false, 'isLess(15,10)
should return false
');"
},
{
- "text": "You should not use any if
or else
statements",
- "testString": "assert(!/if|else/g.test(code), 'You should not use any if
or else
statements');"
+ "text":
+ "You should not use any if
or else
statements",
+ "testString":
+ "assert(!/if|else/g.test(code), 'You should not use any if
or else
statements');"
}
],
"challengeType": 1,
@@ -5561,9 +5910,9 @@
"description": [
"Tal vez recuerdes de La comparación con el operador de igualdad que todos los operadores de comparación retornan un valor booleano true
(verdadero) o false
(falso).",
"Un anti-patrón común es usar una sentencia if/else
para hacer una comparación y entonces retornar true
o false
:",
- "function sonIguales(a,b) {
if (a === b) {
return true;
} else {
return false;
}
}
",
+ "function sonIguales(a,b) {
if (a === b) {
return true;
} else {
return false;
}
}
",
"Ya que ===
returna true
(verdadero) o false
(falso), podemos simplemente retornar el resultado de la comparación:",
- "function sonIguales(a,b) {
return a === b;
}
",
+ "function sonIguales(a,b) {
return a === b;
}
",
"Instrucciones
",
"Arregla la función isLess
para remover las sentencias if/else
."
]
@@ -5598,7 +5947,7 @@
"description": [
"When a return
statement is reached, the execution of the current function stops and control returns to the calling location.",
"Example",
- "function myFun() {
console.log(\"Hello\");
return \"World\";
console.log(\"byebye\")
}
myFun();
",
+ "function myFun() {
console.log(\"Hello\");
return \"World\";
console.log(\"byebye\")
}
myFun();
",
"The above outputs \"Hello\" to the console, returns \"World\", but \"byebye\"
is never output, because the function exits at the return
statement.",
"
",
"Modify the function abTest
so that if a
or b
are less than 0
the function will immediately exit with a value of undefined
.",
@@ -5611,27 +5960,35 @@
"tests": [
{
"text": "abTest(2,2)
should return a number",
- "testString": "assert(typeof abTest(2,2) === 'number' , 'abTest(2,2)
should return a number');"
+ "testString":
+ "assert(typeof abTest(2,2) === 'number' , 'abTest(2,2)
should return a number');"
},
{
"text": "abTest(2,2)
should return 8
",
- "testString": "assert(abTest(2,2) === 8 , 'abTest(2,2)
should return 8
');"
+ "testString":
+ "assert(abTest(2,2) === 8 , 'abTest(2,2)
should return 8
');"
},
{
- "text": "abTest(-2,2)
should return undefined
",
- "testString": "assert(abTest(-2,2) === undefined , 'abTest(-2,2)
should return undefined
');"
+ "text":
+ "abTest(-2,2)
should return undefined
",
+ "testString":
+ "assert(abTest(-2,2) === undefined , 'abTest(-2,2)
should return undefined
');"
},
{
- "text": "abTest(2,-2)
should return undefined
",
- "testString": "assert(abTest(2,-2) === undefined , 'abTest(2,-2)
should return undefined
');"
+ "text":
+ "abTest(2,-2)
should return undefined
",
+ "testString":
+ "assert(abTest(2,-2) === undefined , 'abTest(2,-2)
should return undefined
');"
},
{
"text": "abTest(2,8)
should return 18
",
- "testString": "assert(abTest(2,8) === 18 , 'abTest(2,8)
should return 18
');"
+ "testString":
+ "assert(abTest(2,8) === 18 , 'abTest(2,8)
should return 18
');"
},
{
"text": "abTest(3,3)
should return 12
",
- "testString": "assert(abTest(3,3) === 12 , 'abTest(3,3)
should return 12
');"
+ "testString":
+ "assert(abTest(3,3) === 12 , 'abTest(3,3)
should return 12
');"
}
],
"challengeType": 1,
@@ -5641,7 +5998,7 @@
"description": [
"Cuando se alcanza una sentencia return
, la ejecución de la presente función se detiene y el control la retorna a la ubicación de la llamada.",
"Ejemplo",
- "function miFuncion() {
console.log(\"Hola\");
return \"Mundo\";
console.log(\"chaochao\")
}
miFuncion();
",
+ "function miFuncion() {
console.log(\"Hola\");
return \"Mundo\";
console.log(\"chaochao\")
}
miFuncion();
",
"Esta presenta en consola \"Hola\", retorna \"Mundo\", pero \"chaochao\"
nunca se presenta, porque la función sale con la sentencia return
.",
"Instrucciones
",
"Modifica la función abTest
de manera que si a
o b
son menores que 0
la función saldrá inmediatamente con un valor undefined
.",
@@ -5691,32 +6048,44 @@
],
"tests": [
{
- "text": "Cards Sequence 2, 3, 4, 5, 6 should return 5 Bet
",
- "testString": "assert((function(){ count = 0; cc(2);cc(3);cc(4);cc(5);var out = cc(6); if(out === \"5 Bet\") {return true;} return false; })(), 'Cards Sequence 2, 3, 4, 5, 6 should return 5 Bet
');"
+ "text":
+ "Cards Sequence 2, 3, 4, 5, 6 should return 5 Bet
",
+ "testString":
+ "assert((function(){ count = 0; cc(2);cc(3);cc(4);cc(5);var out = cc(6); if(out === \"5 Bet\") {return true;} return false; })(), 'Cards Sequence 2, 3, 4, 5, 6 should return 5 Bet
');"
},
{
"text": "Cards Sequence 7, 8, 9 should return 0 Hold
",
- "testString": "assert((function(){ count = 0; cc(7);cc(8);var out = cc(9); if(out === \"0 Hold\") {return true;} return false; })(), 'Cards Sequence 7, 8, 9 should return 0 Hold
');"
+ "testString":
+ "assert((function(){ count = 0; cc(7);cc(8);var out = cc(9); if(out === \"0 Hold\") {return true;} return false; })(), 'Cards Sequence 7, 8, 9 should return 0 Hold
');"
},
{
- "text": "Cards Sequence 10, J, Q, K, A should return -5 Hold
",
- "testString": "assert((function(){ count = 0; cc(10);cc('J');cc('Q');cc('K');var out = cc('A'); if(out === \"-5 Hold\") {return true;} return false; })(), 'Cards Sequence 10, J, Q, K, A should return -5 Hold
');"
+ "text":
+ "Cards Sequence 10, J, Q, K, A should return -5 Hold
",
+ "testString":
+ "assert((function(){ count = 0; cc(10);cc('J');cc('Q');cc('K');var out = cc('A'); if(out === \"-5 Hold\") {return true;} return false; })(), 'Cards Sequence 10, J, Q, K, A should return -5 Hold
');"
},
{
- "text": "Cards Sequence 3, 7, Q, 8, A should return -1 Hold
",
- "testString": "assert((function(){ count = 0; cc(3);cc(7);cc('Q');cc(8);var out = cc('A'); if(out === \"-1 Hold\") {return true;} return false; })(), 'Cards Sequence 3, 7, Q, 8, A should return -1 Hold
');"
+ "text":
+ "Cards Sequence 3, 7, Q, 8, A should return -1 Hold
",
+ "testString":
+ "assert((function(){ count = 0; cc(3);cc(7);cc('Q');cc(8);var out = cc('A'); if(out === \"-1 Hold\") {return true;} return false; })(), 'Cards Sequence 3, 7, Q, 8, A should return -1 Hold
');"
},
{
- "text": "Cards Sequence 2, J, 9, 2, 7 should return 1 Bet
",
- "testString": "assert((function(){ count = 0; cc(2);cc('J');cc(9);cc(2);var out = cc(7); if(out === \"1 Bet\") {return true;} return false; })(), 'Cards Sequence 2, J, 9, 2, 7 should return 1 Bet
');"
+ "text":
+ "Cards Sequence 2, J, 9, 2, 7 should return 1 Bet
",
+ "testString":
+ "assert((function(){ count = 0; cc(2);cc('J');cc(9);cc(2);var out = cc(7); if(out === \"1 Bet\") {return true;} return false; })(), 'Cards Sequence 2, J, 9, 2, 7 should return 1 Bet
');"
},
{
"text": "Cards Sequence 2, 2, 10 should return 1 Bet
",
- "testString": "assert((function(){ count = 0; cc(2);cc(2);var out = cc(10); if(out === \"1 Bet\") {return true;} return false; })(), 'Cards Sequence 2, 2, 10 should return 1 Bet
');"
+ "testString":
+ "assert((function(){ count = 0; cc(2);cc(2);var out = cc(10); if(out === \"1 Bet\") {return true;} return false; })(), 'Cards Sequence 2, 2, 10 should return 1 Bet
');"
},
{
- "text": "Cards Sequence 3, 2, A, 10, K should return -1 Hold
",
- "testString": "assert((function(){ count = 0; cc(3);cc(2);cc('A');cc(10);var out = cc('K'); if(out === \"-1 Hold\") {return true;} return false; })(), 'Cards Sequence 3, 2, A, 10, K should return -1 Hold
');"
+ "text":
+ "Cards Sequence 3, 2, A, 10, K should return -1 Hold
",
+ "testString":
+ "assert((function(){ count = 0; cc(3);cc(2);cc('A');cc(10);var out = cc('K'); if(out === \"-1 Hold\") {return true;} return false; })(), 'Cards Sequence 3, 2, A, 10, K should return -1 Hold
');"
}
],
"challengeType": 1,
@@ -5765,9 +6134,9 @@
"Objects are similar to arrays
, except that instead of using indexes to access and modify their data, you access the data in objects through what are called properties
.",
"Objects are useful for storing data in a structured way, and can represent real world objects, like a cat.",
"Here's a sample cat object:",
- "var cat = {
\"name\": \"Whiskers\",
\"legs\": 4,
\"tails\": 1,
\"enemies\": [\"Water\", \"Dogs\"]
};
",
+ "var cat = {
\"name\": \"Whiskers\",
\"legs\": 4,
\"tails\": 1,
\"enemies\": [\"Water\", \"Dogs\"]
};
",
"In this example, all the properties are stored as strings, such as - \"name\"
, \"legs\"
, and \"tails\"
. However, you can also use numbers as properties. You can even omit the quotes for single-word string properties, as follows:",
- "var anotherObject = {
make: \"Ford\",
5: \"five\",
\"model\": \"focus\"
};
",
+ "var anotherObject = {
make: \"Ford\",
5: \"five\",
\"model\": \"focus\"
};
",
"However, if your object has any non-string properties, JavaScript will automatically typecast them as strings.",
"
",
"Make an object that represents a dog called myDog
which contains the properties \"name\"
(a string), \"legs\"
, \"tails\"
and \"friends\"
.",
@@ -5778,24 +6147,34 @@
],
"tests": [
{
- "text": "myDog
should contain the property name
and it should be a string
.",
- "testString": "assert((function(z){if(z.hasOwnProperty(\"name\") && z.name !== undefined && typeof z.name === \"string\"){return true;}else{return false;}})(myDog), 'myDog
should contain the property name
and it should be a string
.');"
+ "text":
+ "myDog
should contain the property name
and it should be a string
.",
+ "testString":
+ "assert((function(z){if(z.hasOwnProperty(\"name\") && z.name !== undefined && typeof z.name === \"string\"){return true;}else{return false;}})(myDog), 'myDog
should contain the property name
and it should be a string
.');"
},
{
- "text": "myDog
should contain the property legs
and it should be a number
.",
- "testString": "assert((function(z){if(z.hasOwnProperty(\"legs\") && z.legs !== undefined && typeof z.legs === \"number\"){return true;}else{return false;}})(myDog), 'myDog
should contain the property legs
and it should be a number
.');"
+ "text":
+ "myDog
should contain the property legs
and it should be a number
.",
+ "testString":
+ "assert((function(z){if(z.hasOwnProperty(\"legs\") && z.legs !== undefined && typeof z.legs === \"number\"){return true;}else{return false;}})(myDog), 'myDog
should contain the property legs
and it should be a number
.');"
},
{
- "text": "myDog
should contain the property tails
and it should be a number
.",
- "testString": "assert((function(z){if(z.hasOwnProperty(\"tails\") && z.tails !== undefined && typeof z.tails === \"number\"){return true;}else{return false;}})(myDog), 'myDog
should contain the property tails
and it should be a number
.');"
+ "text":
+ "myDog
should contain the property tails
and it should be a number
.",
+ "testString":
+ "assert((function(z){if(z.hasOwnProperty(\"tails\") && z.tails !== undefined && typeof z.tails === \"number\"){return true;}else{return false;}})(myDog), 'myDog
should contain the property tails
and it should be a number
.');"
},
{
- "text": "myDog
should contain the property friends
and it should be an array
.",
- "testString": "assert((function(z){if(z.hasOwnProperty(\"friends\") && z.friends !== undefined && Array.isArray(z.friends)){return true;}else{return false;}})(myDog), 'myDog
should contain the property friends
and it should be an array
.');"
+ "text":
+ "myDog
should contain the property friends
and it should be an array
.",
+ "testString":
+ "assert((function(z){if(z.hasOwnProperty(\"friends\") && z.friends !== undefined && Array.isArray(z.friends)){return true;}else{return false;}})(myDog), 'myDog
should contain the property friends
and it should be an array
.');"
},
{
- "text": "myDog
should only contain all the given properties.",
- "testString": "assert((function(z){return Object.keys(z).length === 4;})(myDog), 'myDog
should only contain all the given properties.');"
+ "text":
+ "myDog
should only contain all the given properties.",
+ "testString":
+ "assert((function(z){return Object.keys(z).length === 4;})(myDog), 'myDog
should only contain all the given properties.');"
}
],
"challengeType": 1,
@@ -5842,9 +6221,7 @@
"};"
],
"head": [],
- "tail": [
- "(function(z){return z;})(myDog);"
- ]
+ "tail": ["(function(z){return z;})(myDog);"]
}
}
},
@@ -5855,7 +6232,7 @@
"There are two ways to access the properties of an object: dot notation (.
) and bracket notation ([]
), similar to an array.",
"Dot notation is what you use when you know the name of the property you're trying to access ahead of time.",
"Here is a sample of using dot notation (.
) to read an object's property:",
- "var myObj = {
prop1: \"val1\",
prop2: \"val2\"
};
var prop1val = myObj.prop1; // val1
var prop2val = myObj.prop2; // val2
",
+ "var myObj = {
prop1: \"val1\",
prop2: \"val2\"
};
var prop1val = myObj.prop1; // val1
var prop2val = myObj.prop2; // val2
",
"
",
"Read in the property values of testObj
using dot notation. Set the variable hatValue
equal to the object's property hat
and set the variable shirtValue
equal to the object's property shirt
."
],
@@ -5866,23 +6243,30 @@
"tests": [
{
"text": "hatValue
should be a string",
- "testString": "assert(typeof hatValue === 'string' , 'hatValue
should be a string');"
+ "testString":
+ "assert(typeof hatValue === 'string' , 'hatValue
should be a string');"
},
{
- "text": "The value of hatValue
should be \"ballcap\"
",
- "testString": "assert(hatValue === 'ballcap' , 'The value of hatValue
should be \"ballcap\"
');"
+ "text":
+ "The value of hatValue
should be \"ballcap\"
",
+ "testString":
+ "assert(hatValue === 'ballcap' , 'The value of hatValue
should be \"ballcap\"
');"
},
{
"text": "shirtValue
should be a string",
- "testString": "assert(typeof shirtValue === 'string' , 'shirtValue
should be a string');"
+ "testString":
+ "assert(typeof shirtValue === 'string' , 'shirtValue
should be a string');"
},
{
- "text": "The value of shirtValue
should be \"jersey\"
",
- "testString": "assert(shirtValue === 'jersey' , 'The value of shirtValue
should be \"jersey\"
');"
+ "text":
+ "The value of shirtValue
should be \"jersey\"
",
+ "testString":
+ "assert(shirtValue === 'jersey' , 'The value of shirtValue
should be \"jersey\"
');"
},
{
"text": "You should use dot notation twice",
- "testString": "assert(code.match(/testObj\\.\\w+/g).length > 1, 'You should use dot notation twice');"
+ "testString":
+ "assert(code.match(/testObj\\.\\w+/g).length > 1, 'You should use dot notation twice');"
}
],
"challengeType": 1,
@@ -5893,7 +6277,7 @@
"Hay dos maneras de acceder a las propiedades de un objeto: con el operador punto (.
) y con la notación corchete ([]
), similar al caso de un vector.",
"El operador punto es el que usas cuando de antemano sabes el nombre de la propiedad que estás intentando acceder.",
"Aquí está un ejemplo del uso del operador punto (.
) para leer una propiedad de un objeto:",
- "var miObj = {
prop1: \"val1\",
prop2: \"val2\"
};
var prop1val = miObj.prop1; // val1
var prop2val = miObj.prop2; // val2
",
+ "var miObj = {
prop1: \"val1\",
prop2: \"val2\"
};
var prop1val = miObj.prop1; // val1
var prop2val = miObj.prop2; // val2
",
"Instrucciones
",
"Lee los valores de propiedades de testObj
usando notación punto. Asigna la variable hatValue
igual a la propiedad objeto hat
y asigna la variable shirtValue
igual a la propiedad objeto shirt
."
]
@@ -5931,7 +6315,7 @@
"The second way to access the properties of an object is bracket notation ([]
). If the property of the object you are trying to access has a space in its name, you will need to use bracket notation.",
"However, you can still use bracket notation on object properties without spaces.",
"Here is a sample of using bracket notation to read an object's property:",
- "var myObj = {
\"Space Name\": \"Kirk\",
\"More Space\": \"Spock\",
\"NoSpace\": \"USS Enterprise\"
};
myObj[\"Space Name\"]; // Kirk
myObj['More Space']; // Spock
myObj[\"NoSpace\"]; // USS Enterprise
",
+ "var myObj = {
\"Space Name\": \"Kirk\",
\"More Space\": \"Spock\",
\"NoSpace\": \"USS Enterprise\"
};
myObj[\"Space Name\"]; // Kirk
myObj['More Space']; // Spock
myObj[\"NoSpace\"]; // USS Enterprise
",
"Note that property names with spaces in them must be in quotes (single or double).",
"
",
"Read the values of the properties \"an entree\"
and \"the drink\"
of testObj
using bracket notation and assign them to entreeValue
and drinkValue
respectively."
@@ -5943,40 +6327,49 @@
"tests": [
{
"text": "entreeValue
should be a string",
- "testString": "assert(typeof entreeValue === 'string' , 'entreeValue
should be a string');"
+ "testString":
+ "assert(typeof entreeValue === 'string' , 'entreeValue
should be a string');"
},
{
- "text": "The value of entreeValue
should be \"hamburger\"
",
- "testString": "assert(entreeValue === 'hamburger' , 'The value of entreeValue
should be \"hamburger\"
');"
+ "text":
+ "The value of entreeValue
should be \"hamburger\"
",
+ "testString":
+ "assert(entreeValue === 'hamburger' , 'The value of entreeValue
should be \"hamburger\"
');"
},
{
"text": "drinkValue
should be a string",
- "testString": "assert(typeof drinkValue === 'string' , 'drinkValue
should be a string');"
+ "testString":
+ "assert(typeof drinkValue === 'string' , 'drinkValue
should be a string');"
},
{
- "text": "The value of drinkValue
should be \"water\"
",
- "testString": "assert(drinkValue === 'water' , 'The value of drinkValue
should be \"water\"
');"
+ "text":
+ "The value of drinkValue
should be \"water\"
",
+ "testString":
+ "assert(drinkValue === 'water' , 'The value of drinkValue
should be \"water\"
');"
},
{
"text": "You should use bracket notation twice",
- "testString": "assert(code.match(/testObj\\s*?\\[('|\")[^'\"]+\\1\\]/g).length > 1, 'You should use bracket notation twice');"
+ "testString":
+ "assert(code.match(/testObj\\s*?\\[('|\")[^'\"]+\\1\\]/g).length > 1, 'You should use bracket notation twice');"
}
],
"challengeType": 1,
"translations": {
"es": {
- "title": "Acceder a las propiedades de objetos con la notación corchete",
+ "title":
+ "Acceder a las propiedades de objetos con la notación corchete",
"description": [
"La segunda manera de acceder a las propiedades de un objeto es con la notación corchete ([]
). Si el nombre de la propiedad del objeto que estás intentando acceder tiene un espacio, necesitarás usar la notación corchete.",
"Aquí está un ejemplo del uso de la notación corchete para leer una propiedad de un objeto:",
- "var miObj = {
\"Nombre con espacio\": \"Kirk\",
\"Mas espacio\": \"Spock\"
};
miObj[\"Nombre con espacio\"]; // Kirk
miObj['Mas espacio']; // Spock
",
+ "var miObj = {
\"Nombre con espacio\": \"Kirk\",
\"Mas espacio\": \"Spock\"
};
miObj[\"Nombre con espacio\"]; // Kirk
miObj['Mas espacio']; // Spock
",
"Nota que los nombres de propiedades con espacios tienen que estar entre comillas (apóstrofes o comillas).",
"Instrucciones
",
"Lee los valores de las propiedades \"an entree\"
y \"the drink\"
de testObj
usando la notación corchete."
]
}
},
- "guideUrl": "https://guide.freecodecamp.org/certificates/accessing-objects-properties-with-bracket-notation",
+ "guideUrl":
+ "https://guide.freecodecamp.org/certificates/accessing-objects-properties-with-bracket-notation",
"files": {
"indexjs": {
"key": "indexjs",
@@ -6008,9 +6401,9 @@
"description": [
"Another use of bracket notation on objects is to access a property which is stored as the value of a variable. This can be very useful for iterating through an object's properties or when accessing a lookup table.",
"Here is an example of using a variable to access a property:",
- "var dogs = {
Fido: \"Mutt\",\n Hunter: \"Doberman\",\n Snoopie: \"Beagle\"
};
var myDog = \"Hunter\";
var myBreed = dogs[myDog];
console.log(myBreed); // \"Doberman\"
",
+ "var dogs = {
Fido: \"Mutt\",\n Hunter: \"Doberman\",\n Snoopie: \"Beagle\"
};
var myDog = \"Hunter\";
var myBreed = dogs[myDog];
console.log(myBreed); // \"Doberman\"
",
"Another way you can use this concept is when the property's name is collected dynamically during the program execution, as follows:",
- "var someObj = {
propName: \"John\"
};
function propPrefix(str) {
var s = \"prop\";
return s + str;
}
var someProp = propPrefix(\"Name\"); // someProp now holds the value 'propName'
console.log(someObj[someProp]); // \"John\"
",
+ "var someObj = {
propName: \"John\"
};
function propPrefix(str) {
var s = \"prop\";
return s + str;
}
var someProp = propPrefix(\"Name\"); // someProp now holds the value 'propName'
console.log(someObj[someProp]); // \"John\"
",
"Note that we do not use quotes around the variable name when using it to access the property because we are using the value of the variable, not the name.",
"
",
"Use the playerNumber
variable to look up player 16
in testObj
using bracket notation. Then assign that name to the player
variable."
@@ -6022,27 +6415,36 @@
"tests": [
{
"text": "playerNumber
should be a number",
- "testString": "assert(typeof playerNumber === 'number', 'playerNumber
should be a number');"
+ "testString":
+ "assert(typeof playerNumber === 'number', 'playerNumber
should be a number');"
},
{
"text": "The variable player
should be a string",
- "testString": "assert(typeof player === 'string', 'The variable player
should be a string');"
+ "testString":
+ "assert(typeof player === 'string', 'The variable player
should be a string');"
},
{
"text": "The value of player
should be \"Montana\"",
- "testString": "assert(player === 'Montana', 'The value of player
should be \"Montana\"');"
+ "testString":
+ "assert(player === 'Montana', 'The value of player
should be \"Montana\"');"
},
{
- "text": "You should use bracket notation to access testObj
",
- "testString": "assert(/testObj\\s*?\\[.*?\\]/.test(code),'You should use bracket notation to access testObj
');"
+ "text":
+ "You should use bracket notation to access testObj
",
+ "testString":
+ "assert(/testObj\\s*?\\[.*?\\]/.test(code),'You should use bracket notation to access testObj
');"
},
{
- "text": "You should not assign the value Montana
to the variable player
directly.",
- "testString": "assert(!code.match(/player\\s*=\\s*\"|\\'\\s*Montana\\s*\"|\\'\\s*;/gi),'You should not assign the value Montana
to the variable player
directly.');"
+ "text":
+ "You should not assign the value Montana
to the variable player
directly.",
+ "testString":
+ "assert(!code.match(/player\\s*=\\s*\"|\\'\\s*Montana\\s*\"|\\'\\s*;/gi),'You should not assign the value Montana
to the variable player
directly.');"
},
{
- "text": "You should be using the variable playerNumber
in your bracket notation",
- "testString": "assert(/testObj\\s*?\\[\\s*playerNumber\\s*\\]/.test(code),'You should be using the variable playerNumber
in your bracket notation');"
+ "text":
+ "You should be using the variable playerNumber
in your bracket notation",
+ "testString":
+ "assert(/testObj\\s*?\\[\\s*playerNumber\\s*\\]/.test(code),'You should be using the variable playerNumber
in your bracket notation');"
}
],
"challengeType": 1,
@@ -6052,16 +6454,17 @@
"description": [
"Otro uso de la notación corchete sobre objetos es usar una variable para acceder a una propiedad. Esto puede ser muy útil en iteraciones sobre la lista de propiedades de un objetos o para hacer operaciones de búsqueda.",
"Aquí está un ejemplo del uso de una variable para acceder a una propiedad:",
- "var algunaProp = \"propNombre\";
var miObj = {
propNombre: \"Algún valor\"
}
miObj[algunaProp]; // \"Algún valor\"
",
+ "var algunaProp = \"propNombre\";
var miObj = {
propNombre: \"Algún valor\"
}
miObj[algunaProp]; // \"Algún valor\"
",
"Aquí hay uno más:",
- "var miPerro = \"Cazador\";
var perros = {
Fido: \"Mutt\",\n Cazador: \"Doberman\",\n Snoopie: \"Beagle\"
}
var raza = perros[miPerro]; // \"Cazador\"
console.log(raza)// \"Doberman\"
",
+ "var miPerro = \"Cazador\";
var perros = {
Fido: \"Mutt\",\n Cazador: \"Doberman\",\n Snoopie: \"Beagle\"
}
var raza = perros[miPerro]; // \"Cazador\"
console.log(raza)// \"Doberman\"
",
"Nota que no usamos comillas alrededor del nombre de la variable (miPerro
) cuando la usamos para acceder a la propiedad (perros[miPerro]
porque estamos usando el valor de la variable y no su nombre",
"Instrucciones
",
"Usa la variable playerNumber
para buscar y asignar a player
el jugador 16
de testObj
, usa la notación corchete."
]
}
},
- "guideUrl": "https://guide.freecodecamp.org/certificates/accessing-objects-properties-with-variables",
+ "guideUrl":
+ "https://guide.freecodecamp.org/certificates/accessing-objects-properties-with-variables",
"files": {
"indexjs": {
"key": "indexjs",
@@ -6093,7 +6496,7 @@
"description": [
"After you've created a JavaScript object, you can update its properties at any time just like you would update any other variable. You can use either dot or bracket notation to update.",
"For example, let's look at ourDog
:",
- "var ourDog = {
\"name\": \"Camper\",
\"legs\": 4,
\"tails\": 1,
\"friends\": [\"everything!\"]
};
",
+ "var ourDog = {
\"name\": \"Camper\",
\"legs\": 4,
\"tails\": 1,
\"friends\": [\"everything!\"]
};
",
"Since he's a particularly happy dog, let's change his name to \"Happy Camper\". Here's how we update his object's name property:",
"ourDog.name = \"Happy Camper\";
or",
"ourDog[\"name\"] = \"Happy Camper\";
",
@@ -6106,12 +6509,15 @@
],
"tests": [
{
- "text": "Update myDog
's \"name\"
property to equal \"Happy Coder\".",
- "testString": "assert(/happy coder/gi.test(myDog.name), 'Update myDog
's \"name\"
property to equal \"Happy Coder\".');"
+ "text":
+ "Update myDog
's \"name\"
property to equal \"Happy Coder\".",
+ "testString":
+ "assert(/happy coder/gi.test(myDog.name), 'Update myDog
's \"name\"
property to equal \"Happy Coder\".');"
},
{
"text": "Do not edit the myDog
definition",
- "testString": "assert(/\"name\": \"Coder\"/.test(code), 'Do not edit the myDog
definition');"
+ "testString":
+ "assert(/\"name\": \"Coder\"/.test(code), 'Do not edit the myDog
definition');"
}
],
"challengeType": 1,
@@ -6164,9 +6570,7 @@
""
],
"head": [],
- "tail": [
- "(function(z){return z;})(myDog);"
- ]
+ "tail": ["(function(z){return z;})(myDog);"]
}
}
},
@@ -6188,12 +6592,15 @@
],
"tests": [
{
- "text": "Add the property \"bark\"
to myDog
.",
- "testString": "assert(myDog.bark !== undefined, 'Add the property \"bark\"
to myDog
.');"
+ "text":
+ "Add the property \"bark\"
to myDog
.",
+ "testString":
+ "assert(myDog.bark !== undefined, 'Add the property \"bark\"
to myDog
.');"
},
{
"text": "Do not add \"bark\"
to the setup section",
- "testString": "assert(!/bark[^\\n]:/.test(code), 'Do not add \"bark\"
to the setup section');"
+ "testString":
+ "assert(!/bark[^\\n]:/.test(code), 'Do not add \"bark\"
to the setup section');"
}
],
"challengeType": 1,
@@ -6238,9 +6645,7 @@
""
],
"head": [],
- "tail": [
- "(function(z){return z;})(myDog);"
- ]
+ "tail": ["(function(z){return z;})(myDog);"]
}
}
},
@@ -6258,12 +6663,15 @@
],
"tests": [
{
- "text": "Delete the property \"tails\"
from myDog
.",
- "testString": "assert(typeof myDog === \"object\" && myDog.tails === undefined, 'Delete the property \"tails\"
from myDog
.');"
+ "text":
+ "Delete the property \"tails\"
from myDog
.",
+ "testString":
+ "assert(typeof myDog === \"object\" && myDog.tails === undefined, 'Delete the property \"tails\"
from myDog
.');"
},
{
"text": "Do not modify the myDog
setup",
- "testString": "assert(code.match(/\"tails\": 1/g).length > 1, 'Do not modify the myDog
setup');"
+ "testString":
+ "assert(code.match(/\"tails\": 1/g).length > 1, 'Do not modify the myDog
setup');"
}
],
"challengeType": 1,
@@ -6309,9 +6717,7 @@
""
],
"head": [],
- "tail": [
- "(function(z){return z;})(myDog);"
- ]
+ "tail": ["(function(z){return z;})(myDog);"]
}
}
},
@@ -6321,7 +6727,7 @@
"description": [
"Objects can be thought of as a key/value storage, like a dictionary. If you have tabular data, you can use an object to \"lookup\" values rather than a switch
statement or an if/else
chain. This is most useful when you know that your input data is limited to a certain range.",
"Here is an example of a simple reverse alphabet lookup:",
- "var alpha = {
1:\"Z\",
2:\"Y\",
3:\"X\",
4:\"W\",
...
24:\"C\",
25:\"B\",
26:\"A\"
};
alpha[2]; // \"Y\"
alpha[24]; // \"C\"
var value = 2;
alpha[value]; // \"Y\"
",
+ "var alpha = {
1:\"Z\",
2:\"Y\",
3:\"X\",
4:\"W\",
...
24:\"C\",
25:\"B\",
26:\"A\"
};
alpha[2]; // \"Y\"
alpha[24]; // \"C\"
var value = 2;
alpha[value]; // \"Y\"
",
"
",
"Convert the switch statement into an object called lookup
. Use it to look up val
and assign the associated string to the result
variable."
],
@@ -6331,40 +6737,57 @@
],
"tests": [
{
- "text": "phoneticLookup(\"alpha\")
should equal \"Adams\"
",
- "testString": "assert(phoneticLookup(\"alpha\") === 'Adams', 'phoneticLookup(\"alpha\")
should equal \"Adams\"
');"
+ "text":
+ "phoneticLookup(\"alpha\")
should equal \"Adams\"
",
+ "testString":
+ "assert(phoneticLookup(\"alpha\") === 'Adams', 'phoneticLookup(\"alpha\")
should equal \"Adams\"
');"
},
{
- "text": "phoneticLookup(\"bravo\")
should equal \"Boston\"
",
- "testString": "assert(phoneticLookup(\"bravo\") === 'Boston', 'phoneticLookup(\"bravo\")
should equal \"Boston\"
');"
+ "text":
+ "phoneticLookup(\"bravo\")
should equal \"Boston\"
",
+ "testString":
+ "assert(phoneticLookup(\"bravo\") === 'Boston', 'phoneticLookup(\"bravo\")
should equal \"Boston\"
');"
},
{
- "text": "phoneticLookup(\"charlie\")
should equal \"Chicago\"
",
- "testString": "assert(phoneticLookup(\"charlie\") === 'Chicago', 'phoneticLookup(\"charlie\")
should equal \"Chicago\"
');"
+ "text":
+ "phoneticLookup(\"charlie\")
should equal \"Chicago\"
",
+ "testString":
+ "assert(phoneticLookup(\"charlie\") === 'Chicago', 'phoneticLookup(\"charlie\")
should equal \"Chicago\"
');"
},
{
- "text": "phoneticLookup(\"delta\")
should equal \"Denver\"
",
- "testString": "assert(phoneticLookup(\"delta\") === 'Denver', 'phoneticLookup(\"delta\")
should equal \"Denver\"
');"
+ "text":
+ "phoneticLookup(\"delta\")
should equal \"Denver\"
",
+ "testString":
+ "assert(phoneticLookup(\"delta\") === 'Denver', 'phoneticLookup(\"delta\")
should equal \"Denver\"
');"
},
{
- "text": "phoneticLookup(\"echo\")
should equal \"Easy\"
",
- "testString": "assert(phoneticLookup(\"echo\") === 'Easy', 'phoneticLookup(\"echo\")
should equal \"Easy\"
');"
+ "text":
+ "phoneticLookup(\"echo\")
should equal \"Easy\"
",
+ "testString":
+ "assert(phoneticLookup(\"echo\") === 'Easy', 'phoneticLookup(\"echo\")
should equal \"Easy\"
');"
},
{
- "text": "phoneticLookup(\"foxtrot\")
should equal \"Frank\"
",
- "testString": "assert(phoneticLookup(\"foxtrot\") === 'Frank', 'phoneticLookup(\"foxtrot\")
should equal \"Frank\"
');"
+ "text":
+ "phoneticLookup(\"foxtrot\")
should equal \"Frank\"
",
+ "testString":
+ "assert(phoneticLookup(\"foxtrot\") === 'Frank', 'phoneticLookup(\"foxtrot\")
should equal \"Frank\"
');"
},
{
- "text": "phoneticLookup(\"\")
should equal undefined
",
- "testString": "assert(typeof phoneticLookup(\"\") === 'undefined', 'phoneticLookup(\"\")
should equal undefined
');"
+ "text":
+ "phoneticLookup(\"\")
should equal undefined
",
+ "testString":
+ "assert(typeof phoneticLookup(\"\") === 'undefined', 'phoneticLookup(\"\")
should equal undefined
');"
},
{
"text": "You should not modify the return
statement",
- "testString": "assert(code.match(/return\\sresult;/), 'You should not modify the return
statement');"
+ "testString":
+ "assert(code.match(/return\\sresult;/), 'You should not modify the return
statement');"
},
{
- "text": "You should not use case
, switch
, or if
statements",
- "testString": "assert(!/case|switch|if/g.test(code), 'You should not use case
, switch
, or if
statements'); "
+ "text":
+ "You should not use case
, switch
, or if
statements",
+ "testString":
+ "assert(!/case|switch|if/g.test(code), 'You should not use case
, switch
, or if
statements'); "
}
],
"challengeType": 1,
@@ -6374,7 +6797,7 @@
"description": [
"Los objetos pueden ser considerados como un almacenamiento llave/valor, como un diccionario. Si tienes datos tabulados, puedes almacenarlos en un objeto para después \"buscar\" valores, en lugar de emplear una sentencia switch
o una secuencia de if/else
. Esto es más útil cuando sabes que tus datos de entrada son limitados a un cierto rango.",
"Aquí está un ejemplo de una simple búsqueda inversa de alfabeto:",
- "var alfa = {
1:\"Z\",
2:\"Y\",
3:\"X\",
4:\"W\",
...
24:\"C\",
25:\"B\",
26:\"A\"
};
alfa[2]; // \"Y\"
alfa[24]; // \"C\"
var valor = 2;
alfa[valor]; // \"Y\"
",
+ "var alfa = {
1:\"Z\",
2:\"Y\",
3:\"X\",
4:\"W\",
...
24:\"C\",
25:\"B\",
26:\"A\"
};
alfa[2]; // \"Y\"
alfa[24]; // \"C\"
var valor = 2;
alfa[valor]; // \"Y\"
",
"Instrucciones
",
"Convierte la sentencia switch en una tabla de búsqueda llamada lookup
. Usala para buscar val
y asigna la cadena asociada a la variable result
."
]
@@ -6429,7 +6852,7 @@
"description": [
"Sometimes it is useful to check if the property of a given object exists or not. We can use the .hasOwnProperty(propname)
method of objects to determine if that object has the given property name. .hasOwnProperty()
returns true
or false
if the property is found or not.",
"Example",
- "var myObj = {
top: \"hat\",
bottom: \"pants\"
};
myObj.hasOwnProperty(\"top\"); // true
myObj.hasOwnProperty(\"middle\"); // false
",
+ "var myObj = {
top: \"hat\",
bottom: \"pants\"
};
myObj.hasOwnProperty(\"top\"); // true
myObj.hasOwnProperty(\"middle\"); // false
",
"
",
"Modify the function checkObj
to test myObj
for checkProp
. If the property is found, return that property's value. If not, return \"Not Found\"
."
],
@@ -6439,16 +6862,22 @@
],
"tests": [
{
- "text": "checkObj(\"gift\")
should return \"pony\"
.",
- "testString": "assert(checkObj(\"gift\") === \"pony\", 'checkObj(\"gift\")
should return \"pony\"
.');"
+ "text":
+ "checkObj(\"gift\")
should return \"pony\"
.",
+ "testString":
+ "assert(checkObj(\"gift\") === \"pony\", 'checkObj(\"gift\")
should return \"pony\"
.');"
},
{
- "text": "checkObj(\"pet\")
should return \"kitten\"
.",
- "testString": "assert(checkObj(\"pet\") === \"kitten\", 'checkObj(\"pet\")
should return \"kitten\"
.');"
+ "text":
+ "checkObj(\"pet\")
should return \"kitten\"
.",
+ "testString":
+ "assert(checkObj(\"pet\") === \"kitten\", 'checkObj(\"pet\")
should return \"kitten\"
.');"
},
{
- "text": "checkObj(\"house\")
should return \"Not Found\"
.",
- "testString": "assert(checkObj(\"house\") === \"Not Found\", 'checkObj(\"house\")
should return \"Not Found\"
.');"
+ "text":
+ "checkObj(\"house\")
should return \"Not Found\"
.",
+ "testString":
+ "assert(checkObj(\"house\") === \"Not Found\", 'checkObj(\"house\")
should return \"Not Found\"
.');"
}
],
"challengeType": 1,
@@ -6458,7 +6887,7 @@
"description": [
"A veces es útil revisar si cierta propiedad existe o no en un objeto dado. Podemos usar el método de objetos .hasOwnProperty(nomprop)
para determinar si un objeto tiene la propiedad nomprop
. .hasOwnProperty()
retorna true
o false
si la propiedad es encontrada o no.",
"Ejemplo",
- "var miObj = {
arriba: \"sombrero\",
abajo: \"pantalones\"
};
miObj.hasOwnProperty(\"arriba\"); // true
miObj.hasOwnProperty(\"medio\"); // false
",
+ "var miObj = {
arriba: \"sombrero\",
abajo: \"pantalones\"
};
miObj.hasOwnProperty(\"arriba\"); // true
miObj.hasOwnProperty(\"medio\"); // false
",
"Instrucciones
",
"Modifica la función checkObj
que prueba si myObj
tiene la propiedad checkProp
. Si la propiedad es encontrada, retorna el valor de esa propiedad. Si no, retorna \"Not Found\"
."
]
@@ -6497,11 +6926,11 @@
"description": [
"Sometimes you may want to store data in a flexible Data Structure. A JavaScript object is one way to handle flexible data. They allow for arbitrary combinations of strings, numbers, booleans, arrays, functions, and objects.",
"Here's an example of a complex data structure:",
- "var ourMusic = [
{
\"artist\": \"Daft Punk\",
\"title\": \"Homework\",
\"release_year\": 1997,
\"formats\": [
\"CD\",
\"Cassette\",
\"LP\"
],
\"gold\": true
}
];
",
+ "var ourMusic = [
{
\"artist\": \"Daft Punk\",
\"title\": \"Homework\",
\"release_year\": 1997,
\"formats\": [
\"CD\",
\"Cassette\",
\"LP\"
],
\"gold\": true
}
];
",
"This is an array which contains one object inside. The object has various pieces of metadata about an album. It also has a nested \"formats\"
array. If you want to add more album records, you can do this by adding records to the top level array.",
"Objects hold data in a property, which has a key-value format. In the example above, \"artist\": \"Daft Punk\"
is a property that has a key of \"artist\"
and a value of \"Daft Punk\"
.",
"JavaScript Object Notation or JSON
is a related data interchange format used to store data.",
- "{
\"artist\": \"Daft Punk\",
\"title\": \"Homework\",
\"release_year\": 1997,
\"formats\": [
\"CD\",
\"Cassette\",
\"LP\"
],
\"gold\": true
}
",
+ "{
\"artist\": \"Daft Punk\",
\"title\": \"Homework\",
\"release_year\": 1997,
\"formats\": [
\"CD\",
\"Cassette\",
\"LP\"
],
\"gold\": true
}
",
"Note
You will need to place a comma after every object in the array, unless it is the last object in the array.",
"
",
"Add a new album to the myMusic
array. Add artist
and title
strings, release_year
number, and a formats
array of strings."
@@ -6513,39 +6942,53 @@
"tests": [
{
"text": "myMusic
should be an array",
- "testString": "assert(Array.isArray(myMusic), 'myMusic
should be an array');"
+ "testString":
+ "assert(Array.isArray(myMusic), 'myMusic
should be an array');"
},
{
"text": "myMusic
should have at least two elements",
- "testString": "assert(myMusic.length > 1, 'myMusic
should have at least two elements');"
+ "testString":
+ "assert(myMusic.length > 1, 'myMusic
should have at least two elements');"
},
{
"text": "myMusic[1]
should be an object",
- "testString": "assert(typeof myMusic[1] === 'object', 'myMusic[1]
should be an object');"
+ "testString":
+ "assert(typeof myMusic[1] === 'object', 'myMusic[1]
should be an object');"
},
{
"text": "myMusic[1]
should have at least 4 properties",
- "testString": "assert(Object.keys(myMusic[1]).length > 3, 'myMusic[1]
should have at least 4 properties');"
+ "testString":
+ "assert(Object.keys(myMusic[1]).length > 3, 'myMusic[1]
should have at least 4 properties');"
},
{
- "text": "myMusic[1]
should contain an artist
property which is a string",
- "testString": "assert(myMusic[1].hasOwnProperty('artist') && typeof myMusic[1].artist === 'string', 'myMusic[1]
should contain an artist
property which is a string');"
+ "text":
+ "myMusic[1]
should contain an artist
property which is a string",
+ "testString":
+ "assert(myMusic[1].hasOwnProperty('artist') && typeof myMusic[1].artist === 'string', 'myMusic[1]
should contain an artist
property which is a string');"
},
{
- "text": "myMusic[1]
should contain a title
property which is a string",
- "testString": "assert(myMusic[1].hasOwnProperty('title') && typeof myMusic[1].title === 'string', 'myMusic[1]
should contain a title
property which is a string');"
+ "text":
+ "myMusic[1]
should contain a title
property which is a string",
+ "testString":
+ "assert(myMusic[1].hasOwnProperty('title') && typeof myMusic[1].title === 'string', 'myMusic[1]
should contain a title
property which is a string');"
},
{
- "text": "myMusic[1]
should contain a release_year
property which is a number",
- "testString": "assert(myMusic[1].hasOwnProperty('release_year') && typeof myMusic[1].release_year === 'number', 'myMusic[1]
should contain a release_year
property which is a number');"
+ "text":
+ "myMusic[1]
should contain a release_year
property which is a number",
+ "testString":
+ "assert(myMusic[1].hasOwnProperty('release_year') && typeof myMusic[1].release_year === 'number', 'myMusic[1]
should contain a release_year
property which is a number');"
},
{
- "text": "myMusic[1]
should contain a formats
property which is an array",
- "testString": "assert(myMusic[1].hasOwnProperty('formats') && Array.isArray(myMusic[1].formats), 'myMusic[1]
should contain a formats
property which is an array');"
+ "text":
+ "myMusic[1]
should contain a formats
property which is an array",
+ "testString":
+ "assert(myMusic[1].hasOwnProperty('formats') && Array.isArray(myMusic[1].formats), 'myMusic[1]
should contain a formats
property which is an array');"
},
{
- "text": "formats
should be an array of strings with at least two elements",
- "testString": "assert(myMusic[1].formats.every(function(item) { return (typeof item === \"string\")}) && myMusic[1].formats.length > 1, 'formats
should be an array of strings with at least two elements');"
+ "text":
+ "formats
should be an array of strings with at least two elements",
+ "testString":
+ "assert(myMusic[1].formats.every(function(item) { return (typeof item === \"string\")}) && myMusic[1].formats.length > 1, 'formats
should be an array of strings with at least two elements');"
}
],
"challengeType": 1,
@@ -6555,7 +6998,7 @@
"description": [
"Los objetos JavaScript son flexibles porque permiten Estructuras de Datos con combinaciones arbitrarias de cadenas, números, booleanos, vectores, funciones, y objetos.",
"Aquí está un ejemplo de un objeto complicado:",
- "var nuestraMusica = [
{
\"artista\": \"Daft Punk\",
\"titulo\": \"Homework\",
\"año_publicacion\": 1997,
\"formatos\": [
\"CD\",
\"Cassette\",
\"LP\" ],
\"oro\": true
}
];
",
+ "var nuestraMusica = [
{
\"artista\": \"Daft Punk\",
\"titulo\": \"Homework\",
\"año_publicacion\": 1997,
\"formatos\": [
\"CD\",
\"Cassette\",
\"LP\" ],
\"oro\": true
}
];
",
"Este es un vector de objetos con diversos metadatos acerca de un álbum musical. Además tiene anidado un vector formatos
. En el vector de nivel superior, pueden añadirse otros registros del álbum.",
"Nota
En vectores que tengan más de un objeto, necesitarás separar un objeto de otro mediante comas.",
"Instrucciones
",
@@ -6598,7 +7041,7 @@
"description": [
"The sub-properties of objects can be accessed by chaining together the dot or bracket notation.",
"Here is a nested object:",
- "var ourStorage = {
\"desk\": {
\"drawer\": \"stapler\"
},
\"cabinet\": {
\"top drawer\": {
\"folder1\": \"a file\",
\"folder2\": \"secrets\"
},
\"bottom drawer\": \"soda\"
}
};
ourStorage.cabinet[\"top drawer\"].folder2; // \"secrets\"
ourStorage.desk.drawer; // \"stapler\"
",
+ "var ourStorage = {
\"desk\": {
\"drawer\": \"stapler\"
},
\"cabinet\": {
\"top drawer\": {
\"folder1\": \"a file\",
\"folder2\": \"secrets\"
},
\"bottom drawer\": \"soda\"
}
};
ourStorage.cabinet[\"top drawer\"].folder2; // \"secrets\"
ourStorage.desk.drawer; // \"stapler\"
",
"
",
"Access the myStorage
object and assign the contents of the glove box
property to the gloveBoxContents
variable. Use bracket notation for properties with a space in their name."
],
@@ -6609,11 +7052,14 @@
"tests": [
{
"text": "gloveBoxContents
should equal \"maps\"",
- "testString": "assert(gloveBoxContents === \"maps\", 'gloveBoxContents
should equal \"maps\"');"
+ "testString":
+ "assert(gloveBoxContents === \"maps\", 'gloveBoxContents
should equal \"maps\"');"
},
{
- "text": "Use dot and bracket notation to access myStorage
",
- "testString": "assert(/=\\s*myStorage\\.car\\.inside\\[\\s*(\"|')glove box\\1\\s*\\]/g.test(code), 'Use dot and bracket notation to access myStorage
');"
+ "text":
+ "Use dot and bracket notation to access myStorage
",
+ "testString":
+ "assert(/=\\s*myStorage\\.car\\.inside\\[\\s*(\"|')glove box\\1\\s*\\]/g.test(code), 'Use dot and bracket notation to access myStorage
');"
}
],
"challengeType": 1,
@@ -6623,13 +7069,14 @@
"description": [
"Las sub-propiedades de los objetos pueden ser accesadas mediante encadenamiento de la notación punto o corchete.",
"Aquí está un objeto anidado:",
- "var nuestroAlmacen = {
\"escritorio\": {
\"cajon\": \"grapadora\"
},
\"armario\": {
\"cajón superior\": {
\"legajador1\": \"un archivo\",
\"legajador2\": \"secretos\"
},
\"cajón inferior\": \"gaseosa\"
}
}
nuestroAlmacen.armario[\"cajón superior\"].legajador2; // \"secretos\"
nuestroAlmacen.escritorio.cajon; // \"grapadora\"
",
+ "var nuestroAlmacen = {
\"escritorio\": {
\"cajon\": \"grapadora\"
},
\"armario\": {
\"cajón superior\": {
\"legajador1\": \"un archivo\",
\"legajador2\": \"secretos\"
},
\"cajón inferior\": \"gaseosa\"
}
}
nuestroAlmacen.armario[\"cajón superior\"].legajador2; // \"secretos\"
nuestroAlmacen.escritorio.cajon; // \"grapadora\"
",
"Instrucciones
",
"Accede al objeto myStorage
para recuperar el contenido de glove box
. Usa notación corchete para las propiedades con un espacio en su nombre."
]
}
},
- "guideUrl": "https://guide.freecodecamp.org/certificates/accessing-nested-objects-in-json",
+ "guideUrl":
+ "https://guide.freecodecamp.org/certificates/accessing-nested-objects-in-json",
"files": {
"indexjs": {
"key": "indexjs",
@@ -6670,7 +7117,7 @@
"description": [
"As we have seen in earlier examples, objects can contain both nested objects and nested arrays. Similar to accessing nested objects, Array bracket notation can be chained to access nested arrays.",
"Here is an example of how to access a nested array:",
- "var ourPets = [
{
animalType: \"cat\",
names: [
\"Meowzer\",
\"Fluffy\",
\"Kit-Cat\"
]
},
{
animalType: \"dog\",
names: [
\"Spot\",
\"Bowser\",
\"Frankie\"
]
}
];
ourPets[0].names[1]; // \"Fluffy\"
ourPets[1].names[0]; // \"Spot\"
",
+ "var ourPets = [
{
animalType: \"cat\",
names: [
\"Meowzer\",
\"Fluffy\",
\"Kit-Cat\"
]
},
{
animalType: \"dog\",
names: [
\"Spot\",
\"Bowser\",
\"Frankie\"
]
}
];
ourPets[0].names[1]; // \"Fluffy\"
ourPets[1].names[0]; // \"Spot\"
",
"
",
"Retrieve the second tree from the variable myPlants
using object dot and array bracket notation."
],
@@ -6681,11 +7128,14 @@
"tests": [
{
"text": "secondTree
should equal \"pine\"",
- "testString": "assert(secondTree === \"pine\", 'secondTree
should equal \"pine\"');"
+ "testString":
+ "assert(secondTree === \"pine\", 'secondTree
should equal \"pine\"');"
},
{
- "text": "Use dot and bracket notation to access myPlants
",
- "testString": "assert(/=\\s*myPlants\\[1\\].list\\[1\\]/.test(code), 'Use dot and bracket notation to access myPlants
');"
+ "text":
+ "Use dot and bracket notation to access myPlants
",
+ "testString":
+ "assert(/=\\s*myPlants\\[1\\].list\\[1\\]/.test(code), 'Use dot and bracket notation to access myPlants
');"
}
],
"challengeType": 1,
@@ -6695,13 +7145,14 @@
"description": [
"Como hemos visto en ejemplos anteriores, los objetos pueden contener objetos anidados y vectores anidados. De forma similar a acceder a objetos anidados, la notación corchete en vectores puede ser encadenada para acceder a vectores anidados.",
"Aquí está un ejemplo de como acceder a un vector anidado:",
- "var nuestrasMascotas = {
\"gatos\": [
\"Maullador\",
\"Blandito\",
\"Kit-Cat\"
],
\"perros\": [
\"Mancha\",
\"Bowser\",
\"Frankie\"
]
};
nuestrasMascotas.cats[1]; // \"Blandito\"
nuestrasMascotas.dogs[0]; // \"Mancha\"
",
+ "var nuestrasMascotas = {
\"gatos\": [
\"Maullador\",
\"Blandito\",
\"Kit-Cat\"
],
\"perros\": [
\"Mancha\",
\"Bowser\",
\"Frankie\"
]
};
nuestrasMascotas.cats[1]; // \"Blandito\"
nuestrasMascotas.dogs[0]; // \"Mancha\"
",
"Instrucciones
",
"Recupera el segundo arbol de la variable myPlants
usando notación punto para objetos y notación corchete para vectores."
]
}
},
- "guideUrl": "https://guide.freecodecamp.org/certificates/access-array-data-with-indexes",
+ "guideUrl":
+ "https://guide.freecodecamp.org/certificates/access-array-data-with-indexes",
"files": {
"indexjs": {
"key": "indexjs",
@@ -6767,32 +7218,46 @@
],
"tests": [
{
- "text": "After updateRecords(5439, \"artist\", \"ABBA\")
, artist
should be \"ABBA\"
",
- "testString": "collection = collectionCopy; assert(updateRecords(5439, \"artist\", \"ABBA\")[5439][\"artist\"] === \"ABBA\", 'After updateRecords(5439, \"artist\", \"ABBA\")
, artist
should be \"ABBA\"
');"
+ "text":
+ "After updateRecords(5439, \"artist\", \"ABBA\")
, artist
should be \"ABBA\"
",
+ "testString":
+ "collection = collectionCopy; assert(updateRecords(5439, \"artist\", \"ABBA\")[5439][\"artist\"] === \"ABBA\", 'After updateRecords(5439, \"artist\", \"ABBA\")
, artist
should be \"ABBA\"
');"
},
{
- "text": "After updateRecords(5439, \"tracks\", \"Take a Chance on Me\")
, tracks
should have \"Take a Chance on Me\"
as the last element.",
- "testString": "assert(updateRecords(5439, \"tracks\", \"Take a Chance on Me\")[5439][\"tracks\"].pop() === \"Take a Chance on Me\", 'After updateRecords(5439, \"tracks\", \"Take a Chance on Me\")
, tracks
should have \"Take a Chance on Me\"
as the last element.');"
+ "text":
+ "After updateRecords(5439, \"tracks\", \"Take a Chance on Me\")
, tracks
should have \"Take a Chance on Me\"
as the last element.",
+ "testString":
+ "assert(updateRecords(5439, \"tracks\", \"Take a Chance on Me\")[5439][\"tracks\"].pop() === \"Take a Chance on Me\", 'After updateRecords(5439, \"tracks\", \"Take a Chance on Me\")
, tracks
should have \"Take a Chance on Me\"
as the last element.');"
},
{
- "text": "After updateRecords(2548, \"artist\", \"\")
, artist
should not be set",
- "testString": "updateRecords(2548, \"artist\", \"\"); assert(!collection[2548].hasOwnProperty(\"artist\"), 'After updateRecords(2548, \"artist\", \"\")
, artist
should not be set');"
+ "text":
+ "After updateRecords(2548, \"artist\", \"\")
, artist
should not be set",
+ "testString":
+ "updateRecords(2548, \"artist\", \"\"); assert(!collection[2548].hasOwnProperty(\"artist\"), 'After updateRecords(2548, \"artist\", \"\")
, artist
should not be set');"
},
{
- "text": "After updateRecords(1245, \"tracks\", \"Addicted to Love\")
, tracks
should have \"Addicted to Love\"
as the last element.",
- "testString": "assert(updateRecords(1245, \"tracks\", \"Addicted to Love\")[1245][\"tracks\"].pop() === \"Addicted to Love\", 'After updateRecords(1245, \"tracks\", \"Addicted to Love\")
, tracks
should have \"Addicted to Love\"
as the last element.');"
+ "text":
+ "After updateRecords(1245, \"tracks\", \"Addicted to Love\")
, tracks
should have \"Addicted to Love\"
as the last element.",
+ "testString":
+ "assert(updateRecords(1245, \"tracks\", \"Addicted to Love\")[1245][\"tracks\"].pop() === \"Addicted to Love\", 'After updateRecords(1245, \"tracks\", \"Addicted to Love\")
, tracks
should have \"Addicted to Love\"
as the last element.');"
},
{
- "text": "After updateRecords(2468, \"tracks\", \"Free\")
, tracks
should have \"1999\"
as the first element.",
- "testString": "assert(updateRecords(2468, \"tracks\", \"Free\")[2468][\"tracks\"][0] === \"1999\", 'After updateRecords(2468, \"tracks\", \"Free\")
, tracks
should have \"1999\"
as the first element.');"
+ "text":
+ "After updateRecords(2468, \"tracks\", \"Free\")
, tracks
should have \"1999\"
as the first element.",
+ "testString":
+ "assert(updateRecords(2468, \"tracks\", \"Free\")[2468][\"tracks\"][0] === \"1999\", 'After updateRecords(2468, \"tracks\", \"Free\")
, tracks
should have \"1999\"
as the first element.');"
},
{
- "text": "After updateRecords(2548, \"tracks\", \"\")
, tracks
should not be set",
- "testString": "updateRecords(2548, \"tracks\", \"\"); assert(!collection[2548].hasOwnProperty(\"tracks\"), 'After updateRecords(2548, \"tracks\", \"\")
, tracks
should not be set');"
+ "text":
+ "After updateRecords(2548, \"tracks\", \"\")
, tracks
should not be set",
+ "testString":
+ "updateRecords(2548, \"tracks\", \"\"); assert(!collection[2548].hasOwnProperty(\"tracks\"), 'After updateRecords(2548, \"tracks\", \"\")
, tracks
should not be set');"
},
{
- "text": "After updateRecords(1245, \"album\", \"Riptide\")
, album
should be \"Riptide\"
",
- "testString": "assert(updateRecords(1245, \"album\", \"Riptide\")[1245][\"album\"] === \"Riptide\", 'After updateRecords(1245, \"album\", \"Riptide\")
, album
should be \"Riptide\"
');"
+ "text":
+ "After updateRecords(1245, \"album\", \"Riptide\")
, album
should be \"Riptide\"
",
+ "testString":
+ "assert(updateRecords(1245, \"album\", \"Riptide\")[1245][\"album\"] === \"Riptide\", 'After updateRecords(1245, \"album\", \"Riptide\")
, album
should be \"Riptide\"
');"
}
],
"challengeType": 1,
@@ -6870,7 +7335,7 @@
"description": [
"You can run the same code multiple times by using a loop.",
"The first type of loop we will learn is called a \"while
\" loop because it runs \"while\" a specified condition is true and stops once that condition is no longer true.",
- "var ourArray = [];
var i = 0;
while(i < 5) {
ourArray.push(i);
i++;
}
",
+ "var ourArray = [];
var i = 0;
while(i < 5) {
ourArray.push(i);
i++;
}
",
"Let's try getting a while loop to work by pushing values to an array.",
"
",
"Push the numbers 0 through 4 to myArray
using a while
loop."
@@ -6881,11 +7346,13 @@
"tests": [
{
"text": "You should be using a while
loop for this.",
- "testString": "assert(code.match(/while/g), 'You should be using a while
loop for this.');"
+ "testString":
+ "assert(code.match(/while/g), 'You should be using a while
loop for this.');"
},
{
"text": "myArray
should equal [0,1,2,3,4]
.",
- "testString": "assert.deepEqual(myArray, [0,1,2,3,4], 'myArray
should equal [0,1,2,3,4]
.');"
+ "testString":
+ "assert.deepEqual(myArray, [0,1,2,3,4], 'myArray
should equal [0,1,2,3,4]
.');"
}
],
"challengeType": 1,
@@ -6939,7 +7406,7 @@
"The condition
statement is evaluated at the beginning of every loop iteration and will continue as long as it evaluates to true
. When condition
is false
at the start of the iteration, the loop will stop executing. This means if condition
starts as false
, your loop will never execute.",
"The final-expression
is executed at the end of each loop iteration, prior to the next condition
check and is usually used to increment or decrement your loop counter.",
"In the following example we initialize with i = 0
and iterate while our condition i < 5
is true. We'll increment i
by 1
in each loop iteration with i++
as our final-expression
.",
- "var ourArray = [];
for (var i = 0; i < 5; i++) {
ourArray.push(i);
}
",
+ "var ourArray = [];
for (var i = 0; i < 5; i++) {
ourArray.push(i);
}
",
"ourArray
will now contain [0,1,2,3,4]
.",
"
",
"Use a for
loop to work to push the values 1 through 5 onto myArray
."
@@ -6950,11 +7417,13 @@
"tests": [
{
"text": "You should be using a for
loop for this.",
- "testString": "assert(code.match(/for\\s*\\(/g).length > 1, 'You should be using a for
loop for this.');"
+ "testString":
+ "assert(code.match(/for\\s*\\(/g).length > 1, 'You should be using a for
loop for this.');"
},
{
"text": "myArray
should equal [1,2,3,4,5]
.",
- "testString": "assert.deepEqual(myArray, [1,2,3,4,5], 'myArray
should equal [1,2,3,4,5]
.');"
+ "testString":
+ "assert.deepEqual(myArray, [1,2,3,4,5], 'myArray
should equal [1,2,3,4,5]
.');"
}
],
"challengeType": 1,
@@ -7013,7 +7482,7 @@
"description": [
"For loops don't have to iterate one at a time. By changing our final-expression
, we can count by even numbers.",
"We'll start at i = 0
and loop while i < 10
. We'll increment i
by 2 each loop with i += 2
.",
- "var ourArray = [];
for (var i = 0; i < 10; i += 2) {
ourArray.push(i);
}
",
+ "var ourArray = [];
for (var i = 0; i < 10; i += 2) {
ourArray.push(i);
}
",
"ourArray
will now contain [0,2,4,6,8]
.",
"Let's change our initialization
so we can count by odd numbers.",
"
",
@@ -7025,11 +7494,13 @@
"tests": [
{
"text": "You should be using a for
loop for this.",
- "testString": "assert(code.match(/for\\s*\\(/g).length > 1, 'You should be using a for
loop for this.');"
+ "testString":
+ "assert(code.match(/for\\s*\\(/g).length > 1, 'You should be using a for
loop for this.');"
},
{
"text": "myArray
should equal [1,3,5,7,9]
.",
- "testString": "assert.deepEqual(myArray, [1,3,5,7,9], 'myArray
should equal [1,3,5,7,9]
.');"
+ "testString":
+ "assert.deepEqual(myArray, [1,3,5,7,9], 'myArray
should equal [1,3,5,7,9]
.');"
}
],
"challengeType": 1,
@@ -7084,7 +7555,7 @@
"A for loop can also count backwards, so long as we can define the right conditions.",
"In order to count backwards by twos, we'll need to change our initialization
, condition
, and final-expression
.",
"We'll start at i = 10
and loop while i > 0
. We'll decrement i
by 2 each loop with i -= 2
.",
- "var ourArray = [];
for (var i=10; i > 0; i-=2) {
ourArray.push(i);
}
",
+ "var ourArray = [];
for (var i=10; i > 0; i-=2) {
ourArray.push(i);
}
",
"ourArray
will now contain [10,8,6,4,2]
.",
"Let's change our initialization
and final-expression
so we can count backward by twos by odd numbers.",
"
",
@@ -7096,15 +7567,18 @@
"tests": [
{
"text": "You should be using a for
loop for this.",
- "testString": "assert(code.match(/for\\s*\\(/g).length > 1, 'You should be using a for
loop for this.');"
+ "testString":
+ "assert(code.match(/for\\s*\\(/g).length > 1, 'You should be using a for
loop for this.');"
},
{
"text": "You should be using the array method push
.",
- "testString": "assert(code.match(/myArray.push/), 'You should be using the array method push
.');"
+ "testString":
+ "assert(code.match(/myArray.push/), 'You should be using the array method push
.');"
},
{
"text": "myArray
should equal [9,7,5,3,1]
.",
- "testString": "assert.deepEqual(myArray, [9,7,5,3,1], 'myArray
should equal [9,7,5,3,1]
.');"
+ "testString":
+ "assert.deepEqual(myArray, [9,7,5,3,1], 'myArray
should equal [9,7,5,3,1]
.');"
}
],
"challengeType": 1,
@@ -7158,7 +7632,7 @@
"title": "Iterate Through an Array with a For Loop",
"description": [
"A common task in JavaScript is to iterate through the contents of an array. One way to do that is with a for
loop. This code will output each element of the array arr
to the console:",
- "var arr = [10,9,8,7,6];
for (var i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
",
+ "var arr = [10,9,8,7,6];
for (var i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
",
"Remember that Arrays have zero-based numbering, which means the last index of the array is length - 1. Our condition for this loop is i < arr.length
, which stops when i
is at length - 1.",
"
",
"Declare and initialize a variable total
to 0
. Use a for
loop to add the value of each element of the myArr
array to total
."
@@ -7170,19 +7644,24 @@
"tests": [
{
"text": "total
should be declared and initialized to 0",
- "testString": "assert(code.match(/var.*?total\\s*=\\s*0.*?;/), 'total
should be declared and initialized to 0');"
+ "testString":
+ "assert(code.match(/var.*?total\\s*=\\s*0.*?;/), 'total
should be declared and initialized to 0');"
},
{
"text": "total
should equal 20",
- "testString": "assert(total === 20, 'total
should equal 20');"
+ "testString":
+ "assert(total === 20, 'total
should equal 20');"
},
{
- "text": "You should use a for
loop to iterate through myArr
",
- "testString": "assert(code.match(/for\\s*\\(/g).length > 1 && code.match(/myArr\\s*\\[/), 'You should use a for
loop to iterate through myArr
');"
+ "text":
+ "You should use a for
loop to iterate through myArr
",
+ "testString":
+ "assert(code.match(/for\\s*\\(/g).length > 1 && code.match(/myArr\\s*\\[/), 'You should use a for
loop to iterate through myArr
');"
},
{
"text": "Do not set total
to 20 directly",
- "testString": "assert(!code.match(/total[\\s\\+\\-]*=\\s*(\\d(?!\\s*[;,])|[1-9])/g), 'Do not set total
to 20 directly');"
+ "testString":
+ "assert(!code.match(/total[\\s\\+\\-]*=\\s*(\\d(?!\\s*[;,])|[1-9])/g), 'Do not set total
to 20 directly');"
}
],
"challengeType": 1,
@@ -7191,7 +7670,7 @@
"title": "Iterar a través de un vector con un ciclo for",
"description": [
"Una tarea común en JavaScript es iterar a traves del contenido de un vector. Una manera de hacerlo es con un ciclo for
. Este código imprimirá cada elemento del vector arr
en la consola:",
- "var arr = [10,9,8,7,6];
for (var i=0; i < arr.length; i++) {
console.log(arr[i]);
}
",
+ "var arr = [10,9,8,7,6];
for (var i=0; i < arr.length; i++) {
console.log(arr[i]);
}
",
"Recuerda que los vectores tienen numeración que comienza en cero, la cual significa que el último índice del vector es su longitud - 1. Nuestra condición para este ciclo es i < arr.length
, que lo detendrá cuando i
sea la longitud - 1.",
"Instrucciones
",
"Declara e inicializa una variable total
en 0
. Usa un ciclo for
para añadir el valor de cada elemento del vector myArr
a total
."
@@ -7231,7 +7710,7 @@
"title": "Nesting For Loops",
"description": [
"If you have a multi-dimensional array, you can use the same logic as the prior waypoint to loop through both the array and any sub-arrays. Here is an example:",
- "var arr = [
[1,2], [3,4], [5,6]
];
for (var i=0; i < arr.length; i++) {
for (var j=0; j < arr[i].length; j++) {
console.log(arr[i][j]);
}
}
",
+ "var arr = [
[1,2], [3,4], [5,6]
];
for (var i=0; i < arr.length; i++) {
for (var j=0; j < arr[i].length; j++) {
console.log(arr[i][j]);
}
}
",
"This outputs each sub-element in arr
one at a time. Note that for the inner loop, we are checking the .length
of arr[i]
, since arr[i]
is itself an array.",
"
",
"Modify function multiplyAll
so that it multiplies the product
variable by each number in the sub-arrays of arr
"
@@ -7242,16 +7721,22 @@
],
"tests": [
{
- "text": "multiplyAll([[1],[2],[3]])
should return 6
",
- "testString": "assert(multiplyAll([[1],[2],[3]]) === 6, 'multiplyAll([[1],[2],[3]])
should return 6
');"
+ "text":
+ "multiplyAll([[1],[2],[3]])
should return 6
",
+ "testString":
+ "assert(multiplyAll([[1],[2],[3]]) === 6, 'multiplyAll([[1],[2],[3]])
should return 6
');"
},
{
- "text": "multiplyAll([[1,2],[3,4],[5,6,7]])
should return 5040
",
- "testString": "assert(multiplyAll([[1,2],[3,4],[5,6,7]]) === 5040, 'multiplyAll([[1,2],[3,4],[5,6,7]])
should return 5040
');"
+ "text":
+ "multiplyAll([[1,2],[3,4],[5,6,7]])
should return 5040
",
+ "testString":
+ "assert(multiplyAll([[1,2],[3,4],[5,6,7]]) === 5040, 'multiplyAll([[1,2],[3,4],[5,6,7]])
should return 5040
');"
},
{
- "text": "multiplyAll([[5,1],[0.2, 4, 0.5],[3, 9]])
should return 54
",
- "testString": "assert(multiplyAll([[5,1],[0.2, 4, 0.5],[3, 9]]) === 54, 'multiplyAll([[5,1],[0.2, 4, 0.5],[3, 9]])
should return 54
');"
+ "text":
+ "multiplyAll([[5,1],[0.2, 4, 0.5],[3, 9]])
should return 54
",
+ "testString":
+ "assert(multiplyAll([[5,1],[0.2, 4, 0.5],[3, 9]]) === 54, 'multiplyAll([[5,1],[0.2, 4, 0.5],[3, 9]])
should return 54
');"
}
],
"challengeType": 1,
@@ -7260,7 +7745,7 @@
"title": "Anidar ciclos for",
"description": [
"Si tienes una matriz multi-dimensional, puedes usar la misma lógica del punto anterior para iterar a través de un vector y cualquier sub-vector. Aquí está un ejemplo:",
- "var arr = [
[1,2], [3,4], [5,6]
];
for (var i=0; i < arr.length; i++) {
for (var j=0; j < arr[i].length; j++) {
console.log(arr[i][j]);
}
}
",
+ "var arr = [
[1,2], [3,4], [5,6]
];
for (var i=0; i < arr.length; i++) {
for (var j=0; j < arr[i].length; j++) {
console.log(arr[i][j]);
}
}
",
"Esto imprime cada sub-elemento en arr
uno a la vez. Nota que en el ciclo interior, estamos comprobando la longitud .length
de arr[i]
, ya que arr[i]
es por si mismo un vector.",
"Instrucciones
",
"Modifica la función multiplyAll
de manera que esta multiplique la variable product
por cada número en los sub-vectores de arr
"
@@ -7296,13 +7781,13 @@
"description": [
"You can run the same code multiple times by using a loop.",
"The next type of loop you will learn is called a \"do...while
\" loop because it first will \"do
\" one pass of the code inside the loop no matter what, and then it runs \"while
\" a specified condition is true and stops once that condition is no longer true. Let's look at an example.",
- "var ourArray = [];
var i = 0;
do {
ourArray.push(i);
i++;
} while (i < 5);
",
+ "var ourArray = [];
var i = 0;
do {
ourArray.push(i);
i++;
} while (i < 5);
",
"This behaves just as you would expect with any other type of loop, and the resulting array will look like [0, 1, 2, 3, 4]
. However, what makes the do...while
different from other loops is how it behaves when the condition fails on the first check. Let's see this in action.",
"Here is a regular while loop that will run the code in the loop as long as i < 5
.",
- "var ourArray = [];
var i = 5;
while (i < 5) {
ourArray.push(i);
i++;
}
",
+ "var ourArray = [];
var i = 5;
while (i < 5) {
ourArray.push(i);
i++;
}
",
"Notice that we initialize the value of i
to be 5. When we execute the next line, we notice that i
is not less than 5. So we do not execute the code inside the loop. The result is that ourArray
will end up with nothing added to it, so it will still look like this []
when all the code in the example above finishes running.",
"Now, take a look at a do...while
loop.",
- "var ourArray = [];
var i = 5;
do {
ourArray.push(i);
i++;
} while (i < 5);
",
+ "var ourArray = [];
var i = 5;
do {
ourArray.push(i);
i++;
} while (i < 5);
",
"In this case, we initialize the value of i
as 5, just like we did with the while loop. When we get to the next line, there is no check for the value of i
, so we go to the code inside the curly braces and execute it. We will add one element to the array and increment i
before we get to the condition check. Then, when we get to checking if i < 5
see that i
is now 6, which fails the conditional check. So we exit the loop and are done. At the end of the above example, the value of ourArray
is [5]
.",
"Essentially, a do...while
loop ensures that the code inside the loop will run at least once.",
"Let's try getting a do...while
loop to work by pushing values to an array.",
@@ -7314,16 +7799,20 @@
],
"tests": [
{
- "text": "You should be using a do...while
loop for this.",
- "testString": "assert(code.match(/do/g), 'You should be using a do...while
loop for this.');"
+ "text":
+ "You should be using a do...while
loop for this.",
+ "testString":
+ "assert(code.match(/do/g), 'You should be using a do...while
loop for this.');"
},
{
"text": "myArray
should equal [10]
.",
- "testString": "assert.deepEqual(myArray, [10], 'myArray
should equal [10]
.');"
+ "testString":
+ "assert.deepEqual(myArray, [10], 'myArray
should equal [10]
.');"
},
{
"text": "i
should equal 11
",
- "testString": "assert.deepEqual(i, 11, 'i
should equal 11
');"
+ "testString":
+ "assert.deepEqual(i, 11, 'i
should equal 11
');"
}
],
"challengeType": 1,
@@ -7370,28 +7859,39 @@
],
"tests": [
{
- "text": "\"Kristian\", \"lastName\"
should return \"Vos\"
",
- "testString": "assert(lookUpProfile('Kristian','lastName') === \"Vos\", '\"Kristian\", \"lastName\"
should return \"Vos\"
');"
+ "text":
+ "\"Kristian\", \"lastName\"
should return \"Vos\"
",
+ "testString":
+ "assert(lookUpProfile('Kristian','lastName') === \"Vos\", '\"Kristian\", \"lastName\"
should return \"Vos\"
');"
},
{
- "text": "\"Sherlock\", \"likes\"
should return [\"Intriguing Cases\", \"Violin\"]
",
- "testString": "assert.deepEqual(lookUpProfile(\"Sherlock\", \"likes\"), [\"Intriguing Cases\", \"Violin\"], '\"Sherlock\", \"likes\"
should return [\"Intriguing Cases\", \"Violin\"]
');"
+ "text":
+ "\"Sherlock\", \"likes\"
should return [\"Intriguing Cases\", \"Violin\"]
",
+ "testString":
+ "assert.deepEqual(lookUpProfile(\"Sherlock\", \"likes\"), [\"Intriguing Cases\", \"Violin\"], '\"Sherlock\", \"likes\"
should return [\"Intriguing Cases\", \"Violin\"]
');"
},
{
"text": "\"Harry\",\"likes\"
should return an array",
- "testString": "assert(typeof lookUpProfile(\"Harry\", \"likes\") === \"object\", '\"Harry\",\"likes\"
should return an array');"
+ "testString":
+ "assert(typeof lookUpProfile(\"Harry\", \"likes\") === \"object\", '\"Harry\",\"likes\"
should return an array');"
},
{
- "text": "\"Bob\", \"number\"
should return \"No such contact\"",
- "testString": "assert(lookUpProfile(\"Bob\", \"number\") === \"No such contact\", '\"Bob\", \"number\"
should return \"No such contact\"');"
+ "text":
+ "\"Bob\", \"number\"
should return \"No such contact\"",
+ "testString":
+ "assert(lookUpProfile(\"Bob\", \"number\") === \"No such contact\", '\"Bob\", \"number\"
should return \"No such contact\"');"
},
{
- "text": "\"Bob\", \"potato\"
should return \"No such contact\"",
- "testString": "assert(lookUpProfile(\"Bob\", \"potato\") === \"No such contact\", '\"Bob\", \"potato\"
should return \"No such contact\"');"
+ "text":
+ "\"Bob\", \"potato\"
should return \"No such contact\"",
+ "testString":
+ "assert(lookUpProfile(\"Bob\", \"potato\") === \"No such contact\", '\"Bob\", \"potato\"
should return \"No such contact\"');"
},
{
- "text": "\"Akira\", \"address\"
should return \"No such property\"",
- "testString": "assert(lookUpProfile(\"Akira\", \"address\") === \"No such property\", '\"Akira\", \"address\"
should return \"No such property\"');"
+ "text":
+ "\"Akira\", \"address\"
should return \"No such property\"",
+ "testString":
+ "assert(lookUpProfile(\"Akira\", \"address\") === \"No such property\", '\"Akira\", \"address\"
should return \"No such property\"');"
}
],
"challengeType": 1,
@@ -7468,21 +7968,24 @@
"
",
"Change randomFraction
to return a random number instead of returning 0
."
],
- "solutions": [
- "function randomFraction() {\n return Math.random();\n}"
- ],
+ "solutions": ["function randomFraction() {\n return Math.random();\n}"],
"tests": [
{
"text": "randomFraction
should return a random number.",
- "testString": "assert(typeof randomFraction() === \"number\", 'randomFraction
should return a random number.');"
+ "testString":
+ "assert(typeof randomFraction() === \"number\", 'randomFraction
should return a random number.');"
},
{
- "text": "The number returned by randomFraction
should be a decimal.",
- "testString": "assert((randomFraction()+''). match(/\\./g), 'The number returned by randomFraction
should be a decimal.');"
+ "text":
+ "The number returned by randomFraction
should be a decimal.",
+ "testString":
+ "assert((randomFraction()+''). match(/\\./g), 'The number returned by randomFraction
should be a decimal.');"
},
{
- "text": "You should be using Math.random
to generate the random decimal number.",
- "testString": "assert(code.match(/Math\\.random/g).length >= 0, 'You should be using Math.random
to generate the random decimal number.');"
+ "text":
+ "You should be using Math.random
to generate the random decimal number.",
+ "testString":
+ "assert(code.match(/Math\\.random/g).length >= 0, 'You should be using Math.random
to generate the random decimal number.');"
}
],
"challengeType": 1,
@@ -7514,9 +8017,7 @@
"}"
],
"head": [],
- "tail": [
- "(function(){return randomFraction();})();"
- ]
+ "tail": ["(function(){return randomFraction();})();"]
}
}
},
@@ -7538,20 +8039,28 @@
],
"tests": [
{
- "text": "The result of randomWholeNum
should be a whole number.",
- "testString": "assert(typeof randomWholeNum() === \"number\" && (function(){var r = randomWholeNum();return Math.floor(r) === r;})(), 'The result of randomWholeNum
should be a whole number.');"
+ "text":
+ "The result of randomWholeNum
should be a whole number.",
+ "testString":
+ "assert(typeof randomWholeNum() === \"number\" && (function(){var r = randomWholeNum();return Math.floor(r) === r;})(), 'The result of randomWholeNum
should be a whole number.');"
},
{
- "text": "You should be using Math.random
to generate a random number.",
- "testString": "assert(code.match(/Math.random/g).length > 1, 'You should be using Math.random
to generate a random number.');"
+ "text":
+ "You should be using Math.random
to generate a random number.",
+ "testString":
+ "assert(code.match(/Math.random/g).length > 1, 'You should be using Math.random
to generate a random number.');"
},
{
- "text": "You should have multiplied the result of Math.random
by 10 to make it a number that is between zero and nine.",
- "testString": "assert(code.match(/\\s*?Math.random\\s*?\\(\\s*?\\)\\s*?\\*\\s*?10[\\D]\\s*?/g) || code.match(/\\s*?10\\s*?\\*\\s*?Math.random\\s*?\\(\\s*?\\)\\s*?/g), 'You should have multiplied the result of Math.random
by 10 to make it a number that is between zero and nine.');"
+ "text":
+ "You should have multiplied the result of Math.random
by 10 to make it a number that is between zero and nine.",
+ "testString":
+ "assert(code.match(/\\s*?Math.random\\s*?\\(\\s*?\\)\\s*?\\*\\s*?10[\\D]\\s*?/g) || code.match(/\\s*?10\\s*?\\*\\s*?Math.random\\s*?\\(\\s*?\\)\\s*?/g), 'You should have multiplied the result of Math.random
by 10 to make it a number that is between zero and nine.');"
},
{
- "text": "You should use Math.floor
to remove the decimal part of the number.",
- "testString": "assert(code.match(/Math.floor/g).length > 1, 'You should use Math.floor
to remove the decimal part of the number.');"
+ "text":
+ "You should use Math.floor
to remove the decimal part of the number.",
+ "testString":
+ "assert(code.match(/Math.floor/g).length > 1, 'You should use Math.floor
to remove the decimal part of the number.');"
}
],
"challengeType": 1,
@@ -7589,9 +8098,7 @@
"}"
],
"head": [],
- "tail": [
- "(function(){return randomWholeNum();})();"
- ]
+ "tail": ["(function(){return randomWholeNum();})();"]
}
}
},
@@ -7611,20 +8118,28 @@
],
"tests": [
{
- "text": "The lowest random number that can be generated by randomRange
should be equal to your minimum number, myMin
.",
- "testString": "assert(calcMin === 5, 'The lowest random number that can be generated by randomRange
should be equal to your minimum number, myMin
.');"
+ "text":
+ "The lowest random number that can be generated by randomRange
should be equal to your minimum number, myMin
.",
+ "testString":
+ "assert(calcMin === 5, 'The lowest random number that can be generated by randomRange
should be equal to your minimum number, myMin
.');"
},
{
- "text": "The highest random number that can be generated by randomRange
should be equal to your maximum number, myMax
.",
- "testString": "assert(calcMax === 15, 'The highest random number that can be generated by randomRange
should be equal to your maximum number, myMax
.');"
+ "text":
+ "The highest random number that can be generated by randomRange
should be equal to your maximum number, myMax
.",
+ "testString":
+ "assert(calcMax === 15, 'The highest random number that can be generated by randomRange
should be equal to your maximum number, myMax
.');"
},
{
- "text": "The random number generated by randomRange
should be an integer, not a decimal.",
- "testString": "assert(randomRange(0,1) % 1 === 0 , 'The random number generated by randomRange
should be an integer, not a decimal.');"
+ "text":
+ "The random number generated by randomRange
should be an integer, not a decimal.",
+ "testString":
+ "assert(randomRange(0,1) % 1 === 0 , 'The random number generated by randomRange
should be an integer, not a decimal.');"
},
{
- "text": "randomRange
should use both myMax
and myMin
, and return a random number in your range.",
- "testString": "assert((function(){if(code.match(/myMax/g).length > 1 && code.match(/myMin/g).length > 2 && code.match(/Math.floor/g) && code.match(/Math.random/g)){return true;}else{return false;}})(), 'randomRange
should use both myMax
and myMin
, and return a random number in your range.');"
+ "text":
+ "randomRange
should use both myMax
and myMin
, and return a random number in your range.",
+ "testString":
+ "assert((function(){if(code.match(/myMax/g).length > 1 && code.match(/myMin/g).length > 2 && code.match(/Math.floor/g) && code.match(/Math.random/g)){return true;}else{return false;}})(), 'randomRange
should use both myMax
and myMin
, and return a random number in your range.');"
}
],
"challengeType": 1,
@@ -7700,24 +8215,32 @@
"solutions": [],
"tests": [
{
- "text": "convertToInteger
should use the parseInt()
function",
- "testString": "assert(/parseInt/g.test(code), 'convertToInteger
should use the parseInt()
function');"
+ "text":
+ "convertToInteger
should use the parseInt()
function",
+ "testString":
+ "assert(/parseInt/g.test(code), 'convertToInteger
should use the parseInt()
function');"
},
{
- "text": "convertToInteger(\"56\")
should return a number",
- "testString": "assert(typeof(convertToInteger(\"56\")) === \"number\", 'convertToInteger(\"56\")
should return a number');"
+ "text":
+ "convertToInteger(\"56\")
should return a number",
+ "testString":
+ "assert(typeof(convertToInteger(\"56\")) === \"number\", 'convertToInteger(\"56\")
should return a number');"
},
{
"text": "convertToInteger(\"56\")
should return 56",
- "testString": "assert(convertToInteger(\"56\") === 56, 'convertToInteger(\"56\")
should return 56');"
+ "testString":
+ "assert(convertToInteger(\"56\") === 56, 'convertToInteger(\"56\")
should return 56');"
},
{
"text": "convertToInteger(\"77\")
should return 77",
- "testString": "assert(convertToInteger(\"77\") === 77, 'convertToInteger(\"77\")
should return 77');"
+ "testString":
+ "assert(convertToInteger(\"77\") === 77, 'convertToInteger(\"77\")
should return 77');"
},
{
- "text": "convertToInteger(\"JamesBond\")
should return NaN",
- "testString": "assert.isNaN(convertToInteger(\"JamesBond\"), 'convertToInteger(\"JamesBond\")
should return NaN');"
+ "text":
+ "convertToInteger(\"JamesBond\")
should return NaN",
+ "testString":
+ "assert.isNaN(convertToInteger(\"JamesBond\"), 'convertToInteger(\"JamesBond\")
should return NaN');"
}
],
"challengeType": 1,
@@ -7756,24 +8279,32 @@
"solutions": [],
"tests": [
{
- "text": "convertToInteger
should use the parseInt()
function",
- "testString": "assert(/parseInt/g.test(code), 'convertToInteger
should use the parseInt()
function');"
+ "text":
+ "convertToInteger
should use the parseInt()
function",
+ "testString":
+ "assert(/parseInt/g.test(code), 'convertToInteger
should use the parseInt()
function');"
},
{
- "text": "convertToInteger(\"10011\")
should return a number",
- "testString": "assert(typeof(convertToInteger(\"10011\")) === \"number\", 'convertToInteger(\"10011\")
should return a number');"
+ "text":
+ "convertToInteger(\"10011\")
should return a number",
+ "testString":
+ "assert(typeof(convertToInteger(\"10011\")) === \"number\", 'convertToInteger(\"10011\")
should return a number');"
},
{
"text": "convertToInteger(\"10011\")
should return 19",
- "testString": "assert(convertToInteger(\"10011\") === 19, 'convertToInteger(\"10011\")
should return 19');"
+ "testString":
+ "assert(convertToInteger(\"10011\") === 19, 'convertToInteger(\"10011\")
should return 19');"
},
{
"text": "convertToInteger(\"111001\")
should return 57",
- "testString": "assert(convertToInteger(\"111001\") === 57, 'convertToInteger(\"111001\")
should return 57');"
+ "testString":
+ "assert(convertToInteger(\"111001\") === 57, 'convertToInteger(\"111001\")
should return 57');"
},
{
- "text": "convertToInteger(\"JamesBond\")
should return NaN",
- "testString": "assert.isNaN(convertToInteger(\"JamesBond\"), 'convertToInteger(\"JamesBond\")
should return NaN');"
+ "text":
+ "convertToInteger(\"JamesBond\")
should return NaN",
+ "testString":
+ "assert.isNaN(convertToInteger(\"JamesBond\"), 'convertToInteger(\"JamesBond\")
should return NaN');"
}
],
"challengeType": 1,
@@ -7804,29 +8335,34 @@
"The syntax is:",
"condition ? statement-if-true : statement-if-false;
",
"The following function uses an if-else statement to check a condition:",
- "function findGreater(a, b) {
if(a > b) {
return \"a is greater\";
}
else {
return \"b is greater\";
}
}
",
+ "function findGreater(a, b) {
if(a > b) {
return \"a is greater\";
}
else {
return \"b is greater\";
}
}
",
"This can be re-written using the conditional operator
:",
- "function findGreater(a, b) {
return a > b ? \"a is greater\" : \"b is greater\";
}
",
+ "function findGreater(a, b) {
return a > b ? \"a is greater\" : \"b is greater\";
}
",
"
",
"Use the conditional operator
in the checkEqual
function to check if two numbers are equal or not. The function should return either true or false."
],
"solutions": [],
"tests": [
{
- "text": "checkEqual
should use the conditional operator
",
- "testString": "assert(/.+?\\s*?\\?\\s*?.+?\\s*?:\\s*?.+?/gi.test(code), 'checkEqual
should use the conditional operator
');"
+ "text":
+ "checkEqual
should use the conditional operator
",
+ "testString":
+ "assert(/.+?\\s*?\\?\\s*?.+?\\s*?:\\s*?.+?/gi.test(code), 'checkEqual
should use the conditional operator
');"
},
{
"text": "checkEqual(1, 2)
should return false",
- "testString": "assert(checkEqual(1, 2) === false, 'checkEqual(1, 2)
should return false');"
+ "testString":
+ "assert(checkEqual(1, 2) === false, 'checkEqual(1, 2)
should return false');"
},
{
"text": "checkEqual(1, 1)
should return true",
- "testString": "assert(checkEqual(1, 1) === true, 'checkEqual(1, 1)
should return true');"
+ "testString":
+ "assert(checkEqual(1, 1) === true, 'checkEqual(1, 1)
should return true');"
},
{
"text": "checkEqual(1, -1)
should return false",
- "testString": "assert(checkEqual(1, -1) === false, 'checkEqual(1, -1)
should return false');"
+ "testString":
+ "assert(checkEqual(1, -1) === false, 'checkEqual(1, -1)
should return false');"
}
],
"challengeType": 1,
@@ -7855,29 +8391,37 @@
"description": [
"In the previous challenge, you used a single conditional operator
. You can also chain them together to check for multiple conditions.",
"The following function uses if, else if, and else statements to check multiple conditions:",
- "function findGreaterOrEqual(a, b) {
if(a === b) {
return \"a and b are equal\";
}
else if(a > b) {
return \"a is greater\";
}
else {
return \"b is greater\";
}
}
",
+ "function findGreaterOrEqual(a, b) {
if(a === b) {
return \"a and b are equal\";
}
else if(a > b) {
return \"a is greater\";
}
else {
return \"b is greater\";
}
}
",
"The above function can be re-written using multiple conditional operators
:",
- "function findGreaterOrEqual(a, b) {
return (a === b) ? \"a and b are equal\" : (a > b) ? \"a is greater\" : \"b is greater\";
}
",
+ "function findGreaterOrEqual(a, b) {
return (a === b) ? \"a and b are equal\" : (a > b) ? \"a is greater\" : \"b is greater\";
}
",
"
",
"Use multiple conditional operators
in the checkSign
function to check if a number is positive, negative or zero."
],
"solutions": [],
"tests": [
{
- "text": "checkSign
should use multiple conditional operators
",
- "testString": "assert(/.+?\\s*?\\?\\s*?.+?\\s*?:\\s*?.+?\\s*?\\?\\s*?.+?\\s*?:\\s*?.+?/gi.test(code), 'checkSign
should use multiple conditional operators
');"
+ "text":
+ "checkSign
should use multiple conditional operators
",
+ "testString":
+ "assert(/.+?\\s*?\\?\\s*?.+?\\s*?:\\s*?.+?\\s*?\\?\\s*?.+?\\s*?:\\s*?.+?/gi.test(code), 'checkSign
should use multiple conditional operators
');"
},
{
- "text": "checkSign(10)
should return \"positive\". Note that capitalization matters",
- "testString": "assert(checkSign(10) === 'positive', 'checkSign(10)
should return \"positive\". Note that capitalization matters');"
+ "text":
+ "checkSign(10)
should return \"positive\". Note that capitalization matters",
+ "testString":
+ "assert(checkSign(10) === 'positive', 'checkSign(10)
should return \"positive\". Note that capitalization matters');"
},
{
- "text": "checkSign(-12)
should return \"negative\". Note that capitalization matters",
- "testString": "assert(checkSign(-12) === 'negative', 'checkSign(-12)
should return \"negative\". Note that capitalization matters');"
+ "text":
+ "checkSign(-12)
should return \"negative\". Note that capitalization matters",
+ "testString":
+ "assert(checkSign(-12) === 'negative', 'checkSign(-12)
should return \"negative\". Note that capitalization matters');"
},
{
- "text": "checkSign(0)
should return \"zero\". Note that capitalization matters",
- "testString": "assert(checkSign(0) === 'zero', 'checkSign(0)
should return \"zero\". Note that capitalization matters');"
+ "text":
+ "checkSign(0)
should return \"zero\". Note that capitalization matters",
+ "testString":
+ "assert(checkSign(0) === 'zero', 'checkSign(0)
should return \"zero\". Note that capitalization matters');"
}
],
"challengeType": 1,
diff --git a/challenges/02-javascript-algorithms-and-data-structures/es6.json b/challenges/02-javascript-algorithms-and-data-structures/es6.json
index 41707c022..ed0764dff 100644
--- a/challenges/02-javascript-algorithms-and-data-structures/es6.json
+++ b/challenges/02-javascript-algorithms-and-data-structures/es6.json
@@ -26,15 +26,19 @@
"tests": [
{
"text": "var
does not exist in code.",
- "testString": "getUserInput => assert(!getUserInput('index').match(/var/g),'var
does not exist in code.');"
+ "testString":
+ "getUserInput => assert(!getUserInput('index').match(/var/g),'var
does not exist in code.');"
},
{
"text": "catName
should be Oliver
.",
- "testString": "assert(catName === \"Oliver\", 'catName
should be Oliver
.');"
+ "testString":
+ "assert(catName === \"Oliver\", 'catName
should be Oliver
.');"
},
{
- "text": "quote
should be \"Oliver says Meow!\"
",
- "testString": "assert(quote === \"Oliver says Meow!\", 'quote
should be \"Oliver says Meow!\"
');"
+ "text":
+ "quote
should be \"Oliver says Meow!\"
",
+ "testString":
+ "assert(quote === \"Oliver says Meow!\", 'quote
should be \"Oliver says Meow!\"
');"
}
],
"releasedOn": "Feb 17, 2017",
@@ -69,13 +73,13 @@
"When you declare a variable with the var
keyword, it is declared globally, or locally if declared inside a function.",
"The let
keyword behaves similarly, but with some extra features. When you declare a variable with the let
keyword inside a block, statement, or expression, its scope is limited to that block, statement, or expression.",
"For example:",
- "var numArray = [];
for (var i = 0; i < 3; i++) {
numArray.push(i);
}
console.log(numArray);
// returns [0, 1, 2]
console.log(i);
// returns 3
",
+ "var numArray = [];
for (var i = 0; i < 3; i++) {
numArray.push(i);
}
console.log(numArray);
// returns [0, 1, 2]
console.log(i);
// returns 3
",
"With the var
keyword, i
is declared globally. So when i++
is executed, it updates the global variable. This code is similar to the following:",
- "var numArray = [];
var i;
for (i = 0; i < 3; i++) {
numArray.push(i);
}
console.log(numArray);
// returns [0, 1, 2]
console.log(i);
// returns 3
",
+ "var numArray = [];
var i;
for (i = 0; i < 3; i++) {
numArray.push(i);
}
console.log(numArray);
// returns [0, 1, 2]
console.log(i);
// returns 3
",
"This behavior will cause problems if you were to create a function and store it for later use inside a for loop that uses the i
variable. This is because the stored function will always refer to the value of the updated global i
variable.",
- "var printNumTwo;
for (var i = 0; i < 3; i++) {
if(i === 2){
printNumTwo = function() {
return i;
};
}
}
console.log(printNumTwo());
// returns 3
",
+ "var printNumTwo;
for (var i = 0; i < 3; i++) {
if(i === 2){
printNumTwo = function() {
return i;
};
}
}
console.log(printNumTwo());
// returns 3
",
"As you can see, printNumTwo()
prints 3 and not 2. This is because the value assigned to i
was updated and the printNumTwo()
returns the global i
and not the value i
had when the function was created in the for loop. The let
keyword does not follow this behavior:",
- "'use strict';
let printNumTwo;
for (let i = 0; i < 3; i++) {
if (i === 2) {
printNumTwo = function() {
return i;
};
}
}
console.log(printNumTwo());
// returns 2
console.log(i);
// returns \"i is not defined\"
",
+ "'use strict';
let printNumTwo;
for (let i = 0; i < 3; i++) {
if (i === 2) {
printNumTwo = function() {
return i;
};
}
}
console.log(printNumTwo());
// returns 2
console.log(i);
// returns \"i is not defined\"
",
"i
is not defined because it was not declared in the global scope. It is only declared within the for loop statement. printNumTwo()
returned the correct value because three different i
variables with unique values (0, 1, and 2) were created by the let
keyword within the loop statement.",
"
",
"Fix the code so that i
declared in the if statement is a separate variable than i
declared in the first line of the function. Be certain not to use the var
keyword anywhere in your code.",
@@ -84,15 +88,19 @@
"tests": [
{
"text": "var
does not exist in code.",
- "testString": "getUserInput => assert(!getUserInput('index').match(/var/g),'var
does not exist in code.');"
+ "testString":
+ "getUserInput => assert(!getUserInput('index').match(/var/g),'var
does not exist in code.');"
},
{
- "text": "The variable i
declared in the if statement should equal \"block scope\".",
- "testString": "getUserInput => assert(getUserInput('index').match(/(i\\s*=\\s*).*\\s*.*\\s*.*\\1('|\")block\\s*scope\\2/g), 'The variable i
declared in the if statement should equal \"block scope\".');"
+ "text":
+ "The variable i
declared in the if statement should equal \"block scope\".",
+ "testString":
+ "getUserInput => assert(getUserInput('index').match(/(i\\s*=\\s*).*\\s*.*\\s*.*\\1('|\")block\\s*scope\\2/g), 'The variable i
declared in the if statement should equal \"block scope\".');"
},
{
"text": "checkScope()
should return \"function scope\"",
- "testString": "assert(checkScope() === \"function scope\", 'checkScope()
should return \"function scope\"');"
+ "testString":
+ "assert(checkScope() === \"function scope\", 'checkScope()
should return \"function scope\"');"
}
],
"releasedOn": "Feb 17, 2017",
@@ -134,19 +142,25 @@
"tests": [
{
"text": "var
does not exist in your code.",
- "testString": "getUserInput => assert(!getUserInput('index').match(/var/g),'var
does not exist in your code.');"
+ "testString":
+ "getUserInput => assert(!getUserInput('index').match(/var/g),'var
does not exist in your code.');"
},
{
- "text": "SENTENCE
should be a constant variable declared with const
.",
- "testString": "getUserInput => assert(getUserInput('index').match(/(const SENTENCE)/g), 'SENTENCE
should be a constant variable declared with const
.');"
+ "text":
+ "SENTENCE
should be a constant variable declared with const
.",
+ "testString":
+ "getUserInput => assert(getUserInput('index').match(/(const SENTENCE)/g), 'SENTENCE
should be a constant variable declared with const
.');"
},
{
"text": "i
should be declared with let
.",
- "testString": "getUserInput => assert(getUserInput('index').match(/(let i)/g), 'i
should be declared with let
.');"
+ "testString":
+ "getUserInput => assert(getUserInput('index').match(/(let i)/g), 'i
should be declared with let
.');"
},
{
- "text": "console.log
should be changed to print the SENTENCE
variable.",
- "testString": "getUserInput => assert(getUserInput('index').match(/console.log/(/s*?SENTENCE/s*?/)/s*?;/g), 'console.log
should be adjusted to print the variable SENTENCE
.');"
+ "text":
+ "console.log
should be changed to print the SENTENCE
variable.",
+ "testString":
+ "getUserInput => assert(getUserInput('index').match(/console.log/(/s*?SENTENCE/s*?/)/s*?;/g), 'console.log
should be adjusted to print the variable SENTENCE
.');"
}
],
"releasedOn": "Feb 17, 2017",
@@ -193,19 +207,24 @@
"tests": [
{
"text": "Do not replace const
keyword.",
- "testString": "getUserInput => assert(getUserInput('index').match(/const/g), 'Do not replace const
keyword.');"
+ "testString":
+ "getUserInput => assert(getUserInput('index').match(/const/g), 'Do not replace const
keyword.');"
},
{
- "text": "s
should be a constant variable (by using const
).",
- "testString": "getUserInput => assert(getUserInput('index').match(/const\\s+s/g), 's
should be a constant variable (by using const
).');"
+ "text":
+ "s
should be a constant variable (by using const
).",
+ "testString":
+ "getUserInput => assert(getUserInput('index').match(/const\\s+s/g), 's
should be a constant variable (by using const
).');"
},
{
"text": "Do not change the original array declaration.",
- "testString": "getUserInput => assert(getUserInput('index').match(/const\\s+s\\s*=\\s*\\[\\s*5\\s*,\\s*7\\s*,\\s*2\\s*\\]\\s*;?/g), 'Do not change the original array declaration.');"
+ "testString":
+ "getUserInput => assert(getUserInput('index').match(/const\\s+s\\s*=\\s*\\[\\s*5\\s*,\\s*7\\s*,\\s*2\\s*\\]\\s*;?/g), 'Do not change the original array declaration.');"
},
{
"text": "s
should be equal to [2, 5, 7]
.",
- "testString": "assert.deepEqual(s, [2, 5, 7], 's
should be equal to [2, 5, 7]
.');"
+ "testString":
+ "assert.deepEqual(s, [2, 5, 7], 's
should be equal to [2, 5, 7]
.');"
}
],
"releasedOn": "Feb 17, 2017",
@@ -239,26 +258,31 @@
"description": [
"As seen in the previous challenge, const
declaration alone doesn't really protect your data from mutation. To ensure your data doesn't change, JavaScript provides a function Object.freeze
to prevent data mutation.",
"Once the object is frozen, you can no longer add, update, or delete properties from it. Any attempt at changing the object will be rejected without an error.",
- "
let obj = {
name:\"FreeCodeCamp\"
review:\"Awesome\"
};
Object.freeze(obj);
obj.review = \"bad\"; //will be ignored. Mutation not allowed
obj.newProp = \"Test\"; // will be ignored. Mutation not allowed
console.log(obj);
// { name: \"FreeCodeCamp\", review:\"Awesome\"}
",
+ "
let obj = {
name:\"FreeCodeCamp\"
review:\"Awesome\"
};
Object.freeze(obj);
obj.review = \"bad\"; //will be ignored. Mutation not allowed
obj.newProp = \"Test\"; // will be ignored. Mutation not allowed
console.log(obj);
// { name: \"FreeCodeCamp\", review:\"Awesome\"}
",
"
",
"In this challenge you are going to use Object.freeze
to prevent mathematical constants from changing. You need to freeze the MATH_CONSTANTS
object so that no one is able alter the value of PI
, add, or delete properties ."
],
"tests": [
{
"text": "Do not replace const
keyword.",
- "testString": "getUserInput => assert(getUserInput('index').match(/const/g), 'Do not replace const
keyword.');"
+ "testString":
+ "getUserInput => assert(getUserInput('index').match(/const/g), 'Do not replace const
keyword.');"
},
{
- "text": "MATH_CONSTANTS
should be a constant variable (by using const
).",
- "testString": "getUserInput => assert(getUserInput('index').match(/const\\s+MATH_CONSTANTS/g), 'MATH_CONSTANTS
should be a constant variable (by using const
).');"
+ "text":
+ "MATH_CONSTANTS
should be a constant variable (by using const
).",
+ "testString":
+ "getUserInput => assert(getUserInput('index').match(/const\\s+MATH_CONSTANTS/g), 'MATH_CONSTANTS
should be a constant variable (by using const
).');"
},
{
"text": "Do not change original MATH_CONSTANTS
.",
- "testString": "getUserInput => assert(getUserInput('index').match(/const\\s+MATH_CONSTANTS\\s+=\\s+{\\s+PI:\\s+3.14\\s+};/g), 'Do not change original MATH_CONSTANTS
.');"
+ "testString":
+ "getUserInput => assert(getUserInput('index').match(/const\\s+MATH_CONSTANTS\\s+=\\s+{\\s+PI:\\s+3.14\\s+};/g), 'Do not change original MATH_CONSTANTS
.');"
},
{
"text": "PI
equals 3.14
.",
- "testString": "assert(PI === 3.14, 'PI
equals 3.14
.');"
+ "testString":
+ "assert(PI === 3.14, 'PI
equals 3.14
.');"
}
],
"releasedOn": "Aug 12, 2017",
@@ -299,9 +323,9 @@
"description": [
"In JavaScript, we often don't need to name our functions, especially when passing a function as an argument to another function. Instead, we create inline functions. We don't need to name these functions because we do not reuse them anywhere else.",
"To achieve this, we often use the following syntax:",
- "const myFunc = function() {
const myVar = \"value\";
return myVar;
}
",
+ "const myFunc = function() {
const myVar = \"value\";
return myVar;
}
",
"ES6 provides us with the syntactic sugar to not have to write anonymous functions this way. Instead, you can use arrow function syntax:",
- "const myFunc = () => {
const myVar = \"value\";
return myVar;
}
",
+ "const myFunc = () => {
const myVar = \"value\";
return myVar;
}
",
"When there is no function body, and only a return value, arrow function syntax allows you to omit the keyword return
as well as the brackets surrounding the code. This helps simplify smaller functions into one-line statements:",
"const myFunc= () => \"value\"
",
"This code will still return value
by default.",
@@ -311,23 +335,29 @@
"tests": [
{
"text": "User did replace var
keyword.",
- "testString": "getUserInput => assert(!getUserInput('index').match(/var/g), 'User did replace var
keyword.');"
+ "testString":
+ "getUserInput => assert(!getUserInput('index').match(/var/g), 'User did replace var
keyword.');"
},
{
- "text": "magic
should be a constant variable (by using const
).",
- "testString": "getUserInput => assert(getUserInput('index').match(/const\\s+magic/g), 'magic
should be a constant variable (by using const
).');"
+ "text":
+ "magic
should be a constant variable (by using const
).",
+ "testString":
+ "getUserInput => assert(getUserInput('index').match(/const\\s+magic/g), 'magic
should be a constant variable (by using const
).');"
},
{
"text": "magic
is a function
.",
- "testString": "assert(typeof magic === 'function', 'magic
is a function
.');"
+ "testString":
+ "assert(typeof magic === 'function', 'magic
is a function
.');"
},
{
"text": "magic()
returns correct date.",
- "testString": "assert(magic().getDate() == new Date().getDate(), 'magic()
returns correct date.');"
+ "testString":
+ "assert(magic().getDate() == new Date().getDate(), 'magic()
returns correct date.');"
},
{
"text": "function
keyword was not used.",
- "testString": "getUserInput => assert(!getUserInput('index').match(/function/g), 'function
keyword was not used.');"
+ "testString":
+ "getUserInput => assert(!getUserInput('index').match(/function/g), 'function
keyword was not used.');"
}
],
"releasedOn": "Feb 17, 2017",
@@ -362,23 +392,30 @@
"tests": [
{
"text": "User did replace var
keyword.",
- "testString": "getUserInput => assert(!getUserInput('index').match(/var/g), 'User did replace var
keyword.');"
+ "testString":
+ "getUserInput => assert(!getUserInput('index').match(/var/g), 'User did replace var
keyword.');"
},
{
- "text": "myConcat
should be a constant variable (by using const
).",
- "testString": "getUserInput => assert(getUserInput('index').match(/const\\s+myConcat/g), 'myConcat
should be a constant variable (by using const
).');"
+ "text":
+ "myConcat
should be a constant variable (by using const
).",
+ "testString":
+ "getUserInput => assert(getUserInput('index').match(/const\\s+myConcat/g), 'myConcat
should be a constant variable (by using const
).');"
},
{
"text": "myConcat
should be a function",
- "testString": "assert(typeof myConcat === 'function', 'myConcat
should be a function');"
+ "testString":
+ "assert(typeof myConcat === 'function', 'myConcat
should be a function');"
},
{
- "text": "myConcat()
returns the correct array
",
- "testString": "assert(() => { const a = myConcat([1], [2]); return a[0] == 1 && a[1] == 2; }, 'myConcat()
returns the correct array
');"
+ "text":
+ "myConcat()
returns the correct array
",
+ "testString":
+ "assert(() => { const a = myConcat([1], [2]); return a[0] == 1 && a[1] == 2; }, 'myConcat()
returns the correct array
');"
},
{
"text": "function
keyword was not used.",
- "testString": "getUserInput => assert(!getUserInput('index').match(/function/g), 'function
keyword was not used.');"
+ "testString":
+ "getUserInput => assert(!getUserInput('index').match(/function/g), 'function
keyword was not used.');"
}
],
"releasedOn": "Feb 17, 2017",
@@ -409,7 +446,7 @@
"It's time we see how powerful arrow functions are when processing data.",
"Arrow functions work really well with higher order functions, such as map()
, filter()
, and reduce()
, that take other functions as arguments for processing collections of data.",
"Read the following code:",
- "FBPosts.filter(function(post) {
return post.thumbnail !== null && post.shares > 100 && post.likes > 500;
})
",
+ "FBPosts.filter(function(post) {
return post.thumbnail !== null && post.shares > 100 && post.likes > 500;
})
",
"We have written this with filter()
to at least make it somewhat readable. Now compare it to the following code which uses arrow function syntax instead:",
"FBPosts.filter((post) => post.thumbnail !== null && post.shares > 100 && post.likes > 500)
",
"This code is more succinct and accomplishes the same task with fewer lines of code.",
@@ -419,31 +456,42 @@
"tests": [
{
"text": "User did replace var
keyword.",
- "testString": "getUserInput => assert(!getUserInput('index').match(/var/g), 'User did replace var
keyword.');"
+ "testString":
+ "getUserInput => assert(!getUserInput('index').match(/var/g), 'User did replace var
keyword.');"
},
{
- "text": "squaredIntegers
should be a constant variable (by using const
).",
- "testString": "getUserInput => assert(getUserInput('index').match(/const\\s+squaredIntegers/g), 'squaredIntegers
should be a constant variable (by using const
).');"
+ "text":
+ "squaredIntegers
should be a constant variable (by using const
).",
+ "testString":
+ "getUserInput => assert(getUserInput('index').match(/const\\s+squaredIntegers/g), 'squaredIntegers
should be a constant variable (by using const
).');"
},
{
- "text": "squaredIntegers
should be an array
",
- "testString": "assert(Array.isArray(squaredIntegers), 'squaredIntegers
should be an array
');"
+ "text":
+ "squaredIntegers
should be an array
",
+ "testString":
+ "assert(Array.isArray(squaredIntegers), 'squaredIntegers
should be an array
');"
},
{
- "text": "squaredIntegers
should be [16, 1764, 36]
",
- "testString": "assert(squaredIntegers[0] === 16 && squaredIntegers[1] === 1764 && squaredIntegers[2] === 36, 'squaredIntegers
should be [16, 1764, 36]
');"
+ "text":
+ "squaredIntegers
should be [16, 1764, 36]
",
+ "testString":
+ "assert(squaredIntegers[0] === 16 && squaredIntegers[1] === 1764 && squaredIntegers[2] === 36, 'squaredIntegers
should be [16, 1764, 36]
');"
},
{
"text": "function
keyword was not used.",
- "testString": "getUserInput => assert(!getUserInput('index').match(/function/g), 'function
keyword was not used.');"
+ "testString":
+ "getUserInput => assert(!getUserInput('index').match(/function/g), 'function
keyword was not used.');"
},
{
"text": "loop should not be used",
- "testString": "getUserInput => assert(!getUserInput('index').match(/(for)|(while)/g), 'loop should not be used');"
+ "testString":
+ "getUserInput => assert(!getUserInput('index').match(/(for)|(while)/g), 'loop should not be used');"
},
{
- "text": "map
, filter
, or reduce
should be used",
- "testString": "getUserInput => assert(getUserInput('index').match(/map|filter|reduce/g), 'map
, filter
, or reduce
should be used');"
+ "text":
+ "map
, filter
, or reduce
should be used",
+ "testString":
+ "getUserInput => assert(getUserInput('index').match(/map|filter|reduce/g), 'map
, filter
, or reduce
should be used');"
}
],
"releasedOn": "Feb 17, 2017",
@@ -478,23 +526,29 @@
"description": [
"In order to help us create more flexible functions, ES6 introduces default parameters for functions.",
"Check out this code:",
- "function greeting(name = \"Anonymous\") {
return \"Hello \" + name;
}
console.log(greeting(\"John\")); // Hello John
console.log(greeting()); // Hello Anonymous
",
+ "function greeting(name = \"Anonymous\") {
return \"Hello \" + name;
}
console.log(greeting(\"John\")); // Hello John
console.log(greeting()); // Hello Anonymous
",
"The default parameter kicks in when the argument is not specified (it is undefined). As you can see in the example above, the parameter name
will receive its default value \"Anonymous\"
when you do not provide a value for the parameter. You can add default values for as many parameters as you want.",
"
",
"Modify the function increment
by adding default parameters so that it will add 1 to number
if value
is not specified."
],
"tests": [
{
- "text": "The result of increment(5, 2)
should be 7
.",
- "testString": "assert(increment(5, 2) === 7, 'The result of increment(5, 2)
should be 7
.');"
+ "text":
+ "The result of increment(5, 2)
should be 7
.",
+ "testString":
+ "assert(increment(5, 2) === 7, 'The result of increment(5, 2)
should be 7
.');"
},
{
- "text": "The result of increment(5)
should be 6
.",
- "testString": "assert(increment(5) === 6, 'The result of increment(5)
should be 6
.');"
+ "text":
+ "The result of increment(5)
should be 6
.",
+ "testString":
+ "assert(increment(5) === 6, 'The result of increment(5)
should be 6
.');"
},
{
- "text": "default parameter 1
was used for value
.",
- "testString": "getUserInput => assert(getUserInput('index').match(/value\\s*=\\s*1/g), 'default parameter 1
was used for value
.');"
+ "text":
+ "default parameter 1
was used for value
.",
+ "testString":
+ "getUserInput => assert(getUserInput('index').match(/value\\s*=\\s*1/g), 'default parameter 1
was used for value
.');"
}
],
"releasedOn": "Feb 17, 2017",
@@ -526,7 +580,7 @@
"description": [
"In order to help us create more flexible functions, ES6 introduces the rest operator for function parameters. With the rest operator, you can create functions that take a variable number of arguments. These arguments are stored in an array that can be accessed later from inside the function.",
"Check out this code:",
- "function howMany(...args) {
return \"You have passed \" + args.length + \" arguments.\";
}
console.log(howMany(0, 1, 2)); // You have passed 3 arguments
console.log(howMany(\"string\", null, [1, 2, 3], { })); // You have passed 4 arguments.
",
+ "function howMany(...args) {
return \"You have passed \" + args.length + \" arguments.\";
}
console.log(howMany(0, 1, 2)); // You have passed 3 arguments
console.log(howMany(\"string\", null, [1, 2, 3], { })); // You have passed 4 arguments.
",
"The rest operator eliminates the need to check the args
array and allows us to apply map()
, filter()
and reduce()
on the parameters array.",
"
",
"Modify the function sum
so that it uses the rest operator and it works in the same way with any number of parameters."
@@ -534,23 +588,29 @@
"tests": [
{
"text": "The result of sum(0,1,2)
should be 3",
- "testString": "assert(sum(0,1,2) === 3, 'The result of sum(0,1,2)
should be 3');"
+ "testString":
+ "assert(sum(0,1,2) === 3, 'The result of sum(0,1,2)
should be 3');"
},
{
"text": "The result of sum(1,2,3,4)
should be 10",
- "testString": "assert(sum(1,2,3,4) === 10, 'The result of sum(1,2,3,4)
should be 10');"
+ "testString":
+ "assert(sum(1,2,3,4) === 10, 'The result of sum(1,2,3,4)
should be 10');"
},
{
"text": "The result of sum(5)
should be 5",
- "testString": "assert(sum(5) === 5, 'The result of sum(5)
should be 5');"
+ "testString":
+ "assert(sum(5) === 5, 'The result of sum(5)
should be 5');"
},
{
"text": "The result of sum()
should be 0",
- "testString": "assert(sum() === 0, 'The result of sum()
should be 0');"
+ "testString":
+ "assert(sum() === 0, 'The result of sum()
should be 0');"
},
{
- "text": "The sum
function uses the ...
spread operator on the args
parameter.",
- "testString": "getUserInput => assert(getUserInput('index').match(/function\\s+sum\\s*\\(\\s*...args\\s*\\)\\s*{/g), 'The sum
function uses the ...
spread operator on the args
parameter.');"
+ "text":
+ "The sum
function uses the ...
spread operator on the args
parameter.",
+ "testString":
+ "getUserInput => assert(getUserInput('index').match(/function\\s+sum\\s*\\(\\s*...args\\s*\\)\\s*{/g), 'The sum
function uses the ...
spread operator on the args
parameter.');"
}
],
"releasedOn": "Feb 17, 2017",
@@ -595,15 +655,20 @@
"tests": [
{
"text": "arr2
is correct copy of arr1
.",
- "testString": "assert(arr2.every((v, i) => v === arr1[i]), 'arr2
is correct copy of arr1
.');"
+ "testString":
+ "assert(arr2.every((v, i) => v === arr1[i]), 'arr2
is correct copy of arr1
.');"
},
{
- "text": "...
spread operator was used to duplicate arr1
.",
- "testString": "getUserInput => assert(getUserInput('index').match(/\\[\\s*...arr1\\s*\\]/g),'...
spread operator was used to duplicate arr1
.');"
+ "text":
+ "...
spread operator was used to duplicate arr1
.",
+ "testString":
+ "getUserInput => assert(getUserInput('index').match(/\\[\\s*...arr1\\s*\\]/g),'...
spread operator was used to duplicate arr1
.');"
},
{
- "text": "arr2
remains unchanged when arr1
is changed.",
- "testString": "assert((arr1, arr2) => {arr1.push('JUN'); return arr2.length < arr1.length},'arr2
remains unchanged when arr1
is changed.');"
+ "text":
+ "arr2
remains unchanged when arr1
is changed.",
+ "testString":
+ "assert((arr1, arr2) => {arr1.push('JUN'); return arr2.length < arr1.length},'arr2
remains unchanged when arr1
is changed.');"
}
],
"releasedOn": "Feb 17, 2017",
@@ -647,15 +712,19 @@
"tests": [
{
"text": "the function getLength()
returns a number.",
- "testString": "assert(typeof getLength('') === 'number', 'the function getLength()
returns a number.');"
+ "testString":
+ "assert(typeof getLength('') === 'number', 'the function getLength()
returns a number.');"
},
{
- "text": "getLength(\"FreeCodeCamp\")
should be 12
",
- "testString": "assert(getLength(\"FreeCodeCamp\") === 12, 'getLength(\"FreeCodeCamp\")
should be 12
');"
+ "text":
+ "getLength(\"FreeCodeCamp\")
should be 12
",
+ "testString":
+ "assert(getLength(\"FreeCodeCamp\") === 12, 'getLength(\"FreeCodeCamp\")
should be 12
');"
},
{
"text": "destructuring with reassignment was used",
- "testString": "getUserInput => assert(getUserInput('index').match(/\\{\\s*length\\s*:\\s*len\\s*}\\s*=\\s*str/g),'destructuring with reassignment was used');"
+ "testString":
+ "getUserInput => assert(getUserInput('index').match(/\\{\\s*length\\s*:\\s*len\\s*}\\s*=\\s*str/g),'destructuring with reassignment was used');"
}
],
"releasedOn": "Feb 17, 2017",
@@ -687,11 +756,12 @@
},
{
"id": "587d7b89367417b2b2512b4a",
- "title": "Use Destructuring Assignment to Assign Variables from Nested Objects",
+ "title":
+ "Use Destructuring Assignment to Assign Variables from Nested Objects",
"description": [
"We can similarly destructure nested objects into variables.",
"Consider the following code:",
- "const a = {
start: { x: 5, y: 6},
end: { x: 6, y: -9 }
};
const { start : { x: startX, y: startY }} = a;
console.log(startX, startY); // 5, 6
",
+ "const a = {
start: { x: 5, y: 6},
end: { x: 6, y: -9 }
};
const { start : { x: startX, y: startY }} = a;
console.log(startX, startY); // 5, 6
",
"In the example above, the variable start
is assigned the value of a.start
, which is also an object.",
"
",
"Use destructuring assignment to obtain max
of forecast.tomorrow
and assign it to maxOfTomorrow
."
@@ -699,11 +769,13 @@
"tests": [
{
"text": "maxOfTomorrow
equals 84.6
",
- "testString": "assert(getMaxOfTmrw(LOCAL_FORECAST) === 84.6, 'maxOfTomorrow
equals 84.6
');"
+ "testString":
+ "assert(getMaxOfTmrw(LOCAL_FORECAST) === 84.6, 'maxOfTomorrow
equals 84.6
');"
},
{
"text": "nested destructuring was used",
- "testString": "getUserInput => assert(getUserInput('index').match(/\\{\\s*tomorrow\\s*:\\s*\\{\\s*max\\s*:\\s*maxOfTomorrow\\s*\\}\\s*\\}\\s*=\\s*forecast/g),'nested destructuring was used');"
+ "testString":
+ "getUserInput => assert(getUserInput('index').match(/\\{\\s*tomorrow\\s*:\\s*\\{\\s*max\\s*:\\s*maxOfTomorrow\\s*\\}\\s*\\}\\s*=\\s*forecast/g),'nested destructuring was used');"
}
],
"releasedOn": "Feb 17, 2017",
@@ -752,15 +824,18 @@
"tests": [
{
"text": "Value of a
should be 6, after swapping.",
- "testString": "assert(a === 6, 'Value of a
should be 6, after swapping.');"
+ "testString":
+ "assert(a === 6, 'Value of a
should be 6, after swapping.');"
},
{
"text": "Value of b
should be 8, after swapping.",
- "testString": "assert(b === 8, 'Value of b
should be 8, after swapping.');"
+ "testString":
+ "assert(b === 8, 'Value of b
should be 8, after swapping.');"
},
{
"text": "Use array destructuring to swap a and b.",
- "testString": "// assert(/\\[\\s*(\\w)\\s*,\\s*(\\w)\\s*\\]\\s*=\\s*\\[\\s*\\2\\s*,\\s*\\1\\s*\\]/g.test(code), 'Use array destructuring to swap a and b.');"
+ "testString":
+ "// assert(/\\[\\s*(\\w)\\s*,\\s*(\\w)\\s*\\]\\s*=\\s*\\[\\s*\\2\\s*,\\s*\\1\\s*\\]/g.test(code), 'Use array destructuring to swap a and b.');"
}
],
"releasedOn": "Feb 17, 2017",
@@ -789,7 +864,8 @@
},
{
"id": "587d7b8a367417b2b2512b4c",
- "title": "Use Destructuring Assignment with the Rest Operator to Reassign Array Elements",
+ "title":
+ "Use Destructuring Assignment with the Rest Operator to Reassign Array Elements",
"description": [
"In some situations involving array destructuring, we might want to collect the rest of the elements into a separate array.",
"The result is similar to Array.prototype.slice()
, as shown below:",
@@ -802,15 +878,18 @@
"tests": [
{
"text": "arr
should be [3,4,5,6,7,8,9,10]
",
- "testString": "assert(arr.every((v, i) => v === i + 3),'arr
should be [3,4,5,6,7,8,9,10]
');"
+ "testString":
+ "assert(arr.every((v, i) => v === i + 3),'arr
should be [3,4,5,6,7,8,9,10]
');"
},
{
"text": "destructuring was used.",
- "testString": "getUserInput => assert(getUserInput('index').match(/\\[\\s*\\w*\\s*,\\s*\\w*\\s*,\\s*...arr\\s*\\]/g),'destructuring was used.');"
+ "testString":
+ "getUserInput => assert(getUserInput('index').match(/\\[\\s*\\w*\\s*,\\s*\\w*\\s*,\\s*...arr\\s*\\]/g),'destructuring was used.');"
},
{
"text": "Array.slice()
was not used.",
- "testString": "getUserInput => assert(!getUserInput('index').match(/Array.slice/g), 'Array.slice()
was not used.');"
+ "testString":
+ "getUserInput => assert(!getUserInput('index').match(/Array.slice/g), 'Array.slice()
was not used.');"
}
],
"releasedOn": "Feb 17, 2017",
@@ -841,13 +920,14 @@
},
{
"id": "587d7b8a367417b2b2512b4d",
- "title": "Use Destructuring Assignment to Pass an Object as a Function's Parameters",
+ "title":
+ "Use Destructuring Assignment to Pass an Object as a Function's Parameters",
"description": [
"In some cases, you can destructure the object in a function argument itself.",
"Consider the code below:",
- "const profileUpdate = (profileData) => {
const { name, age, nationality, location } = profileData;
// do something with these variables
}
",
+ "const profileUpdate = (profileData) => {
const { name, age, nationality, location } = profileData;
// do something with these variables
}
",
"This effectively destructures the object sent into the function. This can also be done in-place:",
- "const profileUpdate = ({ name, age, nationality, location }) => {
/* do something with these fields */
}
",
+ "const profileUpdate = ({ name, age, nationality, location }) => {
/* do something with these fields */
}
",
"This removes some extra lines and makes our code look neat.",
"This has the added benefit of not having to manipulate an entire object in a function; only the fields that are needed are copied inside the function.",
"
",
@@ -856,15 +936,18 @@
"tests": [
{
"text": "stats
should be an object
.",
- "testString": "assert(typeof stats === 'object', 'stats
should be an object
.');"
+ "testString":
+ "assert(typeof stats === 'object', 'stats
should be an object
.');"
},
{
"text": "half(stats)
should be 28.015
",
- "testString": "assert(half(stats) === 28.015, 'half(stats)
should be 28.015
');"
+ "testString":
+ "assert(half(stats) === 28.015, 'half(stats)
should be 28.015
');"
},
{
"text": "Destructuring was used.",
- "testString": "getUserInput => assert(getUserInput('index').match(/\\(\\s*\\{\\s*\\w+\\s*,\\s*\\w+\\s*\\}\\s*\\)/g), 'Destructuring was used.');"
+ "testString":
+ "getUserInput => assert(getUserInput('index').match(/\\(\\s*\\{\\s*\\w+\\s*,\\s*\\w+\\s*\\}\\s*\\)/g), 'Destructuring was used.');"
}
],
"releasedOn": "Feb 17, 2017",
@@ -909,7 +992,7 @@
"description": [
"A new feature of ES6 is the template literal. This is a special type of string that allows you to use string interpolation features to create strings.",
"Consider the code below:",
- "const person = {
name: \"Zodiac Hasbro\",
age: 56
};
// string interpolation
const greeting = `Hello, my name is ${person.name}!
I am ${person.age} years old.`;
console.log(greeting); // prints
// Hello, my name is Zodiac Hasbro!
// I am 56 years old.
",
+ "const person = {
name: \"Zodiac Hasbro\",
age: 56
};
// string interpolation
const greeting = `Hello, my name is ${person.name}!
I am ${person.age} years old.`;
console.log(greeting); // prints
// Hello, my name is Zodiac Hasbro!
// I am 56 years old.
",
"A lot of things happened there.",
"Firstly, the ${variable}
syntax used above is a place holder. Basically, you won't have to use concatenation with the +
operator anymore. To add variables to strings, you just drop the variable in a template string and wrap it with ${
and }
.",
"Secondly, the example uses backticks (`
), not quotes ('
or \"
), to wrap the string. Notice that the string is multi-line.",
@@ -919,16 +1002,20 @@
],
"tests": [
{
- "text": "resultDisplayArray
is a list containing result failure
messages.",
- "testString": "assert(typeof makeList(result.failure) === 'object' && resultDisplayArray.length === 3, 'resultDisplayArray
is a list containing result failure
messages.');"
+ "text":
+ "resultDisplayArray
is a list containing result failure
messages.",
+ "testString":
+ "assert(typeof makeList(result.failure) === 'object' && resultDisplayArray.length === 3, 'resultDisplayArray
is a list containing result failure
messages.');"
},
{
"text": "resultDisplayArray
is the desired output.",
- "testString": "assert(makeList(result.failure).every((v, i) => v === `${result.failure[i]}`), 'resultDisplayArray
is the desired output.');"
+ "testString":
+ "assert(makeList(result.failure).every((v, i) => v === `${result.failure[i]}`), 'resultDisplayArray
is the desired output.');"
},
{
"text": "Template strings were used",
- "testString": "getUserInput => assert(getUserInput('index').match(/\\`\\$\\{\\w+\\}<\\/li>\\`/g), 'Template strings were used');"
+ "testString":
+ "getUserInput => assert(getUserInput('index').match(/\\`\\$\\{\\w+\\}<\\/li>\\`/g), 'Template strings were used');"
}
],
"releasedOn": "Feb 17, 2017",
@@ -973,7 +1060,7 @@
"description": [
"ES6 adds some nice support for easily defining object literals.",
"Consider the following code:",
- "const getMousePosition = (x, y) => ({
x: x,
y: y
});
",
+ "const getMousePosition = (x, y) => ({
x: x,
y: y
});
",
"getMousePosition
is a simple function that returns an object containing two fields.",
"ES6 provides the syntactic sugar to eliminate the redundancy of having to write x: x
. You can simply write x
once, and it will be converted tox: x
(or something equivalent) under the hood.",
"Here is the same function from above rewritten to use this new syntax:",
@@ -983,12 +1070,15 @@
],
"tests": [
{
- "text": "the output is {name: \"Zodiac Hasbro\", age: 56, gender: \"male\"}
.",
- "testString": "assert(() => {const res={name:\"Zodiac Hasbro\",age:56,gender:\"male\"}; const person=createPerson(\"Zodiac Hasbro\", 56, \"male\"); return Object.keys(person).every(k => person[k] === res[k]);}, 'the output is {name: \"Zodiac Hasbro\", age: 56, gender: \"male\"}
.');"
+ "text":
+ "the output is {name: \"Zodiac Hasbro\", age: 56, gender: \"male\"}
.",
+ "testString":
+ "assert(() => {const res={name:\"Zodiac Hasbro\",age:56,gender:\"male\"}; const person=createPerson(\"Zodiac Hasbro\", 56, \"male\"); return Object.keys(person).every(k => person[k] === res[k]);}, 'the output is {name: \"Zodiac Hasbro\", age: 56, gender: \"male\"}
.');"
},
{
"text": "No :
were used.",
- "testString": "getUserInput => assert(!getUserInput('index').match(/:/g), 'No :
were used.');"
+ "testString":
+ "getUserInput => assert(!getUserInput('index').match(/:/g), 'No :
were used.');"
}
],
"releasedOn": "Feb 17, 2017",
@@ -1022,20 +1112,23 @@
"title": "Write Concise Declarative Functions with ES6",
"description": [
"When defining functions within objects in ES5, we have to use the keyword function
as follows:",
- "const person = {
name: \"Taylor\",
sayHello: function() {
return `Hello! My name is ${this.name}.`;
}
};
",
+ "const person = {
name: \"Taylor\",
sayHello: function() {
return `Hello! My name is ${this.name}.`;
}
};
",
"With ES6, You can remove the function
keyword and colon altogether when defining functions in objects. Here's an example of this syntax:",
- "const person = {
name: \"Taylor\",
sayHello() {
return `Hello! My name is ${this.name}.`;
}
};
",
+ "const person = {
name: \"Taylor\",
sayHello() {
return `Hello! My name is ${this.name}.`;
}
};
",
"
",
"Refactor the function setGear
inside the object bicycle
to use the shorthand syntax described above."
],
"tests": [
{
- "text": "setGear
is a function and changes the gear
variable.",
- "testString": "assert(() => { bicycle.setGear(48); return bicycle.gear === 48 }, 'setGear
is a function and changes the gear
variable.');"
+ "text":
+ "setGear
is a function and changes the gear
variable.",
+ "testString":
+ "assert(() => { bicycle.setGear(48); return bicycle.gear === 48 }, 'setGear
is a function and changes the gear
variable.');"
},
{
"text": "Declarative function was used.",
- "testString": "getUserInput => assert(!getUserInput('index').match(/:\\s*function\\s*\\(\\)/g), 'Declarative function was used.');"
+ "testString":
+ "getUserInput => assert(!getUserInput('index').match(/:\\s*function\\s*\\(\\)/g), 'Declarative function was used.');"
}
],
"releasedOn": "Feb 17, 2017",
@@ -1071,9 +1164,9 @@
"ES6 provides a new syntax to help create objects, using the keyword class.",
"This is to be noted, that the class
syntax is just a syntax, and not a full-fledged class based implementation of object oriented paradigm, unlike in languages like Java, or Python, or Ruby etc.",
"In ES5, we usually define a constructor function, and use the new
keyword to instantiate an object.",
- "var SpaceShuttle = function(targetPlanet){
this.targetPlanet = targetPlanet;
}
var zeus = new spaceShuttle('Jupiter');
",
+ "var SpaceShuttle = function(targetPlanet){
this.targetPlanet = targetPlanet;
}
var zeus = new SpaceShuttle('Jupiter');
",
"The class syntax simply replaces the constructor function creation:",
- "class SpaceShuttle {
constructor(targetPlanet){
this.targetPlanet = targetPlanet;
}
}
const zeus = new spaceShuttle('Jupiter');
",
+ "class SpaceShuttle {
constructor(targetPlanet){
this.targetPlanet = targetPlanet;
}
}
const zeus = new SpaceShuttle('Jupiter');
",
"Notice that the class
keyword declares a new function, and a constructor was added, which would be invoked when new
is called - to create a new object.",
"
",
"Use class
keyword and write a proper constructor to create the Vegetable
class.",
@@ -1081,16 +1174,20 @@
],
"tests": [
{
- "text": "Vegetable
should be a class
with a defined constructor
method.",
- "testString": "assert(typeof Vegetable === 'function' && typeof Vegetable.constructor === 'function', 'Vegetable
should be a class
with a defined constructor
method.');"
+ "text":
+ "Vegetable
should be a class
with a defined constructor
method.",
+ "testString":
+ "assert(typeof Vegetable === 'function' && typeof Vegetable.constructor === 'function', 'Vegetable
should be a class
with a defined constructor
method.');"
},
{
"text": "class
keyword was used.",
- "testString": "getUserInput => assert(getUserInput('index').match(/class/g),'class
keyword was used.');"
+ "testString":
+ "getUserInput => assert(getUserInput('index').match(/class/g),'class
keyword was used.');"
},
{
"text": "Vegetable
can be instantiated.",
- "testString": "assert(() => {const a = new Vegetable(\"apple\"); return typeof a === 'object';},'Vegetable
can be instantiated.');"
+ "testString":
+ "assert(() => {const a = new Vegetable(\"apple\"); return typeof a === 'object';},'Vegetable
can be instantiated.');"
}
],
"releasedOn": "Feb 17, 2017",
@@ -1126,7 +1223,7 @@
"These are classically called getters and setters.",
"Getter functions are meant to simply return (get) the value of an object's private variable to the user without the user directly accessing the private variable.",
"Setter functions are meant to modify (set) the value of an object's private variable based on the value passed into the setter function. This change could involve calculations, or even overwriting the previous value completely.",
- "class Book {
constructor(author) {
this._author = author;
}
// getter
get writer(){
return this._author;
}
// setter
set writer(updatedAuthor){
this._author = updatedAuthor;
}
}
const lol = new Book('anonymous');
console.log(lol.writer);
lol.writer = 'wut';
console.log(lol.writer);
",
+ "class Book {
constructor(author) {
this._author = author;
}
// getter
get writer(){
return this._author;
}
// setter
set writer(updatedAuthor){
this._author = updatedAuthor;
}
}
const lol = new Book('anonymous');
console.log(lol.writer);
lol.writer = 'wut';
console.log(lol.writer);
",
"Notice the syntax we are using to invoke the getter and setter - as if they are not even functions.",
"Getters and setters are important, because they hide internal implementation details.",
"
",
@@ -1140,16 +1237,20 @@
],
"tests": [
{
- "text": "Thermostat
should be a class
with a defined constructor
method.",
- "testString": "assert(typeof Thermostat === 'function' && typeof Thermostat.constructor === 'function','Thermostat
should be a class
with a defined constructor
method.');"
+ "text":
+ "Thermostat
should be a class
with a defined constructor
method.",
+ "testString":
+ "assert(typeof Thermostat === 'function' && typeof Thermostat.constructor === 'function','Thermostat
should be a class
with a defined constructor
method.');"
},
{
"text": "class
keyword was used.",
- "testString": "getUserInput => assert(getUserInput('index').match(/class/g),'class
keyword was used.');"
+ "testString":
+ "getUserInput => assert(getUserInput('index').match(/class/g),'class
keyword was used.');"
},
{
"text": "Thermostat
can be instantiated.",
- "testString": "assert(() => {const t = new Thermostat(32); return typeof t === 'object' && t.temperature === 0;}, 'Thermostat
can be instantiated.');"
+ "testString":
+ "assert(() => {const t = new Thermostat(32); return typeof t === 'object' && t.temperature === 0;}, 'Thermostat
can be instantiated.');"
}
],
"releasedOn": "Feb 17, 2017",
@@ -1199,7 +1300,8 @@
"tests": [
{
"text": "valid import
statement",
- "testString": "getUserInput => assert(getUserInput('index').match(/import\\s+\\{\\s?capitalizeString\\s?\\}\\s+from\\s+\"string_functions\"/g), 'valid import
statement');"
+ "testString":
+ "getUserInput => assert(getUserInput('index').match(/import\\s+\\{\\s?capitalizeString\\s?\\}\\s+from\\s+\"string_functions\"/g), 'valid import
statement');"
}
],
"releasedOn": "Feb 17, 2017",
@@ -1210,10 +1312,7 @@
"key": "indexjs",
"ext": "js",
"name": "index",
- "contents": [
- "\"use strict\";",
- "capitalizeString(\"hello!\");"
- ],
+ "contents": ["\"use strict\";", "capitalizeString(\"hello!\");"],
"head": [
"window.require = function (str) {",
"if (str === 'string_functions') {",
@@ -1231,9 +1330,9 @@
"description": [
"In the previous challenge, you learned about import
and how it can be leveraged to import small amounts of code from large files. In order for this to work, though, we must utilize one of the statements that goes with import
, known as export. When we want some code - a function, or a variable - to be usable in another file, we must export it in order to import it into another file. Like import
, export
is a non-browser feature.",
"The following is what we refer to as a named export. With this, we can import any code we export into another file with the import
syntax you learned in the last lesson. Here's an example:",
- "const capitalizeString = (string) => {
return string.charAt(0).toUpperCase() + string.slice(1);
}
export { capitalizeString } //How to export functions.
export const foo = \"bar\"; //How to export variables.
",
+ "const capitalizeString = (string) => {
return string.charAt(0).toUpperCase() + string.slice(1);
}
export { capitalizeString } //How to export functions.
export const foo = \"bar\"; //How to export variables.
",
"Alternatively, if you would like to compact all your export
statements into one line, you can take this approach:",
- "const capitalizeString = (string) => {
return string.charAt(0).toUpperCase() + string.slice(1);
}
const foo = \"bar\";
export { capitalizeString, foo }
",
+ "const capitalizeString = (string) => {
return string.charAt(0).toUpperCase() + string.slice(1);
}
const foo = \"bar\";
export { capitalizeString, foo }
",
"Either approach is perfectly acceptable.",
"
",
"Below are two variables that I want to make available for other files to use. Utilizing the first way I demonstrated export
, export the two variables."
@@ -1241,11 +1340,13 @@
"tests": [
{
"text": "foo
is exported.",
- "testString": "getUserInput => assert(getUserInput('index').match(/export\\s+const\\s+foo\\s+=+\\s\"bar\"/g), 'foo
is exported.');"
+ "testString":
+ "getUserInput => assert(getUserInput('index').match(/export\\s+const\\s+foo\\s+=+\\s\"bar\"/g), 'foo
is exported.');"
},
{
"text": "bar
is exported.",
- "testString": "getUserInput => assert(getUserInput('index').match(/export\\s+const\\s+bar\\s+=+\\s\"foo\"/g), 'bar
is exported.');"
+ "testString":
+ "getUserInput => assert(getUserInput('index').match(/export\\s+const\\s+bar\\s+=+\\s\"foo\"/g), 'bar
is exported.');"
}
],
"releasedOn": "Feb 17, 2017",
@@ -1261,9 +1362,7 @@
"const foo = \"bar\";",
"const bar= \"foo\";"
],
- "head": [
- "window.exports = function(){};"
- ],
+ "head": ["window.exports = function(){};"],
"tail": []
}
}
@@ -1284,7 +1383,8 @@
"tests": [
{
"text": "Properly uses import * as
syntax.",
- "testString": "assert(code.match(/import\\s+\\*\\s+as\\s+[a-zA-Z0-9_$]+\\s+from\\s*\"\\s*capitalize_strings\\s*\"\\s*;/gi), 'Properly uses import * as
syntax.');"
+ "testString":
+ "assert(code.match(/import\\s+\\*\\s+as\\s+[a-zA-Z0-9_$]+\\s+from\\s*\"\\s*capitalize_strings\\s*\"\\s*;/gi), 'Properly uses import * as
syntax.');"
}
],
"releasedOn": "Feb 17, 2017",
@@ -1295,9 +1395,7 @@
"key": "indexjs",
"ext": "js",
"name": "index",
- "contents": [
- "\"use strict\";"
- ],
+ "contents": ["\"use strict\";"],
"head": [
"window.require = function(str) {",
"if (str === 'capitalize_strings') {",
@@ -1317,7 +1415,7 @@
"In the export
lesson, you learned about the syntax referred to as a named export. This allowed you to make multiple functions and variables available for use in other files.",
"There is another export
syntax you need to know, known as export default. Usually you will use this syntax if only one value is being exported from a file. It is also used to create a fallback value for a file or module.",
"Here is a quick example of export default
:",
- "export default function add(x,y) {
return x + y;
}
",
+ "export default function add(x,y) {
return x + y;
}
",
"Note: Since export default
is used to declare a fallback value for a module or file, you can only have one value be a default export in each module or file. Additionally, you cannot use export default
with var
, let
, or const
",
"
",
"The following function should be the fallback value for the module. Please add the necessary code to do so."
@@ -1325,7 +1423,8 @@
"tests": [
{
"text": "Proper used of export
fallback.",
- "testString": "getUserInput => assert(getUserInput('index').match(/export\\s+default\\s+function\\s+subtract\\(x,y\\)\\s+{return\\s+x\\s-\\s+y;}/g), 'Proper used of export
fallback.');"
+ "testString":
+ "getUserInput => assert(getUserInput('index').match(/export\\s+default\\s+function\\s+subtract\\(x,y\\)\\s+{return\\s+x\\s-\\s+y;}/g), 'Proper used of export
fallback.');"
}
],
"releasedOn": "Feb 17, 2017",
@@ -1340,9 +1439,7 @@
"\"use strict\";",
"function subtract(x,y) {return x - y;}"
],
- "head": [
- "window.exports = function(){};"
- ],
+ "head": ["window.exports = function(){};"],
"tail": []
}
}
@@ -1361,7 +1458,8 @@
"tests": [
{
"text": "Properly imports export default
method.",
- "testString": "getUserInput => assert(getUserInput('index').match(/import\\s+subtract\\s+from\\s+\"math_functions\"/g), 'Properly imports export default
method.');"
+ "testString":
+ "getUserInput => assert(getUserInput('index').match(/import\\s+subtract\\s+from\\s+\"math_functions\"/g), 'Properly imports export default
method.');"
}
],
"releasedOn": "Feb 17, 2017",
@@ -1372,10 +1470,7 @@
"key": "indexjs",
"ext": "js",
"name": "index",
- "contents": [
- "\"use strict\";",
- "subtract(7,4);"
- ],
+ "contents": ["\"use strict\";", "subtract(7,4);"],
"head": [
"window.require = function(str) {",
"if (str === 'math_functions') {",
@@ -1388,4 +1483,4 @@
}
}
]
-}
\ No newline at end of file
+}
diff --git a/challenges/03-front-end-libraries/react-and-redux.json b/challenges/03-front-end-libraries/react-and-redux.json
index 55e0465c9..7fce2db09 100644
--- a/challenges/03-front-end-libraries/react-and-redux.json
+++ b/challenges/03-front-end-libraries/react-and-redux.json
@@ -5,16 +5,18 @@
"helpRoom": "Help",
"required": [
{
- "src":"https://unpkg.com/react@16.4.0/umd/react.production.min.js"
+ "src": "https://unpkg.com/react@16.4.0/umd/react.production.min.js"
},
{
- "src":"https://unpkg.com/react-dom@16.4.0/umd/react-dom.production.min.js"
+ "src":
+ "https://unpkg.com/react-dom@16.4.0/umd/react-dom.production.min.js"
},
{
"src": "https://cdnjs.cloudflare.com/ajax/libs/redux/3.7.2/redux.min.js"
},
{
- "src": "https://cdnjs.cloudflare.com/ajax/libs/react-redux/5.0.7/react-redux.min.js"
+ "src":
+ "https://cdnjs.cloudflare.com/ajax/libs/react-redux/5.0.7/react-redux.min.js"
}
],
"template": "${ source || '' }",
@@ -53,16 +55,22 @@
},
"tests": [
{
- "text": "The DisplayMessages
component should render an empty div
element.",
- "testString": "assert((function() { const mockedComponent = Enzyme.mount(React.createElement(DisplayMessages)); return mockedComponent.find('div').text() === '' })(), 'The DisplayMessages
component should render an empty div
element.');"
+ "text":
+ "The DisplayMessages
component should render an empty div
element.",
+ "testString":
+ "assert((function() { const mockedComponent = Enzyme.mount(React.createElement(DisplayMessages)); return mockedComponent.find('div').text() === '' })(), 'The DisplayMessages
component should render an empty div
element.');"
},
{
- "text": "The DisplayMessages
constructor should be called properly with super
, passing in props
.",
- "testString": "getUserInput => assert((function() { const noWhiteSpace = getUserInput('index').replace(/\\s/g,''); return noWhiteSpace.includes('constructor(props)') && noWhiteSpace.includes('super(props'); })(), 'The DisplayMessages
constructor should be called properly with super
, passing in props
.');"
+ "text":
+ "The DisplayMessages
constructor should be called properly with super
, passing in props
.",
+ "testString":
+ "getUserInput => assert((function() { const noWhiteSpace = getUserInput('index').replace(/\\s/g,''); return noWhiteSpace.includes('constructor(props)') && noWhiteSpace.includes('super(props'); })(), 'The DisplayMessages
constructor should be called properly with super
, passing in props
.');"
},
{
- "text": "The DisplayMessages
component should have an initial state equal to {input: \"\", messages: []}
.",
- "testString": "assert((function() { const mockedComponent = Enzyme.mount(React.createElement(DisplayMessages)); const initialState = mockedComponent.state(); return typeof initialState === 'object' && initialState.input === '' && Array.isArray(initialState.messages) && initialState.messages.length === 0; })(), 'The DisplayMessages
component should have an initial state equal to {input: \"\", messages: []}
.');"
+ "text":
+ "The DisplayMessages
component should have an initial state equal to {input: \"\", messages: []}
.",
+ "testString":
+ "assert((function() { const mockedComponent = Enzyme.mount(React.createElement(DisplayMessages)); const initialState = mockedComponent.state(); return typeof initialState === 'object' && initialState.input === '' && Array.isArray(initialState.messages) && initialState.messages.length === 0; })(), 'The DisplayMessages
component should have an initial state equal to {input: \"\", messages: []}
.');"
}
],
"solutions": [
@@ -120,28 +128,40 @@
},
"tests": [
{
- "text": "The DisplayMessages
component should initialize with a state equal to { input: \"\", messages: [] }
.",
- "testString": "assert((function() { const mockedComponent = Enzyme.mount(React.createElement(DisplayMessages)); const initialState = mockedComponent.state(); return ( typeof initialState === 'object' && initialState.input === '' && initialState.messages.length === 0); })(), 'The DisplayMessages
component should initialize with a state equal to { input: \"\", messages: [] }
.');"
+ "text":
+ "The DisplayMessages
component should initialize with a state equal to { input: \"\", messages: [] }
.",
+ "testString":
+ "assert((function() { const mockedComponent = Enzyme.mount(React.createElement(DisplayMessages)); const initialState = mockedComponent.state(); return ( typeof initialState === 'object' && initialState.input === '' && initialState.messages.length === 0); })(), 'The DisplayMessages
component should initialize with a state equal to { input: \"\", messages: [] }
.');"
},
{
- "text": "The DisplayMessages
component should render a div
containing an h2
element, a button
element, a ul
element, and li
elements as children.",
- "testString": "async () => { const mockedComponent = Enzyme.mount(React.createElement(DisplayMessages)); const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 100)); const state = () => { mockedComponent.setState({messages: ['__TEST__MESSAGE']}); return waitForIt(() => mockedComponent )}; const updated = await state(); assert(updated.find('div').length === 1 && updated.find('h2').length === 1 && updated.find('button').length === 1 && updated.find('ul').length === 1, 'The DisplayMessages
component should render a div
containing an h2
element, a button
element, a ul
element, and li
elements as children.'); }; "
+ "text":
+ "The DisplayMessages
component should render a div
containing an h2
element, a button
element, a ul
element, and li
elements as children.",
+ "testString":
+ "async () => { const mockedComponent = Enzyme.mount(React.createElement(DisplayMessages)); const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 100)); const state = () => { mockedComponent.setState({messages: ['__TEST__MESSAGE']}); return waitForIt(() => mockedComponent )}; const updated = await state(); assert(updated.find('div').length === 1 && updated.find('h2').length === 1 && updated.find('button').length === 1 && updated.find('ul').length === 1, 'The DisplayMessages
component should render a div
containing an h2
element, a button
element, a ul
element, and li
elements as children.'); }; "
},
{
- "text": "The input
element should render the value of input
in local state.",
- "testString": "async () => { const mockedComponent = Enzyme.mount(React.createElement(DisplayMessages)); const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 100)); const causeChange = (c, v) => c.find('input').simulate('change', { target: { value: v }}); const testValue = '__TEST__EVENT__INPUT'; const changed = () => { causeChange(mockedComponent, testValue); return waitForIt(() => mockedComponent )}; const updated = await changed(); assert(updated.find('input').props().value === testValue, 'The input
element should render the value of input
in local state.'); }; "
+ "text":
+ "The input
element should render the value of input
in local state.",
+ "testString":
+ "async () => { const mockedComponent = Enzyme.mount(React.createElement(DisplayMessages)); const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 100)); const causeChange = (c, v) => c.find('input').simulate('change', { target: { value: v }}); const testValue = '__TEST__EVENT__INPUT'; const changed = () => { causeChange(mockedComponent, testValue); return waitForIt(() => mockedComponent )}; const updated = await changed(); assert(updated.find('input').props().value === testValue, 'The input
element should render the value of input
in local state.'); }; "
},
{
- "text": "Calling the method handleChange
should update the input
value in state to the current input.",
- "testString": "async () => { const mockedComponent = Enzyme.mount(React.createElement(DisplayMessages)); const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 100)); const causeChange = (c, v) => c.find('input').simulate('change', { target: { value: v }}); const initialState = mockedComponent.state(); const testMessage = '__TEST__EVENT__MESSAGE__'; const changed = () => { causeChange(mockedComponent, testMessage); return waitForIt(() => mockedComponent )}; const afterInput = await changed(); assert(initialState.input === '' && afterInput.state().input === '__TEST__EVENT__MESSAGE__', 'Calling the method handleChange
should update the input
value in state to the current input.'); }; "
+ "text":
+ "Calling the method handleChange
should update the input
value in state to the current input.",
+ "testString":
+ "async () => { const mockedComponent = Enzyme.mount(React.createElement(DisplayMessages)); const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 100)); const causeChange = (c, v) => c.find('input').simulate('change', { target: { value: v }}); const initialState = mockedComponent.state(); const testMessage = '__TEST__EVENT__MESSAGE__'; const changed = () => { causeChange(mockedComponent, testMessage); return waitForIt(() => mockedComponent )}; const afterInput = await changed(); assert(initialState.input === '' && afterInput.state().input === '__TEST__EVENT__MESSAGE__', 'Calling the method handleChange
should update the input
value in state to the current input.'); }; "
},
{
- "text": "Clicking the Add message
button should call the method submitMessage
which should add the current input
to the messages
array in state.",
- "testString": "async () => { const mockedComponent = Enzyme.mount(React.createElement(DisplayMessages)); const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 100)); const causeChange = (c, v) => c.find('input').simulate('change', { target: { value: v }}); const initialState = mockedComponent.state(); const testMessage_1 = '__FIRST__MESSAGE__'; const firstChange = () => { causeChange(mockedComponent, testMessage_1); return waitForIt(() => mockedComponent )}; const firstResult = await firstChange(); const firstSubmit = () => { mockedComponent.find('button').simulate('click'); return waitForIt(() => mockedComponent )}; const afterSubmit_1 = await firstSubmit(); const submitState_1 = afterSubmit_1.state(); const testMessage_2 = '__SECOND__MESSAGE__'; const secondChange = () => { causeChange(mockedComponent, testMessage_2); return waitForIt(() => mockedComponent )}; const secondResult = await secondChange(); const secondSubmit = () => { mockedComponent.find('button').simulate('click'); return waitForIt(() => mockedComponent )}; const afterSubmit_2 = await secondSubmit(); const submitState_2 = afterSubmit_2.state(); assert(initialState.messages.length === 0 && submitState_1.messages.length === 1 && submitState_2.messages.length === 2 && submitState_2.messages[1] === testMessage_2, 'Clicking the Add message
button should call the method submitMessage
which should add the current input
to the messages
array in state.'); }; "
+ "text":
+ "Clicking the Add message
button should call the method submitMessage
which should add the current input
to the messages
array in state.",
+ "testString":
+ "async () => { const mockedComponent = Enzyme.mount(React.createElement(DisplayMessages)); const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 100)); const causeChange = (c, v) => c.find('input').simulate('change', { target: { value: v }}); const initialState = mockedComponent.state(); const testMessage_1 = '__FIRST__MESSAGE__'; const firstChange = () => { causeChange(mockedComponent, testMessage_1); return waitForIt(() => mockedComponent )}; const firstResult = await firstChange(); const firstSubmit = () => { mockedComponent.find('button').simulate('click'); return waitForIt(() => mockedComponent )}; const afterSubmit_1 = await firstSubmit(); const submitState_1 = afterSubmit_1.state(); const testMessage_2 = '__SECOND__MESSAGE__'; const secondChange = () => { causeChange(mockedComponent, testMessage_2); return waitForIt(() => mockedComponent )}; const secondResult = await secondChange(); const secondSubmit = () => { mockedComponent.find('button').simulate('click'); return waitForIt(() => mockedComponent )}; const afterSubmit_2 = await secondSubmit(); const submitState_2 = afterSubmit_2.state(); assert(initialState.messages.length === 0 && submitState_1.messages.length === 1 && submitState_2.messages.length === 2 && submitState_2.messages[1] === testMessage_2, 'Clicking the Add message
button should call the method submitMessage
which should add the current input
to the messages
array in state.'); }; "
},
{
- "text": "The submitMessage
method should clear the current input.",
- "testString": "async () => { const mockedComponent = Enzyme.mount(React.createElement(DisplayMessages)); const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 100)); const causeChange = (c, v) => c.find('input').simulate('change', { target: { value: v }}); const initialState = mockedComponent.state(); const testMessage = '__FIRST__MESSAGE__'; const firstChange = () => { causeChange(mockedComponent, testMessage); return waitForIt(() => mockedComponent )}; const firstResult = await firstChange(); const firstState = firstResult.state(); const firstSubmit = () => { mockedComponent.find('button').simulate('click'); return waitForIt(() => mockedComponent )}; const afterSubmit = await firstSubmit(); const submitState = afterSubmit.state(); assert(firstState.input === testMessage && submitState.input === '', 'The submitMessage
method should clear the current input.'); }; "
+ "text":
+ "The submitMessage
method should clear the current input.",
+ "testString":
+ "async () => { const mockedComponent = Enzyme.mount(React.createElement(DisplayMessages)); const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 100)); const causeChange = (c, v) => c.find('input').simulate('change', { target: { value: v }}); const initialState = mockedComponent.state(); const testMessage = '__FIRST__MESSAGE__'; const firstChange = () => { causeChange(mockedComponent, testMessage); return waitForIt(() => mockedComponent )}; const firstResult = await firstChange(); const firstState = firstResult.state(); const firstSubmit = () => { mockedComponent.find('button').simulate('click'); return waitForIt(() => mockedComponent )}; const afterSubmit = await firstSubmit(); const submitState = afterSubmit.state(); assert(firstState.input === testMessage && submitState.input === '', 'The submitMessage
method should clear the current input.'); }; "
}
],
"solutions": [
@@ -177,28 +197,39 @@
},
"tests": [
{
- "text": "The const ADD
should exist and hold a value equal to the string ADD
",
- "testString": "assert(ADD === 'ADD', 'The const ADD
should exist and hold a value equal to the string ADD
');"
+ "text":
+ "The const ADD
should exist and hold a value equal to the string ADD
",
+ "testString":
+ "assert(ADD === 'ADD', 'The const ADD
should exist and hold a value equal to the string ADD
');"
},
{
- "text": "The action creator addMessage
should return an object with type
equal to ADD
and message equal to the message that is passed in.",
- "testString": "assert((function() { const addAction = addMessage('__TEST__MESSAGE__'); return addAction.type === ADD && addAction.message === '__TEST__MESSAGE__'; })(), 'The action creator addMessage
should return an object with type
equal to ADD
and message equal to the message that is passed in.');"
+ "text":
+ "The action creator addMessage
should return an object with type
equal to ADD
and message equal to the message that is passed in.",
+ "testString":
+ "assert((function() { const addAction = addMessage('__TEST__MESSAGE__'); return addAction.type === ADD && addAction.message === '__TEST__MESSAGE__'; })(), 'The action creator addMessage
should return an object with type
equal to ADD
and message equal to the message that is passed in.');"
},
{
"text": "messageReducer
should be a function.",
- "testString": "assert(typeof messageReducer === 'function', 'messageReducer
should be a function.');"
+ "testString":
+ "assert(typeof messageReducer === 'function', 'messageReducer
should be a function.');"
},
{
- "text": "The store should exist and have an initial state set to an empty array.",
- "testString": "assert((function() { const initialState = store.getState(); return typeof store === 'object' && initialState.length === 0; })(), 'The store should exist and have an initial state set to an empty array.');"
+ "text":
+ "The store should exist and have an initial state set to an empty array.",
+ "testString":
+ "assert((function() { const initialState = store.getState(); return typeof store === 'object' && initialState.length === 0; })(), 'The store should exist and have an initial state set to an empty array.');"
},
{
- "text": "Dispatching addMessage
against the store should immutably add a new message to the array of messages held in state.",
- "testString": "assert((function() { const initialState = store.getState(); const isFrozen = DeepFreeze(initialState); store.dispatch(addMessage('__A__TEST__MESSAGE')); const addState = store.getState(); return (isFrozen && addState[0] === '__A__TEST__MESSAGE'); })(), 'Dispatching addMessage
against the store should immutably add a new message to the array of messages held in state.');"
+ "text":
+ "Dispatching addMessage
against the store should immutably add a new message to the array of messages held in state.",
+ "testString":
+ "assert((function() { const initialState = store.getState(); const isFrozen = DeepFreeze(initialState); store.dispatch(addMessage('__A__TEST__MESSAGE')); const addState = store.getState(); return (isFrozen && addState[0] === '__A__TEST__MESSAGE'); })(), 'Dispatching addMessage
against the store should immutably add a new message to the array of messages held in state.');"
},
{
- "text": "The messageReducer
should return the current state if called with any other actions.",
- "testString": "assert((function() { const addState = store.getState(); store.dispatch({type: 'FAKE_ACTION'}); const testState = store.getState(); return (addState === testState); })(), 'The messageReducer
should return the current state if called with any other actions.');"
+ "text":
+ "The messageReducer
should return the current state if called with any other actions.",
+ "testString":
+ "assert((function() { const addState = store.getState(); store.dispatch({type: 'FAKE_ACTION'}); const testState = store.getState(); return (addState === testState); })(), 'The messageReducer
should return the current state if called with any other actions.');"
}
],
"solutions": [
@@ -216,7 +247,7 @@
"description": [
"In the last challenge, you created a Redux store to handle the messages array and created an action for adding new messages. The next step is to provide React access to the Redux store and the actions it needs to dispatch updates. React Redux provides its react-redux
package to help accomplish these tasks.",
"React Redux provides a small API with two key features: Provider
and connect
. Another challenge covers connect
. The Provider
is a wrapper component from React Redux that wraps your React app. This wrapper then allows you to access the Redux store
and dispatch
functions throughout your component tree. Provider
takes two props, the Redux store and the child components of your app. Defining the Provider
for an App component might look like this:",
- "<Provider store={store}>
<App/>
</Provider>
",
+ "<Provider store={store}>
<App/>
</Provider>
",
"
",
"The code editor now shows all your Redux and React code from the past several challenges. It includes the Redux store, actions, and the DisplayMessages
component. The only new piece is the AppWrapper
component at the bottom. Use this top level component to render the Provider
from ReactRedux
, and pass the Redux store as a prop. Then render the DisplayMessages
component as a child. Once you are finished, you should see your React component rendered to the page.",
"Note: React Redux is available as a global variable here, so you can access the Provider with dot notation. The code in the editor takes advantage of this and sets it to a constant Provider
for you to use in the AppWrapper
render method."
@@ -315,19 +346,26 @@
"tests": [
{
"text": "The AppWrapper
should render.",
- "testString": "assert((function() { const mockedComponent = Enzyme.mount(React.createElement(AppWrapper)); return mockedComponent.find('AppWrapper').length === 1; })(), 'The AppWrapper
should render.');"
+ "testString":
+ "assert((function() { const mockedComponent = Enzyme.mount(React.createElement(AppWrapper)); return mockedComponent.find('AppWrapper').length === 1; })(), 'The AppWrapper
should render.');"
},
{
- "text": "The Provider
wrapper component should have a prop of store
passed to it, equal to the Redux store.",
- "testString": "getUserInput => assert((function() { const mockedComponent = Enzyme.mount(React.createElement(AppWrapper)); return getUserInput('index').replace(/\\s/g,'').includes(''); })(), 'The Provider
wrapper component should have a prop of store
passed to it, equal to the Redux store.');"
+ "text":
+ "The Provider
wrapper component should have a prop of store
passed to it, equal to the Redux store.",
+ "testString":
+ "getUserInput => assert((function() { const mockedComponent = Enzyme.mount(React.createElement(AppWrapper)); return getUserInput('index').replace(/\\s/g,'').includes(''); })(), 'The Provider
wrapper component should have a prop of store
passed to it, equal to the Redux store.');"
},
{
- "text": "DisplayMessages
should render as a child of AppWrapper
.",
- "testString": "assert((function() { const mockedComponent = Enzyme.mount(React.createElement(AppWrapper)); return mockedComponent.find('AppWrapper').find('DisplayMessages').length === 1; })(), 'DisplayMessages
should render as a child of AppWrapper
.');"
+ "text":
+ "DisplayMessages
should render as a child of AppWrapper
.",
+ "testString":
+ "assert((function() { const mockedComponent = Enzyme.mount(React.createElement(AppWrapper)); return mockedComponent.find('AppWrapper').find('DisplayMessages').length === 1; })(), 'DisplayMessages
should render as a child of AppWrapper
.');"
},
{
- "text": "The DisplayMessages
component should render an h2, input, button, and ul
element.",
- "testString": "assert((function() { const mockedComponent = Enzyme.mount(React.createElement(AppWrapper)); return mockedComponent.find('div').length === 1 && mockedComponent.find('h2').length === 1 && mockedComponent.find('button').length === 1 && mockedComponent.find('ul').length === 1; })(), 'The DisplayMessages
component should render an h2, input, button, and ul
element.');"
+ "text":
+ "The DisplayMessages
component should render an h2, input, button, and ul
element.",
+ "testString":
+ "assert((function() { const mockedComponent = Enzyme.mount(React.createElement(AppWrapper)); return mockedComponent.find('div').length === 1 && mockedComponent.find('h2').length === 1 && mockedComponent.find('button').length === 1 && mockedComponent.find('ul').length === 1; })(), 'The DisplayMessages
component should render an h2, input, button, and ul
element.');"
}
],
"solutions": [
@@ -367,19 +405,24 @@
"tests": [
{
"text": "The const state
should be an empty array.",
- "testString": "assert(Array.isArray(state) && state.length === 0, 'The const state
should be an empty array.');"
+ "testString":
+ "assert(Array.isArray(state) && state.length === 0, 'The const state
should be an empty array.');"
},
{
"text": "mapStateToProps
should be a function.",
- "testString": "assert(typeof mapStateToProps === 'function', 'mapStateToProps
should be a function.');"
+ "testString":
+ "assert(typeof mapStateToProps === 'function', 'mapStateToProps
should be a function.');"
},
{
"text": "mapStateToProps
should return an object.",
- "testString": "assert(typeof mapStateToProps() === 'object', 'mapStateToProps
should return an object.');"
+ "testString":
+ "assert(typeof mapStateToProps() === 'object', 'mapStateToProps
should return an object.');"
},
{
- "text": "Passing an array as state to mapStateToProps
should return this array assigned to a key of messages
.",
- "testString": "assert(mapStateToProps(['messages']).messages.pop() === 'messages', 'Passing an array as state to mapStateToProps
should return this array assigned to a key of messages
.');"
+ "text":
+ "Passing an array as state to mapStateToProps
should return this array assigned to a key of messages
.",
+ "testString":
+ "assert(mapStateToProps(['messages']).messages.pop() === 'messages', 'Passing an array as state to mapStateToProps
should return this array assigned to a key of messages
.');"
}
],
"solutions": [
@@ -397,7 +440,7 @@
"description": [
"The mapDispatchToProps()
function is used to provide specific action creators to your React components so they can dispatch actions against the Redux store. It's similar in structure to the mapStateToProps()
function you wrote in the last challenge. It returns an object that maps dispatch actions to property names, which become component props
. However, instead of returning a piece of state
, each property returns a function that calls dispatch
with an action creator and any relevant action data. You have access to this dispatch
because it's passed in to mapDispatchToProps()
as a parameter when you define the function, just like you passed state
to mapStateToProps()
. Behind the scenes, React Redux is using Redux's store.dispatch()
to conduct these dispatches with mapDispatchToProps()
. This is similar to how it uses store.subscribe()
for components that are mapped to state
.",
"For example, you have a loginUser()
action creator that takes a username
as an action payload. The object returned from mapDispatchToProps()
for this action creator would look something like:",
- "{
submitLoginUser: function(username) {
dispatch(loginUser(username));
}
}
",
+ "{
submitLoginUser: function(username) {
dispatch(loginUser(username));
}
}
",
"
",
"The code editor provides an action creator called addMessage()
. Write the function mapDispatchToProps()
that takes dispatch
as an argument, then returns an object. The object should have a property submitNewMessage
set to the dispatch function, which takes a parameter for the new message to add when it dispatches addMessage()
."
],
@@ -423,20 +466,26 @@
},
"tests": [
{
- "text": "addMessage
should return an object with keys type
and message
.",
- "testString": "assert((function() { const addMessageTest = addMessage(); return ( addMessageTest.hasOwnProperty('type') && addMessageTest.hasOwnProperty('message')); })(), 'addMessage
should return an object with keys type
and message
.');"
+ "text":
+ "addMessage
should return an object with keys type
and message
.",
+ "testString":
+ "assert((function() { const addMessageTest = addMessage(); return ( addMessageTest.hasOwnProperty('type') && addMessageTest.hasOwnProperty('message')); })(), 'addMessage
should return an object with keys type
and message
.');"
},
{
"text": "mapDispatchToProps
should be a function.",
- "testString": "assert(typeof mapDispatchToProps === 'function', 'mapDispatchToProps
should be a function.');"
+ "testString":
+ "assert(typeof mapDispatchToProps === 'function', 'mapDispatchToProps
should be a function.');"
},
{
"text": "mapDispatchToProps
should return an object.",
- "testString": "assert(typeof mapDispatchToProps() === 'object', 'mapDispatchToProps
should return an object.');"
+ "testString":
+ "assert(typeof mapDispatchToProps() === 'object', 'mapDispatchToProps
should return an object.');"
},
{
- "text": "Dispatching addMessage
with submitNewMessage
from mapDispatchToProps
should return a message to the dispatch function.",
- "testString": "assert((function() { let testAction; const dispatch = (fn) => { testAction = fn; }; let dispatchFn = mapDispatchToProps(dispatch); dispatchFn.submitNewMessage('__TEST__MESSAGE__'); return (testAction.type === 'ADD' && testAction.message === '__TEST__MESSAGE__'); })(), 'Dispatching addMessage
with submitNewMessage
from mapDispatchToProps
should return a message to the dispatch function.');"
+ "text":
+ "Dispatching addMessage
with submitNewMessage
from mapDispatchToProps
should return a message to the dispatch function.",
+ "testString":
+ "assert((function() { let testAction; const dispatch = (fn) => { testAction = fn; }; let dispatchFn = mapDispatchToProps(dispatch); dispatchFn.submitNewMessage('__TEST__MESSAGE__'); return (testAction.type === 'ADD' && testAction.message === '__TEST__MESSAGE__'); })(), 'Dispatching addMessage
with submitNewMessage
from mapDispatchToProps
should return a message to the dispatch function.');"
}
],
"solutions": [
@@ -521,15 +570,20 @@
"tests": [
{
"text": "The Presentational
component should render.",
- "testString": "assert((function() { const mockedComponent = Enzyme.mount(React.createElement(AppWrapper)); return mockedComponent.find('Presentational').length === 1; })(), 'The Presentational
component should render.');"
+ "testString":
+ "assert((function() { const mockedComponent = Enzyme.mount(React.createElement(AppWrapper)); return mockedComponent.find('Presentational').length === 1; })(), 'The Presentational
component should render.');"
},
{
- "text": "The Presentational
component should receive a prop messages
via connect
.",
- "testString": "assert((function() { const mockedComponent = Enzyme.mount(React.createElement(AppWrapper)); const props = mockedComponent.find('Presentational').props(); return props.messages === '__INITIAL__STATE__'; })(), 'The Presentational
component should receive a prop messages
via connect
.');"
+ "text":
+ "The Presentational
component should receive a prop messages
via connect
.",
+ "testString":
+ "assert((function() { const mockedComponent = Enzyme.mount(React.createElement(AppWrapper)); const props = mockedComponent.find('Presentational').props(); return props.messages === '__INITIAL__STATE__'; })(), 'The Presentational
component should receive a prop messages
via connect
.');"
},
{
- "text": "The Presentational
component should receive a prop submitNewMessage
via connect
.",
- "testString": "assert((function() { const mockedComponent = Enzyme.mount(React.createElement(AppWrapper)); const props = mockedComponent.find('Presentational').props(); return typeof props.submitNewMessage === 'function'; })(), 'The Presentational
component should receive a prop submitNewMessage
via connect
.');"
+ "text":
+ "The Presentational
component should receive a prop submitNewMessage
via connect
.",
+ "testString":
+ "assert((function() { const mockedComponent = Enzyme.mount(React.createElement(AppWrapper)); const props = mockedComponent.find('Presentational').props(); return typeof props.submitNewMessage === 'function'; })(), 'The Presentational
component should receive a prop submitNewMessage
via connect
.');"
}
],
"solutions": [
@@ -662,23 +716,32 @@
"tests": [
{
"text": "The AppWrapper
should render to the page.",
- "testString": "assert((function() { const mockedComponent = Enzyme.mount(React.createElement(AppWrapper)); return mockedComponent.find('AppWrapper').length === 1; })(), 'The AppWrapper
should render to the page.');"
+ "testString":
+ "assert((function() { const mockedComponent = Enzyme.mount(React.createElement(AppWrapper)); return mockedComponent.find('AppWrapper').length === 1; })(), 'The AppWrapper
should render to the page.');"
},
{
- "text": "The Presentational
component should render an h2
, input
, button
, and ul
elements.",
- "testString": "assert((function() { const mockedComponent = Enzyme.mount(React.createElement(AppWrapper)); return mockedComponent.find('Presentational').length === 1; })(), 'The Presentational
component should render an h2
, input
, button
, and ul
elements.');"
+ "text":
+ "The Presentational
component should render an h2
, input
, button
, and ul
elements.",
+ "testString":
+ "assert((function() { const mockedComponent = Enzyme.mount(React.createElement(AppWrapper)); return mockedComponent.find('Presentational').length === 1; })(), 'The Presentational
component should render an h2
, input
, button
, and ul
elements.');"
},
{
- "text": "The Presentational
component should render an h2
, input
, button
, and ul
elements.",
- "testString": "assert((function() { const mockedComponent = Enzyme.mount(React.createElement(AppWrapper)); const PresentationalComponent = mockedComponent.find('Presentational'); return ( PresentationalComponent.find('div').length === 1 && PresentationalComponent.find('h2').length === 1 && PresentationalComponent.find('button').length === 1 && PresentationalComponent.find('ul').length === 1 ); })(), 'The Presentational
component should render an h2
, input
, button
, and ul
elements.');"
+ "text":
+ "The Presentational
component should render an h2
, input
, button
, and ul
elements.",
+ "testString":
+ "assert((function() { const mockedComponent = Enzyme.mount(React.createElement(AppWrapper)); const PresentationalComponent = mockedComponent.find('Presentational'); return ( PresentationalComponent.find('div').length === 1 && PresentationalComponent.find('h2').length === 1 && PresentationalComponent.find('button').length === 1 && PresentationalComponent.find('ul').length === 1 ); })(), 'The Presentational
component should render an h2
, input
, button
, and ul
elements.');"
},
{
- "text": "The Presentational
component should receive messages
from the Redux store as a prop.",
- "testString": "assert((function() { const mockedComponent = Enzyme.mount(React.createElement(AppWrapper)); const PresentationalComponent = mockedComponent.find('Presentational'); const props = PresentationalComponent.props(); return Array.isArray(props.messages); })(), 'The Presentational
component should receive messages
from the Redux store as a prop.');"
+ "text":
+ "The Presentational
component should receive messages
from the Redux store as a prop.",
+ "testString":
+ "assert((function() { const mockedComponent = Enzyme.mount(React.createElement(AppWrapper)); const PresentationalComponent = mockedComponent.find('Presentational'); const props = PresentationalComponent.props(); return Array.isArray(props.messages); })(), 'The Presentational
component should receive messages
from the Redux store as a prop.');"
},
{
- "text": "The Presentational
component should receive the submitMessage
action creator as a prop.",
- "testString": "assert((function() { const mockedComponent = Enzyme.mount(React.createElement(AppWrapper)); const PresentationalComponent = mockedComponent.find('Presentational'); const props = PresentationalComponent.props(); return typeof props.submitNewMessage === 'function'; })(), 'The Presentational
component should receive the submitMessage
action creator as a prop.');"
+ "text":
+ "The Presentational
component should receive the submitMessage
action creator as a prop.",
+ "testString":
+ "assert((function() { const mockedComponent = Enzyme.mount(React.createElement(AppWrapper)); const PresentationalComponent = mockedComponent.find('Presentational'); const props = PresentationalComponent.props(); return typeof props.submitNewMessage === 'function'; })(), 'The Presentational
component should receive the submitMessage
action creator as a prop.');"
}
],
"solutions": [
@@ -810,39 +873,56 @@
"tests": [
{
"text": "The AppWrapper
should render to the page.",
- "testString": "assert((function() { const mockedComponent = Enzyme.mount(React.createElement(AppWrapper)); return mockedComponent.find('AppWrapper').length === 1; })(), 'The AppWrapper
should render to the page.');"
+ "testString":
+ "assert((function() { const mockedComponent = Enzyme.mount(React.createElement(AppWrapper)); return mockedComponent.find('AppWrapper').length === 1; })(), 'The AppWrapper
should render to the page.');"
},
{
- "text": "The Presentational
component should render an h2
, input
, button
, and ul
elements.",
- "testString": "assert((function() { const mockedComponent = Enzyme.mount(React.createElement(AppWrapper)); return mockedComponent.find('Presentational').length === 1; })(), 'The Presentational
component should render an h2
, input
, button
, and ul
elements.');"
+ "text":
+ "The Presentational
component should render an h2
, input
, button
, and ul
elements.",
+ "testString":
+ "assert((function() { const mockedComponent = Enzyme.mount(React.createElement(AppWrapper)); return mockedComponent.find('Presentational').length === 1; })(), 'The Presentational
component should render an h2
, input
, button
, and ul
elements.');"
},
{
- "text": "The Presentational
component should render an h2
, input
, button
, and ul
elements.",
- "testString": "assert((function() { const mockedComponent = Enzyme.mount(React.createElement(AppWrapper)); const PresentationalComponent = mockedComponent.find('Presentational'); return ( PresentationalComponent.find('div').length === 1 && PresentationalComponent.find('h2').length === 1 && PresentationalComponent.find('button').length === 1 && PresentationalComponent.find('ul').length === 1 ); })(), 'The Presentational
component should render an h2
, input
, button
, and ul
elements.');"
+ "text":
+ "The Presentational
component should render an h2
, input
, button
, and ul
elements.",
+ "testString":
+ "assert((function() { const mockedComponent = Enzyme.mount(React.createElement(AppWrapper)); const PresentationalComponent = mockedComponent.find('Presentational'); return ( PresentationalComponent.find('div').length === 1 && PresentationalComponent.find('h2').length === 1 && PresentationalComponent.find('button').length === 1 && PresentationalComponent.find('ul').length === 1 ); })(), 'The Presentational
component should render an h2
, input
, button
, and ul
elements.');"
},
{
- "text": "The Presentational
component should receive messages
from the Redux store as a prop.",
- "testString": "assert((function() { const mockedComponent = Enzyme.mount(React.createElement(AppWrapper)); const PresentationalComponent = mockedComponent.find('Presentational'); const props = PresentationalComponent.props(); return Array.isArray(props.messages); })(), 'The Presentational
component should receive messages
from the Redux store as a prop.');"
+ "text":
+ "The Presentational
component should receive messages
from the Redux store as a prop.",
+ "testString":
+ "assert((function() { const mockedComponent = Enzyme.mount(React.createElement(AppWrapper)); const PresentationalComponent = mockedComponent.find('Presentational'); const props = PresentationalComponent.props(); return Array.isArray(props.messages); })(), 'The Presentational
component should receive messages
from the Redux store as a prop.');"
},
{
- "text": "The Presentational
component should receive the submitMessage
action creator as a prop.",
- "testString": "assert((function() { const mockedComponent = Enzyme.mount(React.createElement(AppWrapper)); const PresentationalComponent = mockedComponent.find('Presentational'); const props = PresentationalComponent.props(); return typeof props.submitNewMessage === 'function'; })(), 'The Presentational
component should receive the submitMessage
action creator as a prop.');"
+ "text":
+ "The Presentational
component should receive the submitMessage
action creator as a prop.",
+ "testString":
+ "assert((function() { const mockedComponent = Enzyme.mount(React.createElement(AppWrapper)); const PresentationalComponent = mockedComponent.find('Presentational'); const props = PresentationalComponent.props(); return typeof props.submitNewMessage === 'function'; })(), 'The Presentational
component should receive the submitMessage
action creator as a prop.');"
},
{
- "text": "The state of the Presentational
component should contain one property, input
, which is initialized to an empty string.",
- "testString": "assert((function() { const mockedComponent = Enzyme.mount(React.createElement(AppWrapper)); const PresentationalState = mockedComponent.find('Presentational').instance().state; return typeof PresentationalState.input === 'string' && Object.keys(PresentationalState).length === 1; })(), 'The state of the Presentational
component should contain one property, input
, which is initialized to an empty string.');"
+ "text":
+ "The state of the Presentational
component should contain one property, input
, which is initialized to an empty string.",
+ "testString":
+ "assert((function() { const mockedComponent = Enzyme.mount(React.createElement(AppWrapper)); const PresentationalState = mockedComponent.find('Presentational').instance().state; return typeof PresentationalState.input === 'string' && Object.keys(PresentationalState).length === 1; })(), 'The state of the Presentational
component should contain one property, input
, which is initialized to an empty string.');"
},
{
- "text": "Typing in the input
element should update the state of the Presentational
component.",
- "testString": "async () => { const mockedComponent = Enzyme.mount(React.createElement(AppWrapper)); const testValue = '__MOCK__INPUT__'; const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 100)); const causeChange = (c, v) => c.find('input').simulate('change', { target: { value: v }}); let initialInput = mockedComponent.find('Presentational').find('input'); const changed = () => { causeChange(mockedComponent, testValue); return waitForIt(() => mockedComponent )}; const updated = await changed(); const updatedInput = updated.find('Presentational').find('input'); assert(initialInput.props().value === '' && updatedInput.props().value === '__MOCK__INPUT__', 'Typing in the input
element should update the state of the Presentational
component.'); }; "
+ "text":
+ "Typing in the input
element should update the state of the Presentational
component.",
+ "testString":
+ "async () => { const mockedComponent = Enzyme.mount(React.createElement(AppWrapper)); const testValue = '__MOCK__INPUT__'; const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 100)); const causeChange = (c, v) => c.find('input').simulate('change', { target: { value: v }}); let initialInput = mockedComponent.find('Presentational').find('input'); const changed = () => { causeChange(mockedComponent, testValue); return waitForIt(() => mockedComponent )}; const updated = await changed(); const updatedInput = updated.find('Presentational').find('input'); assert(initialInput.props().value === '' && updatedInput.props().value === '__MOCK__INPUT__', 'Typing in the input
element should update the state of the Presentational
component.'); }; "
},
{
- "text": "Dispatching the submitMessage
on the Presentational
component should update Redux store and clear the input in local state.",
- "testString": "async () => { const mockedComponent = Enzyme.mount(React.createElement(AppWrapper)); const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 100)); let beforeProps = mockedComponent.find('Presentational').props(); const testValue = '__TEST__EVENT__INPUT__'; const causeChange = (c, v) => c.find('input').simulate('change', { target: { value: v }}); const changed = () => { causeChange(mockedComponent, testValue); return waitForIt(() => mockedComponent )}; const clickButton = () => { mockedComponent.find('button').simulate('click'); return waitForIt(() => mockedComponent )}; const afterChange = await changed(); const afterChangeInput = afterChange.find('input').props().value; const afterClick = await clickButton(); const afterProps = mockedComponent.find('Presentational').props(); assert(beforeProps.messages.length === 0 && afterChangeInput === testValue && afterProps.messages.pop() === testValue && afterClick.find('input').props().value === '', 'Dispatching the submitMessage
on the Presentational
component should update Redux store and clear the input in local state.'); }; "
+ "text":
+ "Dispatching the submitMessage
on the Presentational
component should update Redux store and clear the input in local state.",
+ "testString":
+ "async () => { const mockedComponent = Enzyme.mount(React.createElement(AppWrapper)); const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 100)); let beforeProps = mockedComponent.find('Presentational').props(); const testValue = '__TEST__EVENT__INPUT__'; const causeChange = (c, v) => c.find('input').simulate('change', { target: { value: v }}); const changed = () => { causeChange(mockedComponent, testValue); return waitForIt(() => mockedComponent )}; const clickButton = () => { mockedComponent.find('button').simulate('click'); return waitForIt(() => mockedComponent )}; const afterChange = await changed(); const afterChangeInput = afterChange.find('input').props().value; const afterClick = await clickButton(); const afterProps = mockedComponent.find('Presentational').props(); assert(beforeProps.messages.length === 0 && afterChangeInput === testValue && afterProps.messages.pop() === testValue && afterClick.find('input').props().value === '', 'Dispatching the submitMessage
on the Presentational
component should update Redux store and clear the input in local state.'); }; "
},
{
- "text": "The Presentational
component should render the messages
from the Redux store.",
- "testString": "async () => { const mockedComponent = Enzyme.mount(React.createElement(AppWrapper)); const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 100)); let beforeProps = mockedComponent.find('Presentational').props(); const testValue = '__TEST__EVENT__INPUT__'; const causeChange = (c, v) => c.find('input').simulate('change', { target: { value: v }}); const changed = () => { causeChange(mockedComponent, testValue); return waitForIt(() => mockedComponent )}; const clickButton = () => { mockedComponent.find('button').simulate('click'); return waitForIt(() => mockedComponent )}; const afterChange = await changed(); const afterChangeInput = afterChange.find('input').props().value; const afterClick = await clickButton(); const afterProps = mockedComponent.find('Presentational').props(); assert(beforeProps.messages.length === 0 && afterChangeInput === testValue && afterProps.messages.pop() === testValue && afterClick.find('input').props().value === '' && afterClick.find('ul').childAt(0).text() === testValue, 'The Presentational
component should render the messages
from the Redux store.'); }; "
+ "text":
+ "The Presentational
component should render the messages
from the Redux store.",
+ "testString":
+ "async () => { const mockedComponent = Enzyme.mount(React.createElement(AppWrapper)); const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 100)); let beforeProps = mockedComponent.find('Presentational').props(); const testValue = '__TEST__EVENT__INPUT__'; const causeChange = (c, v) => c.find('input').simulate('change', { target: { value: v }}); const changed = () => { causeChange(mockedComponent, testValue); return waitForIt(() => mockedComponent )}; const clickButton = () => { mockedComponent.find('button').simulate('click'); return waitForIt(() => mockedComponent )}; const afterChange = await changed(); const afterChangeInput = afterChange.find('input').props().value; const afterClick = await clickButton(); const afterProps = mockedComponent.find('Presentational').props(); assert(beforeProps.messages.length === 0 && afterChangeInput === testValue && afterProps.messages.pop() === testValue && afterClick.find('input').props().value === '' && afterClick.find('ul').childAt(0).text() === testValue, 'The Presentational
component should render the messages
from the Redux store.'); }; "
}
],
"solutions": [
@@ -901,17 +981,17 @@
},
"tests": [
{
- "text": "The message Now I know React and Redux!
should be logged to the console.",
- "testString": "assert(editor.getValue().includes('console.log(\"Now I know React and Redux!\")') || editor.getValue().includes('console.log(\\'Now I know React and Redux!\\')'), 'The message Now I know React and Redux!
should be logged to the console.');"
+ "text":
+ "The message Now I know React and Redux!
should be logged to the console.",
+ "testString":
+ "assert(editor.getValue().includes('console.log(\"Now I know React and Redux!\")') || editor.getValue().includes('console.log(\\'Now I know React and Redux!\\')'), 'The message Now I know React and Redux!
should be logged to the console.');"
}
],
- "solutions": [
- "console.log('Now I know React and Redux!');"
- ],
+ "solutions": ["console.log('Now I know React and Redux!');"],
"challengeType": 6,
"isRequired": false,
"translations": {},
"reactRedux": true
}
]
-}
\ No newline at end of file
+}
diff --git a/challenges/03-front-end-libraries/react.json b/challenges/03-front-end-libraries/react.json
index 998106189..32cbf5560 100644
--- a/challenges/03-front-end-libraries/react.json
+++ b/challenges/03-front-end-libraries/react.json
@@ -5,13 +5,15 @@
"helpRoom": "Help",
"required": [
{
- "src":"https://unpkg.com/react@16.4.0/umd/react.production.min.js"
+ "src": "https://unpkg.com/react@16.4.0/umd/react.production.min.js"
},
{
- "src":"https://unpkg.com/react-dom@16.4.0/umd/react-dom.production.min.js"
+ "src":
+ "https://unpkg.com/react-dom@16.4.0/umd/react-dom.production.min.js"
}
],
- "template": "${ source || '' }",
+ "template":
+ "${ source || '' }",
"challenges": [
{
"id": "587d7dbc367417b2b2512bb1",
@@ -31,30 +33,26 @@
"key": "indexjsx",
"ext": "jsx",
"name": "index",
- "contents": [
- "",
- "const JSX = ;",
- ""
- ],
- "tail": [
- "ReactDOM.render(JSX, document.getElementById('root'))"
- ],
+ "contents": ["", "const JSX = ;", ""],
+ "tail": ["ReactDOM.render(JSX, document.getElementById('root'))"],
"head": []
}
},
"tests": [
{
- "text": "The constant JSX
should return an h1
element.",
- "testString": "assert(JSX.type === 'h1', 'The constant JSX
should return an h1
element.');"
+ "text":
+ "The constant JSX
should return an h1
element.",
+ "testString":
+ "assert(JSX.type === 'h1', 'The constant JSX
should return an h1
element.');"
},
{
- "text": "The h1
tag should include the text Hello JSX!
",
- "testString": "assert(Enzyme.shallow(JSX).contains('Hello JSX!'), 'The h1
tag should include the text Hello JSX!
');"
+ "text":
+ "The h1
tag should include the text Hello JSX!
",
+ "testString":
+ "assert(Enzyme.shallow(JSX).contains('Hello JSX!'), 'The h1
tag should include the text Hello JSX!
');"
}
],
- "solutions": [
- "const JSX = Hello JSX!
;"
- ],
+ "solutions": ["const JSX = Hello JSX!
;"],
"challengeType": 6,
"isRequired": false,
"translations": {},
@@ -71,7 +69,7 @@
"For instance, several JSX elements written as siblings with no parent wrapper element will not transpile.",
"Here's an example:",
"Valid JSX:",
- "<div>
<p>Paragraph One</p>
<p>Paragraph Two</p>
<p>Paragraph Three</p>
</div>
",
+ "<div>
<p>Paragraph One</p>
<p>Paragraph Two</p>
<p>Paragraph Three</p>
</div>
",
"Invalid JSX:",
"<p>Paragraph One</p>
<p>Paragraph Two</p>
<p>Paragraph Three</p>
",
"
",
@@ -84,36 +82,41 @@
"key": "indexjsx",
"ext": "jsx",
"name": "index",
- "contents": [
- "// write your code here",
- ""
- ],
- "tail": [
- "ReactDOM.render(JSX, document.getElementById('root'))"
- ],
+ "contents": ["// write your code here", ""],
+ "tail": ["ReactDOM.render(JSX, document.getElementById('root'))"],
"head": []
}
},
"tests": [
{
- "text": "The constant JSX
should return a div
element.",
- "testString": "assert(JSX.type === 'div', 'The constant JSX
should return a div
element.');"
+ "text":
+ "The constant JSX
should return a div
element.",
+ "testString":
+ "assert(JSX.type === 'div', 'The constant JSX
should return a div
element.');"
},
{
- "text": "The div
should contain a p
tag as the second element.",
- "testString": "assert(JSX.props.children[1].type === 'p', 'The div
should contain a p
tag as the second element.');"
+ "text":
+ "The div
should contain a p
tag as the second element.",
+ "testString":
+ "assert(JSX.props.children[1].type === 'p', 'The div
should contain a p
tag as the second element.');"
},
{
- "text": "The div
should contain a ul
tag as the third element.",
- "testString": "assert(JSX.props.children[2].type === 'ul', 'The div
should contain a ul
tag as the third element.');"
+ "text":
+ "The div
should contain a ul
tag as the third element.",
+ "testString":
+ "assert(JSX.props.children[2].type === 'ul', 'The div
should contain a ul
tag as the third element.');"
},
{
- "text": "The div
should contain an h1
tag as the first element.",
- "testString": "assert(JSX.props.children[0].type === 'h1', 'The div
should contain an h1
tag as the first element.');"
+ "text":
+ "The div
should contain an h1
tag as the first element.",
+ "testString":
+ "assert(JSX.props.children[0].type === 'h1', 'The div
should contain an h1
tag as the first element.');"
},
{
- "text": "The ul
should contain three li
elements.",
- "testString": "assert(JSX.props.children[2].props.children.length === 3, 'The ul
should contain three li
elements.');"
+ "text":
+ "The ul
should contain three li
elements.",
+ "testString":
+ "assert(JSX.props.children[2].props.children.length === 3, 'The ul
should contain three li
elements.');"
}
],
"solutions": [
@@ -147,28 +150,33 @@
"
",
");"
],
- "tail": [
- "ReactDOM.render(JSX, document.getElementById('root'))"
- ],
+ "tail": ["ReactDOM.render(JSX, document.getElementById('root'))"],
"head": []
}
},
"tests": [
{
- "text": "The constant
JSX
should return a
div
element.",
- "testString": "assert(JSX.type === 'div', 'The constant
JSX
should return a
div
element.');"
+ "text":
+ "The constant
JSX
should return a
div
element.",
+ "testString":
+ "assert(JSX.type === 'div', 'The constant
JSX
should return a
div
element.');"
},
{
- "text": "The
div
should contain an
h1
tag as the first element.",
- "testString": "assert(JSX.props.children[0].type === 'h1', 'The
div
should contain an
h1
tag as the first element.');"
+ "text":
+ "The
div
should contain an
h1
tag as the first element.",
+ "testString":
+ "assert(JSX.props.children[0].type === 'h1', 'The
div
should contain an
h1
tag as the first element.');"
},
{
- "text": "The
div
should contain a
p
tag as the second element.",
- "testString": "assert(JSX.props.children[1].type === 'p', 'The
div
should contain a
p
tag as the second element.');"
+ "text":
+ "The
div
should contain a
p
tag as the second element.",
+ "testString":
+ "assert(JSX.props.children[1].type === 'p', 'The
div
should contain a
p
tag as the second element.');"
},
{
"text": "The
JSX
should include a comment.",
- "testString": "getUserInput => assert(getUserInput('index').includes('/*') && getUserInput('index').includes('*/'), 'The
JSX
should include a comment.');"
+ "testString":
+ "getUserInput => assert(getUserInput('index').includes('/*') && getUserInput('index').includes('*/'), 'The
JSX
should include a comment.');"
}
],
"solutions": [
@@ -211,20 +219,28 @@
},
"tests": [
{
- "text": "The constant
JSX
should return a
div
element.",
- "testString": "assert(JSX.type === 'div', 'The constant
JSX
should return a
div
element.');"
+ "text":
+ "The constant
JSX
should return a
div
element.",
+ "testString":
+ "assert(JSX.type === 'div', 'The constant
JSX
should return a
div
element.');"
},
{
- "text": "The
div
should contain an
h1
tag as the first element.",
- "testString": "assert(JSX.props.children[0].type === 'h1', 'The
div
should contain an
h1
tag as the first element.');"
+ "text":
+ "The
div
should contain an
h1
tag as the first element.",
+ "testString":
+ "assert(JSX.props.children[0].type === 'h1', 'The
div
should contain an
h1
tag as the first element.');"
},
{
- "text": "The
div
should contain a
p
tag as the second element.",
- "testString": "assert(JSX.props.children[1].type === 'p', 'The
div
should contain a
p
tag as the second element.');"
+ "text":
+ "The
div
should contain a
p
tag as the second element.",
+ "testString":
+ "assert(JSX.props.children[1].type === 'p', 'The
div
should contain a
p
tag as the second element.');"
},
{
- "text": "The provided JSX element should render to the DOM node with id
challenge-node
.",
- "testString": "assert(document.getElementById('challenge-node').childNodes[0].innerHTML === '
Hello World
Lets render this to the DOM
', 'The provided JSX element should render to the DOM node with id
challenge-node
.');"
+ "text":
+ "The provided JSX element should render to the DOM node with id
challenge-node
.",
+ "testString":
+ "assert(document.getElementById('challenge-node').childNodes[0].innerHTML === '
Hello World
Lets render this to the DOM
', 'The provided JSX element should render to the DOM node with id
challenge-node
.');"
}
],
"solutions": [
@@ -259,20 +275,21 @@
"
",
");"
],
- "tail": [
- "ReactDOM.render(JSX, document.getElementById('root'))"
- ],
+ "tail": ["ReactDOM.render(JSX, document.getElementById('root'))"],
"head": []
}
},
"tests": [
{
- "text": "The constant