Skip to content

Commit 14206fc

Browse files
author
Vitalii Telychko
committed
design patterns and paradigms
1 parent 4f083c4 commit 14206fc

Some content is hidden

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

44 files changed

+428
-72
lines changed

codewars/binary_addition.js

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
function addBinary(a,b) {
2+
return (a + b).toString(2).toString();
3+
}
4+
5+
addBinary(4, 5);

codewars/find_the_missing_letter.js

+7
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
// function findMissingLetter(array) {
2+
// let i, string = array.join(''), size = string.length;
3+
// for (i = 0; i < size; i += 1) {
4+
// if(string.charCodeAt(i) !== string.charCodeAt(0) + i) return String.fromCharCode(string.charCodeAt(i) - 1);
5+
// }
6+
// return '';
7+
// }

codewars/junior_level/binary_addition.js

-6
This file was deleted.

codewars/junior_level/find_the_missing_letter.js

-7
This file was deleted.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
function largestDifference(data) {
2+
3+
}
4+
5+
largestDifference([1, 2, 3]);

codewars/next_bigger_number.js

+13
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
function nextBigger(n){
2+
var str = n.toString().split(''), size = str.length, temp;
3+
for(var i = 0; i < size; i += 1) {
4+
if(str[i + 1] > str[i]) {
5+
temp = str[i];
6+
str[i] = str[i + 1];
7+
str[i + 1] = temp;
8+
}
9+
}
10+
return +str.join('');
11+
}
12+
13+
console.log(nextBigger(2017));

codewars/pair_sum_integers.js

+23
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
var sample_data = [0, 1, 100, 99, 0, 10, 90, 30, 55, 33];
2+
3+
function pairsWithSum(sum, data) {
4+
let pairs = [], i = 0, size = data.length, j = size - 1, a, b;
5+
data.sort((a, b) => a - b);
6+
while (i < j && j >= 0) {
7+
a = data[i];
8+
b = data[j];
9+
if (a + b === sum) {
10+
pairs.push([a, b]);
11+
while (i < size && data[i] === a) {
12+
i += 1;
13+
}
14+
while (j >= 0 && data[j] === b) {
15+
j -= 1;
16+
}
17+
} else if (a + b < sum) while(i < size && data[i += 1] === a);
18+
else while(j >= 0 && data[j -= 1] === b);
19+
}
20+
return pairs;
21+
}
22+
23+
pairsWithSum(100, sample_data);

codewars/reverse_it_quickly.js

+2
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
weirdReverse=a=>a.sort((a, b)=>a-b); // a.sort(_=>1);
2+
weirdReverse([5,4,3,2,1]);
File renamed without changes.
File renamed without changes.
Loading

design_patterns/others/MVC.js renamed to design_patterns/architectural/MVC/MVC.js

+4
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,7 @@
1+
// Usually the controller instantiates the view and the model in the constructor or, in certain implementations, are injected by the main application class via dependency injection.
2+
// The relation between a controller and the views could be one to many, so a controller could handle multiple views: the same relationship is valid for the models as well.
3+
// When we want to scale up this architecture for large projects usually we try to split up these relationships in order to have almost a 1 to 1 relation between these three objects so we can reuse components that are self-contained and architected in the same way the entire application works, like a Russian doll.
4+
15
// VIEW
26
var view = {
37
showNumber: function (n) {
+82
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
// The main differences between MVP and MVC could be summarized in the following list:
2+
// Having a presenter instead of a controller, we will see in a moment which benefits come in with a presenter.
3+
// The relation between a view and a presenter is not 1 to many like in MVC but is always 1 to 1.
4+
// The best MVP implementation for having reusable components is when we design our views as passive views because swapping them becomes easier as long the contract between the presenter and the view is respected.
5+
6+
7+
// MODEL
8+
function TaskModel(_text){
9+
var ID = (new Date()).getTime(), Text = _text;
10+
this.getID = function(){
11+
return ID;
12+
};
13+
this.getText = function(){
14+
return Text;
15+
};
16+
this.setText = function(value){
17+
Text = value;
18+
}
19+
}
20+
21+
// VIEW
22+
function TaskView(){
23+
var html;
24+
function init(){
25+
html = $("<input type='checkbox'/><label></label></li>");
26+
}
27+
28+
var public = {
29+
getHtml: function(){
30+
return html;
31+
},
32+
setModel: function(model){
33+
html.find("input").attr("id", model.getID());
34+
html.find("label").attr("for", model.getID());
35+
html.find("label").html(model.getText());
36+
},
37+
addCheckedHandler: function(handler){
38+
html.find("input").click(handler);
39+
},
40+
remove: function(){
41+
html.remove();
42+
}
43+
};
44+
45+
init();
46+
return public;
47+
}
48+
49+
// PRESENTER
50+
function TaskPresenter(_view){
51+
var view, model;
52+
53+
function init(){
54+
view = _view;
55+
view.addCheckedHandler(function(){
56+
view.remove();
57+
});
58+
}
59+
60+
var public = {
61+
getView: function(){
62+
return view;
63+
},
64+
setModel: function(_model){
65+
model = _model;
66+
view.setModel(model);
67+
}
68+
};
69+
70+
init();
71+
return public;
72+
}
73+
74+
75+
// INIT
76+
var model = new TaskModel("Hello world!");
77+
var task = new TaskPresenter(new TaskView());
78+
79+
task.setModel(model);
80+
81+
$("body").append(task.getView().getHtml());
82+

design_patterns/architectural/MVVM.js

Whitespace-only changes.

design_patterns/others/DAO.js

Whitespace-only changes.

design_patterns/others/DTO.js

Whitespace-only changes.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
// Imperative Way
2+
3+
// class Calculator {
4+
// sum(a, b) {
5+
// return a + b;
6+
// }
7+
// }
8+
//
9+
// class Receipt {
10+
// constructor(calculator) {
11+
// this.calc = calculator;
12+
// }
13+
// print(itemA, itemB) {
14+
// const total = this.calc.sum(itemA, itemB);
15+
// console.log(`total receipt $ ${total}`);
16+
// }
17+
// }
18+
//
19+
// const pizza = 6.00, beer = 5.00,
20+
// calc = new Calculator(),
21+
// receipt = new Receipt(calc);
22+
// receipt.print(pizza, beer);
23+
24+
// Reactive Way
25+
26+
// class Calculator {
27+
// constructor(itemA, itemB) {
28+
// const obs = Rx.Observable.of(itemA, itemB);
29+
// const sum = obs.reduce((acc, item) => acc + item);
30+
// return {
31+
// observable: sum
32+
// }
33+
// }
34+
// }
35+
//
36+
// class Receipt {
37+
// constructor(observable$) {
38+
// observable$.subscribe(value => console.log(`total receipt $ ${value}`));
39+
// }
40+
// }
41+
//
42+
// const pizza = 6.00, beer = 5.00,
43+
// calc = new Calculator(pizza, beer),
44+
// receipt = new Receipt(calc.observable);
45+
// receipt.print(pizza, beer);
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
// IoC Container Example
2+
export default class Container {
3+
constructor() {
4+
this._services = new Map();
5+
this._singletons = new Map();
6+
}
7+
register(name, definition, dependencies) {
8+
this._services.set(name, {definition: definition, dependencies: dependencies})
9+
}
10+
11+
singleton(name, definition, dependencies) {
12+
this._services.set(name, {definition: definition, dependencies: dependencies, singleton:true})
13+
}
14+
15+
get(name) {
16+
const c = this._services.get(name);
17+
18+
if(this._isClass(c.definition)) {
19+
20+
if(c.singleton) {
21+
const singletonInstance = this._singletons.get(name);
22+
if(singletonInstance) {
23+
return singletonInstance
24+
} else {
25+
const newSingletonInstance = this._createInstance(c);
26+
this._singletons.set(name, newSingletonInstance);
27+
return newSingletonInstance;
28+
}
29+
}
30+
31+
return this._createInstance(c);
32+
33+
} else {
34+
return c.definition;
35+
}
36+
}
37+
38+
_getResolvedDependencies(service) {
39+
let classDependencies = [];
40+
if(service.dependencies) {
41+
classDependencies = service.dependencies.map((dep) => {
42+
return this.get(dep)
43+
})
44+
}
45+
return classDependencies;
46+
}
47+
48+
_createInstance(service) {
49+
return new service.definition(...this._getResolvedDependencies(service))
50+
}
51+
52+
_isClass(definition) {
53+
return typeof definition === 'function'
54+
}
55+
}

index.html

+3-1
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@
88
</head>
99
<body>
1010

11-
<script src="sorting_algorithms/quicksort.js"></script>
11+
<script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script>
12+
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin></script>
13+
<script src="design_patterns/architectural/MVP/MVP.js"></script>
1214
</body>
1315
</html>
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
Декларати́вное программи́рование — это парадигма программирования, в которой задаётся спецификация решения задачи, то есть описывается, что представляет собой проблема и ожидаемый результат. Противоположностью декларативного является императивное программирование, описывающее на том или ином уровне детализации, как решить задачу и представить результат. В общем и целом, декларативное программирование идёт от человека к машине, тогда как императивное — от машины к человеку. Как следствие, декларативные программы не используют понятия состояния, то есть не содержат переменных и операторов присваивания (см. также ссылочная прозрачность).
2+
Наиболее близким к «чисто декларативному» программированию является написание исполнимых спецификаций (см. соответствие Карри — Ховарда). В этом случае программа представляет собой формальную теорию, а её выполнение является одновременно автоматическим доказательством этой теории, и характерные для императивного программирования составляющие процесса разработки (проектирование, рефакторинг, отладка и др.) в этом случае исключаются: программа проектирует и доказывает сама себя.
3+
К подвидам декларативного программирования также зачастую относят функциональное и логическое программирование — несмотря на то, что программы на таких языках нередко содержат алгоритмические составляющие, архитектура в императивном понимании (как нечто отдельное от кодирования) в них также отсутствует: схема программы является непосредственно частью исполняемого кода[1].
4+
На повышение уровня декларативности нацелено языково-ориентированное программирование.
5+
«Чисто декларативные» компьютерные языки зачастую не полны по Тьюрингу — так как теоретически не всегда возможно порождение исполняемого кода по декларативному описанию. Это иногда приводит к спорам о корректности термина «декларативное программирование» (менее спорным является «декларативное описание решения» или, что то же самое, «декларативное описание задачи»).
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
Императи́вное программи́рование — это парадигма программирования (стиль написания исходного кода компьютерной программы), для которой характерно следующее:
2+
3+
в исходном коде программы записываются инструкции (команды);
4+
инструкции должны выполняться последовательно;
5+
при выполнении инструкции данные, полученные при выполнении предыдущих инструкций, могут читаться из памяти;
6+
данные, полученные при выполнении инструкции, могут записываться в память.
7+
Императивная программа похожа на приказы (англ. imperative — приказ, повелительное наклонение), выражаемые повелительным наклонением в естественных языках, то есть представляют собой последовательность команд, которые должен выполнить компьютер.
8+
9+
При императивном подходе к составлению кода (в отличие от функционального подхода, относящегося к декларативной парадигме) широко используется присваивание. Наличие операторов присваивания увеличивает сложность модели вычислений и делает императивные программы подверженными специфическим ошибкам, не встречающимся при функциональном подходе[1].
10+
11+
Основные черты императивных языков:
12+
13+
использование именованных переменных;
14+
использование оператора присваивания;
15+
использование составных выражений;
16+
использование подпрограмм;
17+
и др.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
// CSP - Communicating Sequential Processes
2+
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
class Calculator {
2+
constructor() {
3+
this.VAT = 22;
4+
}
5+
6+
sum(items) {
7+
const items$ = Rx.Observable.from(items); // inject observable
8+
return items$.map(value => value + (value * this.VAT / 100)).reduce((acc, value) => acc + value); // calculate
9+
}
10+
}
11+
12+
class Receipt {
13+
constructor(calculator) {
14+
this.calc = calculator;
15+
}
16+
17+
print(...items) {
18+
// Observable as an object that is wrapping the data and exposes some methods for manipulating the values
19+
const total$ = this.calc.sum(items); // transforming the arguments to observable and return observable object
20+
total$.subscribe(total => console.log(`total receipt $ ${total.toFixed(2)}`)); // subscribe and show result
21+
}
22+
}
23+
24+
const JEANS = 80.00,
25+
SHIRT = 35.00,
26+
SHOES = 90.00,
27+
COAT = 140.00,
28+
HAT = 29.00;
29+
const calc = new Calculator(),
30+
receipt = new Receipt(calc);
31+
receipt.print(JEANS, SHIRT, SHOES, COAT, HAT);

0 commit comments

Comments
 (0)