diff --git a/1-js/05-data-types/04-array/10-maximal-subarray/solution.md b/1-js/05-data-types/04-array/10-maximal-subarray/solution.md index dfc6e2eb..a2ba50bf 100644 --- a/1-js/05-data-types/04-array/10-maximal-subarray/solution.md +++ b/1-js/05-data-types/04-array/10-maximal-subarray/solution.md @@ -1,6 +1,6 @@ -# The slow solution +# The slow solution -We can calculate all possible subsums. +We can calculate all possible subsums. The simplest way is to take every element and calculate sums of all subarrays starting from it. @@ -61,7 +61,7 @@ The solution has a time complexety of [O(n2)](https://en.wikipedia.or For big arrays (1000, 10000 or more items) such algorithms can lead to a seroius sluggishness. -# Fast solution +# Fast solution Let's walk the array and keep the current partial sum of elements in the variable `s`. If `s` becomes negative at some point, then assign `s=0`. The maximum of all such `s` will be the answer. @@ -72,7 +72,7 @@ function getMaxSubSum(arr) { let maxSum = 0; let partialSum = 0; - for (let item of arr; i++) { // for each item of arr + for (let item of arr) { // for each item of arr partialSum += item; // add it to partialSum maxSum = Math.max(maxSum, partialSum); // remember the maximum if (partialSum < 0) partialSum = 0; // zero if negative @@ -91,5 +91,4 @@ alert( getMaxSubSum([-1, -2, -3]) ); // 0 The algorithm requires exactly 1 array pass, so the time complexity is O(n). -You can find more detail information about the algorithm here: [Maximum subarray problem](http://en.wikipedia.org/wiki/Maximum_subarray_problem). If it's still not obvious why that works, then please trace the algorithm on the examples above, see how it works, that's better than any words. - +You can find more detail information about the algorithm here: [Maximum subarray problem](http://en.wikipedia.org/wiki/Maximum_subarray_problem). If it's still not obvious why that works, then please trace the algorithm on the examples above, see how it works, that's better than any words. diff --git a/1-js/05-data-types/05-array-methods/article.md b/1-js/05-data-types/05-array-methods/article.md index 522e7ec4..276d8871 100644 --- a/1-js/05-data-types/05-array-methods/article.md +++ b/1-js/05-data-types/05-array-methods/article.md @@ -519,7 +519,7 @@ let arr = [1, 2, 3, 4, 5] let result = arr.reduce((sum, current) => sum + current), 0); -alert( result ); // 15 +alert(result); // 15 ``` Here we used the most common variant of `reduce` which uses only 2 arguments. @@ -562,12 +562,24 @@ The result is the same. That's because if there's no initial, then `reduce` take The calculation table is the same as above, minus the first row. -But such use requires an extreme care. If the array is empty, then `reduce` call without initial value gives an error. So it's generally advised to specify the initial value. +But such use requires an extreme care. If the array is empty, then `reduce` call without initial value gives an error. + +Here's an example: + +```js run +let arr = []; + +// Error: Reduce of empty array with no initial value +// if the initial value existed, reduce would return it for the empty arr. +arr.reduce((sum, current) => sum + current); +``` + + +So it's advised to always specify the initial value. The method [arr.reduceRight](mdn:js/Array/reduceRight) does the same, but goes from right to left. - ## Iterate: forEach The [arr.forEach](mdn:js/Array/forEach) method allows to run a function for every element of the array. @@ -615,13 +627,13 @@ alert(Array.isArray({})); // false alert(Array.isArray([])); // true ``` -## Methods: "thisArg" +## Most methods support "thisArg" Almost all array methods that call functions -- like `find`, `filter`, `map`, with a notable exception of `sort`, accept an optional additional parameter `thisArg`. -In the sections above that parameter is not explained, because it's rarely used. +That parameter is not explained in the sections above, because it's rarely used. But for completeness we have to cover it. -But for completeness here's the full syntax: +Here's the full syntax of these methods: ```js arr.find(func, thisArg); @@ -633,7 +645,7 @@ arr.map(func, thisArg); The value of `thisArg` parameter becomes `this` for `func`. -For instance, here we use an object method as a filter: +For instance, here we use an object method as a filter and `thisArg` comes in handy: ```js run let user = { diff --git a/1-js/08-error-handling/2-custom-errors/article.md b/1-js/08-error-handling/2-custom-errors/article.md index 709cd359..d7a780f6 100644 --- a/1-js/08-error-handling/2-custom-errors/article.md +++ b/1-js/08-error-handling/2-custom-errors/article.md @@ -2,11 +2,11 @@ When we develop something, we often need our own error classes to reflect specific things that may go wrong in our tasks. For errors in network operations we may need `HttpError`, for database operations `DbError`, for searching operations `NotFoundError` and so on. -Our errors should inherit from basic `Error` class and support basic error properties like `message`, `name` and, preferably, `stack`. But they also may have other properties of their own, e.g. `HttpError` objects may have `statusCode` property with a value like `404` or `403` or `500`. +Our errors should support basic error properties like `message`, `name` and, preferably, `stack`. But they also may have other properties of their own, e.g. `HttpError` objects may have `statusCode` property with a value like `404` or `403` or `500`. -Technically, we can use standalone classes for our errors, because JavaScript allows to use `throw` with any argument. But if we inherit from `Error`, then it becomes possible to use `obj instanceof Error` check to identify error objects. So it's better to inherit from it. +JavaScript allows to use `throw` with any argument, so technically our custom error classes don't need to inherit from `Error`. But if we inherit, then it becomes possible to use `obj instanceof Error` to identify error objects. So it's better to inherit from it. -As we build our application, our own errors naturally form a hierarchy, for instance `HttpTimeoutError` may inherit from `HttpError`. Examples will follow soon. +As we build our application, our own errors naturally form a hierarchy, for instance `HttpTimeoutError` may inherit from `HttpError`, and so on. ## Extending Error @@ -17,14 +17,20 @@ Here's an example of how a valid `json` may look: let json = `{ "name": "John", "age": 30 }`; ``` -If `JSON.parse` receives malformed `json`, then it throws `SyntaxError`. But even if `json` is syntactically correct, it may don't have the necessary data. For instance, if may not have `name` and `age` properties that are essential for our users. +Internally, we'll use `JSON.parse`. If it receives malformed `json`, then it throws `SyntaxError`. -That's called "data validation" -- we need to ensure that the data has all the necessary fields. And if the validation fails, then it not really a `SyntaxError`, because the data is syntactically correct. Let's create `ValidationError` -- the error object of our own with additional information about the offending field. +But even if `json` is syntactically correct, that doesn't mean that it's a valid user, right? It may miss the necessary data. For instance, if may not have `name` and `age` properties that are essential for our users. -Our `ValidationError` should inherit from the built-in `Error` class. To better understand what we're extending -- here's the approximate code for built-in [Error class](https://tc39.github.io/ecma262/#sec-error-message): +Our function `readUser(json)` will not only read JSON, but check ("validate") the data. If there are no required fields, or the format is wrong, then that's an error. And that's not a `SyntaxError`, because the data is syntactically correct, but another kind of error. We'll call it `ValidationError` and create a class for it. An error of that kind should also carry the information about the offending field. + +Our `ValidationError` class should inherit from the built-in `Error` class. + +That class is built-in, but we should have its approximate code before our eyes, to understand what we're extending. + +So here you are: ```js -// "pseudocode" for the built-in Error class defined by JavaScript itself +// The "pseudocode" for the built-in Error class defined by JavaScript itself class Error { constructor(message) { this.message = message; @@ -34,7 +40,7 @@ class Error { } ``` -Now let's inherit from it: +Now let's go on and inherit `ValidationError` from it: ```js run untrusted *!* @@ -59,10 +65,10 @@ try { } ``` -Please note: +Please take a look at the constructor: -1. In the line `(1)` we call the parent constructor to set the message. JavaScript requires us to call `super` in the child constructor. -2. The parent constructor sets the `name` property to `"Error"`, so here we reset it to the right value. +1. In the line `(1)` we call the parent constructor. JavaScript requires us to call `super` in the child constructor, so that's obligatory. The parent constructor sets the `message` property. +2. The parent constructor also sets the `name` property to `"Error"`, so in the line `(2)` we reset it to the right value. Let's try to use it in `readUser(json)`: @@ -97,23 +103,34 @@ try { *!* alert("Invalid data: " + err.message); // Invalid data: No field: name */!* - } else if (err instanceof SyntaxError) { + } else if (err instanceof SyntaxError) { // (*) alert("JSON Syntax Error: " + err.message); } else { - throw err; // unknown error, rethrow it + throw err; // unknown error, rethrow it (**) } } ``` -Everything works -- both our `ValidationError` and the built-in `SyntaxError` from `JSON.parse` can be generated and handled. +The `try..catch` block in the code above handles both our `ValidationError` and the built-in `SyntaxError` from `JSON.parse`. -Please take a look at how the code checks for the error type in `catch (err) { ... }`. We could use `if (err.name == "ValidationError")`, but `if (err instanceof ValidationError)` is much better, because in the future we are going to extend `ValidationError`, make new subtypes of it, namely `PropertyRequiredError`. And `instanceof` check will continue to work. So that's future-proof. +Please take a look at how we use `instanceof` to check for the specific error type in the line `(*)`. -Also it's important that if `catch` meets an unknown error, then it rethrows it. The `catch` only knows how to handle validation and syntax errors, other kinds (due to a typo in the code or such) should fall through. +We could also look at `err.name`, like this: + +```js +// ... +// instead of (err instanceof SyntaxError) +} else if (err.name == "SyntaxError") { // (*) +// ... +``` + +The `instanceof` version is much better, because in the future we are going to extend `ValidationError`, make subtypes of it, like `PropertyRequiredError`. And `instanceof` check will continue to work for new inheriting classes. So that's future-proof. + +Also it's important that if `catch` meets an unknown error, then it rethrows it in the line `(**)`. The `catch` only knows how to handle validation and syntax errors, other kinds (due to a typo in the code or such) should fall through. ## Further inheritance -The `ValidationError` class is very generic. Many things may be wrong. The property may be absent or it may be in a wrong format (like a string value for `age`). Let's make a more concrete class `PropertyRequiredError`, exactly for absent properties. It will carry additional information about the property that's missing. +The `ValidationError` class is very generic. Many things may go wrong. The property may be absent or it may be in a wrong format (like a string value for `age`). Let's make a more concrete class `PropertyRequiredError`, exactly for absent properties. It will carry additional information about the property that's missing. ```js run class ValidationError extends Error { @@ -168,9 +185,11 @@ try { The new class `PropertyRequiredError` is easy to use: we only need to pass the property name: `new PropertyRequiredError(property)`. The human-readable `message` is generated by the constructor. -Plese note that `this.name` in `PropertyRequiredError` once again assigned manually. We could make our own "basic error" class, name it `MyError` that removes this burden from our shoulders by using `this.constructor.name` for `this.name` in the constructor. And then inherit from it. +Please note that `this.name` in `PropertyRequiredError` constructor is again assigned manually. That may become a bit tedius -- to assign `this.name = ` when creating each custom error. But there's a way out. We can make our own "basic error" class that removes this burden from our shoulders by using `this.constructor.name` for `this.name` in the constructor. And then inherit from it. -Here we go: +Let's call it `MyError`. + +Here's the code with `MyError` and other custom error classes, simplified: ```js run class MyError extends Error { @@ -195,17 +214,19 @@ class PropertyRequiredError extends ValidationError { alert( new PropertyRequiredError("field").name ); // PropertyRequiredError ``` -Now the inheritance became simpler, as we got rid of the `"this.name = ..."` line in the constructor. +Now custom errors are much shorter, especially `ValidationError`, as we got rid of the `"this.name = ..."` line in the constructor. ## Wrapping exceptions -The purpose of the function `readUser` in the code above is "to read the user data", right? There may occur different kinds of errors in the process. Right now we have `SyntaxError` and `ValidationError`, but there may appear more if we put more stuff into it. +The purpose of the function `readUser` in the code above is "to read the user data", right? There may occur different kinds of errors in the process. Right now we have `SyntaxError` and `ValidationError`, but in the future `readUser` function may grow: the new code will probably generate other kinds of errors. -Right now the code which calls `readUser` uses multiple `if` in `catch` to check for different error types. The important questions is: do we really want to check for all error types one-by-one every time we call `readUser`? +The code which calls `readUser` should handle these errors. Right now it uses multiple `if` in the `catch` block to check for different error types and rethrow the unknown ones. But if `readUser` function generates several kinds of errors -- then we should ask ourselves: do we really want to check for all error types one-by-one in every code that calls `readUser`? -Often the answer is: "No". The outer code wants to be "one level above all that". It wants to have some kind of "data reading error". Why exactly it happened -- is usually irrelevant (the message has the info). Or, even better if there is a way to get more details, but only if we need to. +Often the answer is "No": the outer code wants to be "one level above all that". It wants to have some kind of "data reading error". Why exactly it happened -- is often irrelevant (the error message describes it). Or, even better if there is a way to get error details, but only if we need to. -So let's make a new class `ReadError` to represent such errors. If an error occurs inside `readUser`, we'll catch it there and generate `ReadError`. We'll also keep the reference to the original error in the `cause` property. +So let's make a new class `ReadError` to represent such errors. If an error occurs inside `readUser`, we'll catch it there and generate `ReadError`. We'll also keep the reference to the original error in the `cause` property. Then the outer code will only have to check for `ReadError`. + +Here's the code that defines `ReadError` and demonstrates its use in `readUser` and `try..catch`: ```js run class ReadError extends Error { @@ -273,7 +294,9 @@ try { } ``` -In the code above, `readUser` does exactly as described -- catches syntax and validation errors and throws `ReadError` errors instead (unknown errors are rethrown as usual). +In the code above, `readUser` works exactly as described -- catches syntax and validation errors and throws `ReadError` errors instead (unknown errors are rethrown as usual). + +So the outer code checks `instanceof ReadError` and that's it. No need to list possible all error types. The approach is called "wrapping exceptions", because we take "low level exceptions" and "wrap" them into `ReadError` that is more abstract and more convenient to use for the calling code. It is widely used in object-oriented programming. diff --git a/6-async/05-async-await/01-rewrite-async-2/task.md b/6-async/05-async-await/01-rewrite-async-2/task.md index 8b15386c..94af2e57 100644 --- a/6-async/05-async-await/01-rewrite-async-2/task.md +++ b/6-async/05-async-await/01-rewrite-async-2/task.md @@ -1,9 +1,9 @@ # Rewrite "rethrow" async/await -Rewrite the "rethrow" example from the chapter using `async/await` instead of `.then/catch`. +Below you can find the "rethrow" example from the chapter . Rewrite it using `async/await` instead of `.then/catch`. -And get rid of recursion in favour of a loop in `demoGithubUser`: with `async/await` that becomes possible and is easier to develop later on. +And get rid of the recursion in favour of a loop in `demoGithubUser`: with `async/await` that becomes easy to do. ```js run class HttpError extends Error { diff --git a/6-async/05-async-await/article.md b/6-async/05-async-await/article.md index 2bdbb148..aef4a073 100644 --- a/6-async/05-async-await/article.md +++ b/6-async/05-async-await/article.md @@ -119,9 +119,10 @@ async function showAvatar() { showAvatar(); ``` -Pretty clean and easy to read, right? +Pretty clean and easy to read, right? Much better than before. -Please note that we can't write `await` in the top-level code. That wouldn't work: +````smart header="`await` won't work in the top-level code" +People who are just starting to use `await` tend to forget that, but we can't write `await` in the top-level code. That wouldn't work: ```js run // syntax error in top-level code @@ -129,8 +130,8 @@ let response = await fetch('/article/promise-chaining/user.json'); let user = await response.json(); ``` -So we need to have a wrapping async function for the code that awaits. - +So we need to have a wrapping async function for the code that awaits. Just as in the example above. +```` ````smart header="`await` accepts thenables" Like `promise.then`, `await` allows to use thenable objects (those with a callable `then` method). Again, the idea is that a 3rd-party object may be not a promise, but promise-compatible: if it supports `.then`, that's enough to use with `await`. diff --git a/figures.sketch b/figures.sketch index 9d252bc8..7bf104a3 100644 Binary files a/figures.sketch and b/figures.sketch differ