Skip to content

Commit 2b874a7

Browse files
committed
ok
1 parent f1b7de0 commit 2b874a7

File tree

59 files changed

+1069
-1074
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

59 files changed

+1069
-1074
lines changed

1-js/2-first-steps/19-function-expression/article.md

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -68,17 +68,40 @@ In more detail:
6868
Please note again: there are no brackets after `sayHi`. If they were, then `func = sayHi()` would write *the result of the call* `sayHi()` into `func`, not *the function* `sayHi` itself.
6969
3. Now the function can be called both as `sayHi()` and `func()`.
7070

71-
7271
Note, that we could also have used a Function Expression to declare `sayHi`, in the first line: `let sayHi = function() { ... }`. Everything would work the same.
7372

73+
Every value in Javascript has the type. What type of value is a function?
74+
75+
**In Javascript, a function is an object.**
76+
77+
We can abuse this by adding properties to it and using them in the code:
78+
79+
```js run
80+
function sayHi() {
81+
alert("Hi");
82+
sayHi.counter++;
83+
}
84+
sayHi.counter = 0;
85+
86+
sayHi(); // Hi
87+
sayHi(); // Hi
88+
89+
alert( `Called ${sayHi.counter} times` ); // Called 2 times
90+
```
91+
92+
There are many well-known Javascript libraries that make use of this. They create a function and attach many other functions to it as its properties. For instance, the [jquery](https://jquery.com) library creates a function named `$`, the library [lodash](https://lodash.com) creates a function `_`. So, we have something that can do the job by itself and also carries a bunch of other functionality.
93+
94+
7495
```smart header="A function is a value representing an \"action\""
7596
Regular values like strings or numbers represent the *data*.
7697
7798
A function can be perceived as an *action*.
7899
79-
We can copy it between variables and run when we want.
100+
We can copy it between variables and run when we want. We can even add properties to it if we wish.
80101
```
81102

103+
104+
82105
## Function Expression as a method
83106

84107
Now let's go back: we have two ways of declaring a function. Do we really need both? What's about Function Expressions that makes it a good addition?

1-js/4-data-structures/2-number/article.md

Lines changed: 2 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -327,18 +327,11 @@ Sometimes `isFinite` is used to validate the string value for being a regular nu
327327
```js run
328328
let num = +prompt("Enter a number", '');
329329
330+
// isFinite will be true only for regular numbers
330331
alert(`num:${num}, isFinite:${isFinite(num)}`);
331332
```
332333
333-
Here `num` is always of a number type, because of the unary plus `+`, but...
334-
335-
- It may be `NaN` if the string is non-numeric.
336-
- It may be `Infinity` if the user typed in `"Infinity"`.
337-
338-
The `isFinite` test checks that and returns `true` only if it's a regular number. That's just what we usually need.
339-
340-
Please note that an empty or a space-only string would give `num=0` in the described case.
341-
334+
Please note that an empty or a space-only string is treated as `0` in the described case. If it's not what's needed, then additional checks are required.
342335
343336
## parseInt and parseFloat
344337
Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
describe("ucFirst", function() {
2-
it('делает первый символ заглавным', function() {
3-
assert.strictEqual(ucFirst("вася"), "Вася");
2+
it('Uppercases the first symbol', function() {
3+
assert.strictEqual(ucFirst("john"), "John");
44
});
55

6-
it('для пустой строки возвращает пустую строку', function() {
6+
it("Doesn't die on an empty string", function() {
77
assert.strictEqual(ucFirst(""), "");
88
});
99
});

1-js/4-data-structures/3-string/1-ucfirst/solution.md

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,27 @@
1-
Мы не можем просто заменить первый символ, т.к. строки в JavaScript неизменяемы.
1+
We can't "replace" the first character, because strings in JavaScript are immutable.
22

3-
Но можно пересоздать строку на основе существующей, с заглавным первым символом:
3+
But we can make a new string based on the existing one, with the uppercased first character:
44

55
```js
6-
var newStr = str[0].toUpperCase() + str.slice(1);
6+
let newStr = str[0].toUpperCase() + str.slice(1);
77
```
88

9-
Однако, есть небольшая проблемка -- в случае, когда строка пуста, будет ошибка.
9+
There's a small problem though. If `str` is empty, then `str[0]` is undefined, so we'll get an error.
1010

11-
Ведь `str[0] == undefined`, а у `undefined` нет метода `toUpperCase()`.
11+
There are two variants here:
1212

13-
Выхода два. Первый -- использовать `str.charAt(0)`, он всегда возвращает строку, для пустой строки -- пустую, но не `undefined`. Второй -- отдельно проверить на пустую строку, вот так:
13+
1. Use `str.charAt(0)`, as it always returns a string (maybe empty).
14+
2. Add a test for an empty string.
15+
16+
Here's the 2nd variant:
1417

1518
```js run
1619
function ucFirst(str) {
17-
// только пустая строка в логическом контексте даст false
1820
if (!str) return str;
1921

2022
return str[0].toUpperCase() + str.slice(1);
2123
}
2224

23-
alert( ucFirst("вася") );
25+
alert( ucFirst("john") ); // John
2426
```
2527

26-
P.S. Возможны и более короткие решения, использующие методы для работы со строками, которые мы пройдём далее.

1-js/4-data-structures/3-string/1-ucfirst/task.md

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,11 @@ importance: 5
22

33
---
44

5-
# Сделать первый символ заглавным
5+
# Uppercast the first character
66

7-
Напишите функцию `ucFirst(str)`, которая возвращает строку `str` с заглавным первым символом, например:
7+
Write a function `ucFirst(str)` that returns the string `str` with the uppercased first character, for instance:
88

99
```js
10-
ucFirst("вася") == "Вася";
11-
ucFirst("") == ""; // нет ошибок при пустой строке
10+
ucFirst("john") == "John";
1211
```
1312

14-
P.S. В JavaScript нет встроенного метода для этого. Создайте функцию, используя `toUpperCase()` и `charAt()`.
Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
function checkSpam(str) {
2-
var lowerStr = str.toLowerCase();
2+
let lowerStr = str.toLowerCase();
33

4-
return !!(~lowerStr.indexOf('viagra') || ~lowerStr.indexOf('xxx'));
4+
return lowerStr.includes('viagra') || lowerStr.includes('xxx');
55
}
Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,13 @@
11
describe("checkSpam", function() {
2-
it('считает спамом "buy ViAgRA now"', function() {
2+
it('finds spam in "buy ViAgRA now"', function() {
33
assert.isTrue(checkSpam('buy ViAgRA now'));
44
});
55

6-
it('считает спамом "free xxxxx"', function() {
6+
it('finds spam in "free xxxxx"', function() {
77
assert.isTrue(checkSpam('free xxxxx'));
88
});
99

10-
it('не считает спамом "innocent rabbit"', function() {
10+
it('no spam in "innocent rabbit"', function() {
1111
assert.isFalse(checkSpam('innocent rabbit'));
1212
});
1313
});

1-js/4-data-structures/3-string/2-check-spam/solution.md

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,10 @@
1-
Метод `indexOf` ищет совпадение с учетом регистра. То есть, в строке `'xXx'` он не найдет `'XXX'`.
2-
3-
Для проверки приведем к нижнему регистру и строку `str` а затем уже будем искать.
1+
To make the search case-insensitive, let's bring the stirng to lower case and then search:
42

53
```js run
64
function checkSpam(str) {
7-
var lowerStr = str.toLowerCase();
5+
let lowerStr = str.toLowerCase();
86

9-
return !!(~lowerStr.indexOf('viagra') || ~lowerStr.indexOf('xxx'));
7+
return lowerStr.includes('viagra') || lowerStr.includes('xxx');
108
}
119

1210
alert( checkSpam('buy ViAgRA now') );

1-js/4-data-structures/3-string/2-check-spam/task.md

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,11 @@ importance: 5
22

33
---
44

5-
# Проверьте спам
5+
# Check for spam
66

7-
Напишите функцию `checkSpam(str)`, которая возвращает `true`, если строка `str` содержит 'viagra' or 'XXX', а иначе `false`.
7+
Write a function `checkSpam(str)` that returns `true` if `str` contains 'viagra' or 'XXX', otherwise `false.
88

9-
Функция должна быть нечувствительна к регистру:
9+
The function must be case-insensitive:
1010

1111
```js
1212
checkSpam('buy ViAgRA now') == true
Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
11
function truncate(str, maxlength) {
2-
return (str.length > maxlength) ?
3-
str.slice(0, maxlength - 3) + '...' : str;
2+
return (str.length > maxlength) ?
3+
str.slice(0, maxlength - 1) + '' : str;
44
}

0 commit comments

Comments
 (0)