freeCodeCamp/curriculum/challenges/italian/15-javascript-algorithms-an.../learn-functional-programmin.../step-022.md

121 lines
2.0 KiB
Markdown
Raw Normal View History

---
id: 5d7925334c5e22586dd72962
title: Step 22
challengeType: 0
dashedName: step-22
---
# --description--
The ternary operator has the following syntax:
```js
const result = condition ? valueIfTrue : valueIfFalse;
const result = 1 === 1 ? 1 : 0; // 1
const result = 9 > 10 ? "Yes" : "No"; // "No"
```
Use this operator to return `str` if `str === str2`, and an empty string (`""`) otherwise.
# --hints--
See description above for instructions.
```js
assert(
highPrecedence('2*2') === '' &&
highPrecedence('2+2') === '2+2' &&
code.includes('?')
);
```
# --seed--
## --before-user-code--
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Spreadsheet</title>
<style>
#container {
display: grid;
grid-template-columns: 50px repeat(10, 200px);
grid-template-rows: repeat(11, 30px);
}
.label {
background-color: lightgray;
text-align: center;
vertical-align: middle;
line-height: 30px;
}
</style>
</head>
<body>
<div id="container">
<div></div>
</div>
```
## --after-user-code--
```html
</body>
</html>
```
## --seed-contents--
```html
<script>
const infixToFunction = {
"+": (x, y) => x + y,
"-": (x, y) => x - y,
"*": (x, y) => x * y,
"/": (x, y) => x / y
};
const infixEval = (str, regex) =>
str.replace(regex, (_, arg1, fn, arg2) =>
infixToFunction[fn](parseFloat(arg1), parseFloat(arg2))
);
--fcc-editable-region--
const highPrecedence = str => {
const regex = /([0-9.]+)([*\/])([0-9.]+)/;
const str2 = infixEval(str, regex);
return str2;
};
--fcc-editable-region--
</script>
```
# --solutions--
```html
<script>
const infixToFunction = {
"+": (x, y) => x + y,
"-": (x, y) => x - y,
"*": (x, y) => x * y,
"/": (x, y) => x / y
};
const infixEval = (str, regex) =>
str.replace(regex, (_, arg1, fn, arg2) =>
infixToFunction[fn](parseFloat(arg1), parseFloat(arg2))
);
const highPrecedence = str => {
const regex = /([0-9.]+)([*\/])([0-9.]+)/;
const str2 = infixEval(str, regex);
return str === str2 ? str : "";
};
</script>
```