Skip to content

Commit aa886b1

Browse files
committed
Update examples in readme
1 parent fcfb7d6 commit aa886b1

File tree

2 files changed

+65
-67
lines changed

2 files changed

+65
-67
lines changed

interfaceWrapper/en/README.md

Lines changed: 25 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ how wrapper works for `setTimeout`.
2020

2121
1. Learn how `setTimeout` is wrapped in example: `framework.js`. Now we will
2222
try to wrap module fs. We can iterate all of its functions by following code:
23-
`for (var key in fs) {...}` and replace its function with wrapped ones. We need
23+
`for (const key in fs) {...}` and replace its function with wrapped ones. We need
2424
a closure function and it should be universal to wrap any function in fs
2525
interface. The purpose of this example wrapper is to log all calls to the file
2626
system in a file indicating the time, a function name, its arguments, and if
@@ -30,13 +30,14 @@ This task can be divided into a few steps.
3030
2. Remove `setTimeout` example from `application.js` and replace it with the
3131
following code:
3232

33-
```JavaScript
34-
var fileName = './README.md';
35-
console.log('Application going to read ' + fileName);
36-
fs.readFile(fileName, function(err, src) {
37-
console.log('File ' + fileName + ' size ' + src.length);
38-
});
39-
```
33+
```JavaScript
34+
const fileName = './README.md';
35+
console.log('Application going to read ' + fileName);
36+
fs.readFile(fileName, (err, src) => {
37+
console.log('File ' + fileName + ' size ' + src.length);
38+
});
39+
```
40+
4041
This example contains a call to `fs.readFile`. In next steps we will change the
4142
behavior of the code changing `framework.js` and wrapping all `fs` functions.
4243
Let's run `node framework` and make sure that it reads the file and displays its
@@ -45,33 +46,30 @@ length.
4546
all keys from given library into new interface. So we can pass its result
4647
(cloned `fs`) to sandbox instead of `fs`. Cloning function example:
4748

48-
```JavaScript
49-
function cloneInterface(anInterface) {
50-
var clone = {};
51-
for (var key in anInterface) {
52-
clone[key] = anInterface[key];
53-
}
54-
return clone;
49+
```JavaScript
50+
const cloneInterface = (anInterface) => {
51+
const clone = {};
52+
for (const key in anInterface) {
53+
clone[key] = anInterface[key];
5554
}
56-
```
55+
return clone;
56+
};
57+
```
58+
5759
4. After that we can add wrapper `wrapFunction(fnName, fn)` with 2 arguments:
5860
name of the function and link to a function itself. It returns `wrapper`
5961
closure function. Closure `wrapper` is a newly created function with the help
6062
of functional inheritance, so it will see `fnName`, `fn` in its context. Thus
6163
we can pass all arguments from wrapper into original function as you see in
6264
example:
6365

64-
```JavaScript
65-
function wrapFunction(fnName, fn) {
66-
return function wrapper() {
67-
var args = [];
68-
Array.prototype.push.apply(args, arguments);
69-
console.log('Call: ' + fnName);
70-
console.dir(args);
71-
return fn.apply(undefined, args);
72-
}
73-
}
74-
```
66+
```JavaScript
67+
const wrapFunction = (fnName, fn) => (...args) => {
68+
console.log('Call: ' + fnName);
69+
console.dir(args);
70+
return fn(...args);
71+
}
72+
```
7573

7674
5. Now should detect do we have `callback` argument as a last argument of
7775
function call, we can do that by `typeof()` comparing to `function`. If we have

interfaceWrapper/ru/README.md

Lines changed: 40 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@
2020

2121
1. Нужно изучить, как обернут таймер.
2222
По аналогии с оберткой таймера нужно сделать обертку вокруг модуля fs.
23-
Все его функции нужно пройти в цикле `for (var key in fs) { ... }` и заменить
23+
Все его функции нужно пройти в цикле `for (const key in fs) { ... }` и заменить
2424
на свою функцию. При помощи замыкания эта функция должна стать универсальной
2525
прослойкой для всех функций библиотеки fs. Смысл обертки - логировать все
2626
вызовы к файловой системе в файл, с указанием времени, имени функции, ее
@@ -29,13 +29,14 @@
2929
несколько шагов.
3030
2. Удаляем из `application.js` вызов таймера и оставляем там только код:
3131

32-
```JavaScript
33-
var fileName = './README.md';
34-
console.log('Application going to read ' + fileName);
35-
fs.readFile(fileName, function(err, src) {
36-
console.log('File ' + fileName + ' size ' + src.length);
37-
});
38-
```
32+
```JavaScript
33+
const fileName = './README.md';
34+
console.log('Application going to read ' + fileName);
35+
fs.readFile(fileName, (err, src) => {
36+
console.log('File ' + fileName + ' size ' + src.length);
37+
});
38+
```
39+
3940
Это пример работы с файлом. И мы будем изменять поведение этого кода.
4041
Убираем из `framework.js` обертку таймера и пробрасываем `fs` в приложение.
4142
Теперь запускаем `node framework` и убеждаемся, что файл считывается и
@@ -44,33 +45,31 @@
4445
ключей из библиотеки `fs` в новый интерфейс и передаем в песочницу не исходный
4546
`fs`, а склонированный. Пример функции клонирования:
4647

47-
```JavaScript
48-
function cloneInterface(anInterface) {
49-
var clone = {};
50-
for (var key in anInterface) {
51-
clone[key] = anInterface[key];
52-
}
53-
return clone;
48+
```JavaScript
49+
const cloneInterface = (anInterface) => {
50+
const clone = {};
51+
for (const key in anInterface) {
52+
clone[key] = anInterface[key];
5453
}
55-
```
54+
return clone;
55+
};
56+
```
57+
5658
4. Пишем функцию `wrapFunction(fnName, fn)` которая оборачивает функцию `fn` и
5759
возвращает функцию-замыкание от `wrapper`. Замыкание, это ссылка на копию
5860
функции `wrapper`, которая замкнута на контекст `wrapFunction`. Таким образом
5961
мы применяем функциональное наследование и порождаем такой вариант `wrapper`,
6062
который видит параметры `fnName` и 'fn' от `wrapFunction`. Мы полностью
6163
передаем все аргументы в функцию fn:
6264

63-
```JavaScript
64-
function wrapFunction(fnName, fn) {
65-
return function wrapper() {
66-
var args = [];
67-
Array.prototype.push.apply(args, arguments);
68-
console.log('Call: ' + fnName);
69-
console.dir(args);
70-
return fn.apply(undefined, args);
71-
}
72-
}
73-
```
65+
```JavaScript
66+
const wrapFunction = (fnName, fn) => (...args) => {
67+
console.log('Call: ' + fnName);
68+
console.dir(args);
69+
return fn(...args);
70+
}
71+
```
72+
7473
5. Определяем, есть ли среди аргументов `callback`, он всегда последний в
7574
массиве аргументов и его тип `function`. Если `callback` есть, то вместо него
7675
передаем свою функцию, которая логирует все аргументы и вызывает настоящий
@@ -99,19 +98,20 @@
9998
и прочитать из нее при помощи `fs.readFile`, потом записать файл, создать и
10099
удалить. Пример структуры:
101100

102-
```JavaScript
103-
var virtualFs = {
104-
folder: {
105-
subfolder: {
106-
file1: 'File content',
107-
file2: 'Another file content'
108-
},
101+
```JavaScript
102+
const virtualFs = {
103+
folder: {
104+
subfolder: {
105+
file1: 'File content',
106+
file2: 'Another file content'
109107
},
110-
notes: {
111-
myToDos: 'Refactor projects, Prepare tests',
112-
meetings: 'Meet thoughts at 10:00 walking along garden'
113-
}
114-
};
115-
```
108+
},
109+
notes: {
110+
myToDos: 'Refactor projects, Prepare tests',
111+
meetings: 'Meet thoughts at 10:00 walking along garden'
112+
}
113+
};
114+
```
115+
116116
9. Реализуйте кеширование файловых операций в памяти.
117117
10. Напишите аналогичный пример на другом языке программирования.

0 commit comments

Comments
 (0)