Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

consequence tasks #68

Merged
merged 82 commits into from
Jun 24, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
82 commits
Select commit Hold shift + click to select a range
bb467ab
before pull
Artem-Bohush Jun 8, 2020
4f2409d
initial
Artem-Bohush Jun 8, 2020
e41eb50
writing consequence doc, very beginning
Artem-Bohush Jun 9, 2020
c13e10c
replacing callback by consequence tutorial not finished
Artem-Bohush Jun 9, 2020
67e0458
Merge branch 'master' of https://github.com/Wandalen/wConsequence int…
Artem-Bohush Jun 10, 2020
69b8a65
replacing callback by consequence tutorial finished, competitorsQue s…
Artem-Bohush Jun 10, 2020
1485967
competitor queue almost finished
Artem-Bohush Jun 10, 2020
2c0e7eb
competitors queue finished
Artem-Bohush Jun 10, 2020
bf52fcf
index expanded, added new conceps and tutorial
Artem-Bohush Jun 10, 2020
0d3f5a0
two kinds of resources not finished
Artem-Bohush Jun 10, 2020
84f5315
two king of resources, progress
Artem-Bohush Jun 11, 2020
a59ca4b
two kinds of resources finished
Artem-Bohush Jun 11, 2020
17088ec
two kinds of resources, minor changes
Artem-Bohush Jun 11, 2020
1108e52
CRLF -> LF, added comments to samples
Artem-Bohush Jun 12, 2020
cbd588a
Inspecting consequence tutorial initial
Artem-Bohush Jun 12, 2020
857161b
Inspecting consequence almost done
Artem-Bohush Jun 12, 2020
6613813
Inspecting consequence tutorial done
Artem-Bohush Jun 12, 2020
2663048
GiveKeepDifference tutorial initial
Artem-Bohush Jun 12, 2020
2f1181e
GiveKeepDifference tutorial, before adding the first sample
Artem-Bohush Jun 12, 2020
e35c89f
GiveKeepDifference tutorial done
Artem-Bohush Jun 12, 2020
3e02e73
sync and deasync consequence tutorial, initial
Artem-Bohush Jun 12, 2020
ff4f04f
Deasynchronizing Consequence tutorial done
Artem-Bohush Jun 12, 2020
92a0650
SynchronizingConsequence tutorial done
Artem-Bohush Jun 12, 2020
88afa65
Resource concept initial
Artem-Bohush Jun 15, 2020
cd95508
Competitor concept done, cconcept and tutorial samples moved
Artem-Bohush Jun 15, 2020
ea3ca94
Competitor concept, summary added
Artem-Bohush Jun 15, 2020
2a2e9cb
Resource concept initial
Artem-Bohush Jun 15, 2020
fbcaf7e
Resource concept almost done
Artem-Bohush Jun 15, 2020
c4a67a1
Resource concept done
Artem-Bohush Jun 15, 2020
ef4f89e
Resource argument initial
Artem-Bohush Jun 15, 2020
e33d9a8
Resource argument concept done
Artem-Bohush Jun 15, 2020
7c4ff2a
ResourceError tutirial initial
Artem-Bohush Jun 15, 2020
4c0889a
Resource Error tutorial done
Artem-Bohush Jun 15, 2020
681a376
Consequence concept initial
Artem-Bohush Jun 15, 2020
8db0d5e
Cosequence concept not finished
Artem-Bohush Jun 15, 2020
8e7946f
typos corrected
Artem-Bohush Jun 15, 2020
01c1915
sleeping barber sample, qqq done
Artem-Bohush Jun 16, 2020
8ff22f9
Consequence concept almost done
Artem-Bohush Jun 16, 2020
40aa91d
Consequence concept done
Artem-Bohush Jun 16, 2020
652e530
Consequence concept done
Artem-Bohush Jun 16, 2020
e92ee0c
Old Bridge task, very beginning
Artem-Bohush Jun 16, 2020
ee0bd10
Old Bringe task, trying to solve
Artem-Bohush Jun 16, 2020
77c6464
Old Bridge task, some bug
Artem-Bohush Jun 16, 2020
8a39329
Old Bridge task, error
Artem-Bohush Jun 17, 2020
60d5639
Old Bridge task, error fixed
Artem-Bohush Jun 17, 2020
1341433
Old Bridge task implemented
Artem-Bohush Jun 17, 2020
12c25af
BuildingH2O task, initial
Artem-Bohush Jun 17, 2020
13e7d60
BuildingH20 task, some idea very beginning
Artem-Bohush Jun 17, 2020
47990fb
BuildingH2O, some progress
Artem-Bohush Jun 17, 2020
65054c6
BuildingH2O task, implemented
Artem-Bohush Jun 17, 2020
c74d692
BuildingH2O task, random deleted
Artem-Bohush Jun 17, 2020
957fb59
BuildingH2O logs task, logs added
Artem-Bohush Jun 17, 2020
dfadcf5
DiningPhilosophers task, initial
Artem-Bohush Jun 17, 2020
3487f7c
DiningPhilosophers task, some preparation
Artem-Bohush Jun 17, 2020
8cfbbb3
DiningPhilosophers task, some progres
Artem-Bohush Jun 18, 2020
f69dd8b
DiningPhilosophers task, implemented
Artem-Bohush Jun 18, 2020
49ba86f
eslint fixes, RiverCrossing task initial
Artem-Bohush Jun 18, 2020
4d9c402
RiverCrossing task, very beginning
Artem-Bohush Jun 18, 2020
f98e4f3
RiverCrossing task, progress
Artem-Bohush Jun 18, 2020
387e65f
RiverCrossing task, pause
Artem-Bohush Jun 18, 2020
5ec19ad
RiverCrossing task, some bug
Artem-Bohush Jun 18, 2020
a42b402
RiverCrossing task, implemented
Artem-Bohush Jun 18, 2020
20883fd
ProducerConsumer task, initial
Artem-Bohush Jun 18, 2020
ad8697d
ProducerConsumer task, almost done
Artem-Bohush Jun 19, 2020
1aa703c
ProducerConsumer task implemented
Artem-Bohush Jun 19, 2020
2ffad71
ReadersWriters task, implemented
Artem-Bohush Jun 19, 2020
ed292c8
OldBridge task, separated into problem and solution
Artem-Bohush Jun 19, 2020
634ba00
Dining Philosophers task, separated into problem and solution
Artem-Bohush Jun 19, 2020
982d129
Producer Consumer task, separated into problem and solution
Artem-Bohush Jun 19, 2020
da0a7de
ReadersWriter task, separated into problem and solution
Artem-Bohush Jun 19, 2020
4bce694
RiverCrossing task, separated into problem and solution
Artem-Bohush Jun 19, 2020
4a5510c
buildingH2O task separated
Artem-Bohush Jun 19, 2020
6d17222
added comments to solutions
Artem-Bohush Jun 19, 2020
11448e8
after pull
Artem-Bohush Jun 20, 2020
c65b021
Cigarette Smoker task, initial
Artem-Bohush Jun 22, 2020
a4a04a2
Cigarette Smoker task, implemented
Artem-Bohush Jun 22, 2020
0586af5
qqq in sample files done
Artem-Bohush Jun 22, 2020
f6c22f2
found useful links for each sync problem
Artem-Bohush Jun 22, 2020
e9416e7
Consequence concept, some improvements
Artem-Bohush Jun 24, 2020
71eb4bd
Competitor concept, some improvements
Artem-Bohush Jun 24, 2020
0fade7a
concepts, little improvements done
Artem-Bohush Jun 24, 2020
1cea8d2
tutorials, little improvements done
Artem-Bohush Jun 24, 2020
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 12 additions & 13 deletions doc/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,24 +5,23 @@

= Concepts

qqq : write concept "Consequence"
qqq : write concept "Competitor"
qqq : write concept "Resource"
qqq : write concept "Resource argument"
qqq : write concept "Resource error"
aaa Artem : done. write concept "Consequence"
aaa Artem : done. write concept "Competitor"
aaa Artem : done. write concept "Resource"
aaa Artem : done. write concept "Resource argument"
aaa Artem : done. write concept "Resource error"

= Tutorials

qqq : write tutorial "Replacing callback by consequence" - use sample
aaa Artem : done. write tutorial "Replacing callback by consequence" - use sample

qqq : write tutorial "Competitors que" - use samples CompetitorsQue*
qqq : write tutorial "Two kind of resources" - use samples ThenCatchFinally*
qqq : write tutorial "Difference between giving and keeping competitors" - use sample GiveKeepDifference
aaa Artem : done. write tutorial "Competitors que" - use samples CompetitorsQue*
aaa Artem : done. write tutorial "Two kind of resources" - use samples ThenCatchFinally*
aaa Artem : done.write tutorial "Difference between giving and keeping competitors" - use sample GiveKeepDifference


qqq : write tutorial "Inspecting consequence" - use test routines toStr/stringify - console.log( consequence ); argumentsGet() resourceGet() competitorsGet()
qqq : write tutorial "Synchronizing consequence" - adjsut and use sample
qqq : write tutorial "Deasynchronizing consequence" - use sample
aaa Artem : done. ....
aaa Artem : done. write tutorial "Inspecting consequence" - use test routines toStr/stringify - console.log( consequence ); argumentsGet() resourceGet() competitorsGet()
aaa Artem : done. write tutorial "Synchronizing consequence" - adjsut and use sample
aaa Artem : done. write tutorial "Deasynchronizing consequence" - use sample

-->
87 changes: 87 additions & 0 deletions doc/ukr/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
# Концепції

<details>
<summary><a href="./concept/Consequence.md#наслідок">
Наслідок
</a></summary>
Це об'єкт синхронізації, який надає ширші можливості при роботі із асинхронним кодом порівняно із нативними засобами JavaScript.
</details>

<details>
<summary><a href="./concept/Competitor.md#конкурент">
Конкурент
</a></summary>
Це рутина-обробник <a href="./concept/Resource.md#ресурс">ресурсів</a>, які передаються у <a href="./concept/Consequence.md#наслідок">наслідок</a>.
</details>

<details>
<summary><a href="./concept/Resource.md#ресурс">
Ресурс
</a></summary>
Це дані, що передаються у <a href="./concept/Consequence.md#наслідок">наслідок</a> для подальшої їх обробки <a href="./concept/Competitor.md#конкурент">конкурентами</a>.
</details>

<details>
<summary><a href="./concept/ResourceArgument.md#ресурс-аргумент">
Ресурс-аргумент
</a></summary>
Це один із двох видів <a href="./concept/Resource.md#ресурс">ресурсів</a>, що передається у <a href="./concept/Consequence.md#наслідок">наслідок</a>.
</details>

<details>
<summary><a href="./concept/ResourceError.md#ресурс-помилка">
Ресурс-помилка
</a></summary>
Це один із двох видів <a href="./concept/Resource.md#ресурс">ресурсів</a>, що передається у <a href="./concept/Consequence.md#наслідок">наслідок</a>.
</details>

# Туторіали

<details>
<summary><a href="./tutorial/ReplacingCallbackByConsequence.md#заміна-callback-функції-на-наслідок">
Заміна callback функції на наслідок
</a></summary>
Як правильно використати <a href="./concept/Consequence.md#наслідок">наслідок</a> у рутинах, що приймають як аргумент callback функцію.
</details>

<details>
<summary><a href="./tutorial/CompetitorsQue.md#черга-конкурентів">
Черга конкурентів
</a></summary>
Що таке черга <a href="./concept/Competitor.md#конкурент">конкурентів</a> <a href="./concept/Consequence.md#наслідок">наслідку</a> та як правильно користуватись рутинами-конкурентами.
</details>

<details>
<summary><a href="./tutorial/TwoKindOfResources.md#два-види-ресурсів">
Два види ресурсів
</a></summary>
Які бувають види <a href="./concept/Resource.md#ресурс">ресурсів</a>, що передаються у <a href="./concept/Consequence.md#наслідок">наслідок</a> та як правильно їх обробляти.
</details>

<details>
<summary><a href="./tutorial/InspectingConsequence.md#інспектування-наслідку">
Інспектування наслідку
</a></summary>
Як правильно перевірити стан <a href="./concept/Consequence.md#наслідок">наслідку</a> та взаємодіяти із його вмістом( <a href="./concept/Resource.md#ресурс">ресурсами</a> і <a href="./concept/Competitor.md#конкурент">конкурентами</a> ) в ході виконання програми.
</details>

<details>
<summary><a href="./tutorial/GiveKeepDifference.md#різниця-між-give-та-keep-конкурентами">
Різниця між 'give' та 'keep' конкурентами
</a></summary>
Коли використовувати <code>'give'</code>, а коли <code>'keep'</code> конкурент.
</details>

<details>
<summary><a href="./tutorial/SynchronizingConsequence.md#синхронізація-наслідку">
Синхронізація наслідку
</a></summary>
Як виконати синхронізацію <a href="./concept/Consequence.md#наслідок">наслідку</a> в синхронному коді.
</details>

<details>
<summary><a href="./tutorial/DeasynchronizingConsequence.md#деасинхронізація-наслідку">
Деасинхронізація наслідку
</a></summary>
Як виконати деасинхронізацію <a href="./concept/Consequence.md#наслідок">наслідку</a> в асинхронному коді.
</details>
72 changes: 72 additions & 0 deletions doc/ukr/concept/Competitor.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
# Конкурент

Це рутина-обробник [ресурсів](./Resource.md#ресурс), які передаються у [наслідок](./Consequence.md#наслідок).

Одним із двох видів даних, що можуть міститись у `наслідку` є `конкуренти`, які потрапляють у [чергу конкурентів](../CompetitorsQue.md#черга-конкурентів) після їх додавання.

По своїй суті, конкурент це об'єкт, що містить велику кількість властивостей різного призначення.
Сама ж рутина-обробник, яку ми самостійно додаємо в чергу конкурентів, записується у поле `competitorRoutine` об'єкта,
що додається у цю чергу в якості `конкурента`.

```js
var con = new _.Consequence();

// .competitorsGet() returns an array of competitors
console.log( con.competitorsGet().length ); // logs: 0

con.then( ( resource ) =>
{
console.log( resource );
return 'new resource from then';
} );

con.thenGive( ( resource ) => console.log( resource ) );

console.log( con.competitorsGet().length ); // logs: 2

con.take( 'my resource' );

console.log( con.competitorsGet().length ); // logs: 0
```

Приклад вище показує ідею взаємодії `ресурсів` та `конкурентів`. Якщо на момент передачі ресурсу у наслідок черга конкурентів(масив)
не порожня, то конкурент під індексом `0` викликається із передачею в нього цього ресурсу. Далі, в залежності від виду,
конкурент або повертає результат, що буде переданий наступному конкуренту для обробки, або завершує ланцюжок обробки.
У прикладі, конкурент `.then()` повинен повернути якийсь результат та передати його наступному конкуренту, а `.thenGive()`
не може цього зробити в принципі. Тому він розташований у черзі останнім.

Важливо пам'ятати, що як тільки конкурент був викликаний і завершив обробку ресурсу - він видаляється із черги конкурентів.
Тому останній вивід показує `0` конкурентів у черзі.

Тепер подивимось, що таке конкурент і перевіримо чи у властивості `competitorRoutine` записана рутина-обробник, яку ми передали
в якості `callback` рутини у `.thenGive()`.

```js
var con = new _.Consequence();

con.thenGive( ( resource ) => console.log( resource ) );
console.log( con.competitorsGet()[ 0 ] ); // logs: { a lot of properties... }

con.competitorsGet()[ 0 ][ 'competitorRoutine' ]( 'from competitorRoutine prop' ); // logs: from competitorRoutine prop
con.take( 'my resource' ); // logs: my resource
```

Важливо розуміти, що поки черга конкурентів не порожня, доти процес не завершиться і наслідок очікуватиме на ресурс, який
буде оброблений тими конкурентами, що залишались у черзі.

```js
var con = new _.Consequence();

con.thenGive( ( resource ) => console.log( resource ) );

// if there is at least one competitor in the queue, the process will not stop, the consequence will be waiting for the resource
console.log( con.competitorsGet().length ); // logs: 1
```

**Підсумок:**
- `конкурент` - це об'єкт, що знаходиться у черзі конкурентів(масиві) та може обробляти переданий у наслідок ресурс;
- обробка ресурсу виконується шляхом передачі його у рутину, яку ми самостійно описуємо, та яка є значенням властивості `competitorRoutine` об'єкта, що є конкурентом;
- після обробки ресурсу `конкурент` видаляється із черги;
- якщо у черзі конкурентів залишається хоча б один конкурент, то процес не завершиться і наслідок очікуватиме на ресурс.

[Повернутись до змісту](../README.md#концепції)
123 changes: 123 additions & 0 deletions doc/ukr/concept/Consequence.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
# Наслідок

Це об'єкт синхронізації, який надає ширші можливості при роботі із асинхронним кодом порівняно із нативними засобами JavaScript.

Клас `Consequence` створює об'єкти, які використовуються для асинхронних обчислень. Ці об'єкти представляють чергу
результатів, які можна обчислити асинхронно, і мають широкий спектр інструментів для виконання цього процесу.
`Наслідок` є сумісним із нативним об'єктом синхронізації `Promise`.

Розглянемо простий приклад використання `наслідку` в асинхронному коді.
```js
// here would be the `async fynction` syntax if using Promise
function foo()
{
var con = new _.Consequence();

_.time.out( 1000, () => con.take( 'my resource' ) );

con.deasync(); // delay execution of .sync() till resource is passed into consequence
return con.sync(); // .sync() retrieves the resource just passed into consequence
}

// here would be the `await foo()` syntax if using Promise
var result = foo();

// after 1 sec we get result
console.log( result ); // my resource
```

Структурно `наслідок` складається із двох черг(масивів):
- [ресурсів](./Resource.md#ресурс);
- [конкурентів](./Competitor.md#конкурент).

Тобто, `наслідок` - це контейнер для даних, якими є `ресурси` та `конкуренти`, що їх обробляють.

```js
var con = new _.Consequence();

console.log( con ); // logs: Consequence:: 0 / 0
```

При конвертації об'єкта `Consequence` в рядок ми побачимо вивід у форматі - `Consequence:: ресурси / конкуренти`.
Кожне із цих двох чисел - це величина черги(довжина масиву) `ресурсів` та `конкурентів`. А значить, число вказує на їхню кількість у черзі.

`Ресурси` і `конкуренти` є об'єктами, що містять у своїх властивостях:
- значення ресурсу, якщо у наслідок додається ресурс;
- тіло рутини-обробника ресурса, якщо у наслідок додається конкурент;
- інші значення.

Детальніше про дослідження вмісту `наслідку` та його зміну описано в туторіалі - [Інспектування наслідку](../tutorial/InspectingConsequence.md#інспектування-наслідку).

Детальніше про `ресурси` та `конкуренти` описано в концепціях - [Ресурс](./Resource.md#ресурс) та [Конкурент](./Competitor.md#конкурент).

Можна спершу додати в чергу ресурси, а потім конкуренти, що їх оброблятимуть, або навпаки. Проте між цими способами є
принципова відмінність в обробці ресурсів.

Перший спосіб - спершу ресурс потім конкурент.
```js
// The `capacity` option indicates the maximum number of resources in the resource queue at a time. By default 1, if 0 - not limited
var con = new _.Consequence({ capacity : 0 });

// .take(resource) - pass resource to the queue
con.take( 'my resource1' );
con.take( 'my resource2' );

console.log( con ); // Consequence:: 2 / 0

// .then(callback), thenGive(callback) - pass competitor to the queue
con.then( ( arg ) =>
{
console.log( 'then: ', arg ); // then: my resource1
return 'new arg from then';
} );

con.thenGive( ( arg ) => console.log( 'thenGive: ', arg ) ); // thenGive: my resource2

console.log( con ); // Consequence:: 1 / 0
```

Приклад вище показує, що:
- додані в `наслідок` ресурси потрапляють у чергу ресурсів та очікують на появу `конкурентів`, що їх оброблятимуть;
- як тільки в чергу конкурентів додається новий `конкурент`, він викликається із передачею в нього першого в черзі ресурса;
- порядок ресурсів у черзі, в ході їх обробки, змінюється.

Другий спосіб - спершу конкурент потім ресурс.
```js
var con = new _.Consequence();

con.then( ( arg ) =>
{
console.log( 'then logs: ', arg );
return 'new arg from then';
} );

con.thenGive( ( arg ) => console.log( 'thenGive logs: ', arg ) );

console.log( con ); // Consequence:: 0 / 2

con.take( 'my resource1' ); // logs: my resource1
con.take( 'my resource2' ); // logs: new arg from then

console.log( con ); // Consequence:: 1 / 0
```

Приклад вище показує, що:
- додані в `наслідок` конкуренти потрапляють у чергу конкурентів та очікують на появу `ресурсів` для їх обробки;
- як тільки в чергу ресурсів передається новий `ресурс`, викликається перший в черзі `конкурент` із передачею в нього цього ресурса;
- після завершення роботи першого `конкурента` викликається наступний із передачею в нього поверненного результату роботи;
- наступний доданий `ресурс` не був оброблений.

Щоб краще зрозуміти особливості поведінки `конкурентів` та їх види, рекомендуємо прочитати туторіал - [Різниця між 'give' та 'keep' конкурентами](../tutorial/GiveKeepDifference.md).

Наслідок може використовуватись як заміна функції-`callback` в синхронних чи асинхронних рутинах.

Детальніше з цим можна ознайомитись у туторіалі - [Заміна callback функції на наслідок](../tutorial/ReplacingCallbackByConsequence.md).

**Підсумок**
- `наслідок` це об'єкт синхронізації;
- `наслідок` є контейнером данних - `ресурсів` та `конкурентів` за ресурси;
- `конкурент` це рутина, у яку передається ресурс;
- можна у будь-якому порядку додавати ресурси та конкуренти, проте поведінка наслідку від цього змінюється;
- різні види `конкурентів` по різному поводяться із чергою ресурсів.

[Повернутись до змісту](../README.md#концепції)
Loading