unknown пре 3 година
комит
d91ce86803

+ 3 - 0
README.md

@@ -0,0 +1,3 @@
+// to start , create example.ts in directory javascript after that open powershell
+// in directory javascript and write down command "tsc example.ts"
+// to control changes use command tsc "example.ts -w"

+ 0 - 0
html-css/css/styles.css


+ 13 - 0
html-css/index.html

@@ -0,0 +1,13 @@
+<!DOCTYPE html>
+<html lang="en" lang="uk">
+	<head>
+		<meta charset="UTF-8" />
+		<meta name="viewport" content="width=device-width, initial-scale=1.0" />
+		<style hre></style>
+		<title>Document-js</title>
+	</head>
+	<body>
+		<div id="wrapper"></div>
+	</body>
+	<script src="../javascript/homework.js" type="module"></script>
+</html>

+ 168 - 0
javascript/homework.js

@@ -0,0 +1,168 @@
+//ДЗ: Функции и области видимости
+//Анализ
+//Проанализируйте свои предыдущие ДЗ на предмет повторяющихся действий и придумайте названия,
+//параметры и возвращаемое значение для функций в этих случаях
+//Напишите функцию a, которая просто является коротким именем для alert. Смотрите пример
+//с d(), которая является коротким именем для debugger из материала лекции
+function greetings(greetings) {
+    alert(greetings);
+}
+// greetings("Привет!") // вызывает alert("Привет!")
+//cube
+function cube(number) {
+    return Math.pow(number, 3);
+}
+// console.log(cube(2))
+//avg2
+//Напишите функцию avg2, которая рассчитывает среднюю для двух чисел:
+//формула для подсчета среднего: (a + b) / 2
+//напишите функцию тут
+//avg2(1,2) // возвращает 1.5
+//avg2(10,5) // возвращает 7.5
+var avgOfTwo = function (a, b) { return (a + b) / 2; };
+// console.log(avgOfTwo(1,2))
+// console.log(avgOfTwo(10,5))
+//sum3
+//Напишите функцию sum3 для суммирования 3 чисел:
+//Обратите внимание, что sum3 от двух параметров тоже работает корректно. 
+//sum3(1,2,3) // => 6
+//sum3(5,10,100500) // => 100515
+//sum3(5,10) // => 15
+var sumThree = function (a, b, c) {
+    if (a === void 0) { a = 0; }
+    if (b === void 0) { b = 0; }
+    if (c === void 0) { c = 0; }
+    return (a + b + c);
+};
+// console.log(sumThree(1,2,3))
+// console.log(sumThree(5,10,100500))
+// console.log(sumThree(5, 10))
+//intRandom
+//Напишите функцию intRandom, которая принимает два параметра: нижнюю и верхнюю границу, и возвращает целое
+//случайное число из этого диапазона включительно:
+//Обратите внимание, что если передан один параметр (intRandom(10) в примере выше), то функция работает
+//как будто первый параметр равен 0, а переданный параметр становится вторым параметром(intRandom(0, 10))
+//Используйте умножение для расширения значения встроенной функции Math.random c диапозона 1, сложениe для
+//смещения результата на первый параметр, и Math.round для округления результата
+//intRandom(2,15) // возвращает целое случайное число от 2 до 15 (включительно)
+//intRandom(-1,-1) // вернет -1
+//intRandom(0,1) // вернет 0 или 1
+//intRandom(10) // вернет 0 до 10 включительно
+var intRandom = function (min, max) {
+    if (min === void 0) { min = 0; }
+    return Math.round(Math.random() * ((max ? max : min) - (max ? min : 0)) + (max ? min : 0));
+};
+// console.log(intRandom(2,15))
+// console.log(intRandom(-1,-1))
+// console.log(intRandom(0,1))
+// console.log(intRandom(10))
+//greetAll
+//Сделайтей функцию, которая приветствует всех, кто передан в качестве параметров.
+//Вам поможет arguments и for
+//greetAll("Superman") // выводит alert "Hello Superman"
+//greetAll("Superman", "SpiderMan") // выводит alert "Hello Superman, SpiderMan"
+//greetAll("Superman", "SpiderMan", "Captain Obvious") // выводит alert "Hello Superman, SpiderMan, Captain Obvious"
+var greetAllDeclaration = function () {
+    for (var _i = 0, arguments_1 = arguments; _i < arguments_1.length; _i++) {
+        var arg = arguments_1[_i];
+        console.log("Hello darling " + arg + " from function declaration");
+    }
+};
+// greetAllDeclaration("Superman")
+// greetAllDeclaration("Superman", "SpiderMan")
+// greetAllDeclaration("Superman", "SpiderMan", "Captain Obvious")
+var greetAllArrow = function () {
+    var argumentsArr = [];
+    for (var _i = 0; _i < arguments.length; _i++) {
+        argumentsArr[_i] = arguments[_i];
+    }
+    for (var _a = 0, argumentsArr_1 = argumentsArr; _a < argumentsArr_1.length; _a++) {
+        var arg = argumentsArr_1[_a];
+        console.log("Hello darling " + arg + " from arro function");
+    }
+};
+// greetAllArrow("Superman")
+// greetAllArrow("Superman", "SpiderMan")
+// greetAllArrow("Superman", "SpiderMan", "Captain Obvious")
+//sum
+//Напишите функцию sum, которая сумирует любое количество параметров: Используйте псевдомассив 
+//arguments для получения всех параметров, и for для итерирования по нему
+//sum(1) // => 1
+//sum(2) // => 2
+//sum(10,20,40,100) // => 170
+var sumDeclaration = function () {
+    var sum = 0;
+    for (var _i = 0, arguments_2 = arguments; _i < arguments_2.length; _i++) {
+        var arg = arguments_2[_i];
+        sum += arg;
+    }
+    return sum;
+};
+// sumDeclaration(1)
+// sumDeclaration(2)
+// sumDeclaration(10,20,40,100)
+var sumArrow = function () {
+    var argumentsArr = [];
+    for (var _i = 0; _i < arguments.length; _i++) {
+        argumentsArr[_i] = arguments[_i];
+    }
+    var sum = 0;
+    for (var _a = 0, argumentsArr_2 = argumentsArr; _a < argumentsArr_2.length; _a++) {
+        var arg = argumentsArr_2[_a];
+        sum += arg;
+    }
+    return sum;
+};
+// sumArrow(1)
+// sumArrow(2)
+// sumArrow(10,20,40,100)
+//Union
+//Всё предыдущие функции и примеры с ними объедините в функции, которые вызывайте в switch по имени задания:
+var eternalSample = function () {
+    var sample = prompt("Введите название задания");
+    !sample && eternalSample();
+    switch (sample.toLowerCase()) {
+        case "a":
+            greetings('Gorge');
+            break;
+        case "cube":
+            console.log(cube(2));
+            break;
+        case "avg2":
+            console.log(avgOfTwo(1, 2));
+            break;
+        case "sum3":
+            console.log(sumThree(1, 2, 3));
+            break;
+        case "intrandom":
+            console.log(intRandom(2, 15));
+            break;
+        case "greetall":
+            greetAllArrow("Superman", "SpiderMan");
+            break;
+        case "sum":
+            console.log(sumArrow(10, 20, 40, 100));
+            break;
+        default: console.log('Whoopps');
+    }
+    eternalSample();
+};
+// eternalSample()
+//Union declarative
+//made it but withou invoking , belive me id works
+var associativeArr = new Map();
+associativeArr.set("a", greetings);
+associativeArr.set("cube", cube);
+associativeArr.set("avg2", avgOfTwo);
+associativeArr.set("sum3", sumThree);
+associativeArr.set("intrandom", intRandom);
+associativeArr.set("greetall", greetAllArrow);
+associativeArr.set("sum", sumArrow);
+var eternalSampleAssociativeArr = function () {
+    var sample = prompt("Введите название задания");
+    !sample && eternalSampleAssociativeArr();
+    var getValue = associativeArr.get(sample.toLocaleLowerCase());
+    getValue ? console.log(getValue) : console.log('Whoopps>Try again and writy more exat!');
+    eternalSampleAssociativeArr();
+};
+// eternalSampleAssociativeArr()

+ 168 - 0
javascript/homework.ts

@@ -0,0 +1,168 @@
+//ДЗ: Функции и области видимости
+//Анализ
+//Проанализируйте свои предыдущие ДЗ на предмет повторяющихся действий и придумайте названия,
+//параметры и возвращаемое значение для функций в этих случаях
+//Напишите функцию a, которая просто является коротким именем для alert. Смотрите пример
+//с d(), которая является коротким именем для debugger из материала лекции
+function greetings(greetings:string) {
+	alert(greetings)
+}
+// greetings("Привет!") // вызывает alert("Привет!")
+//cube
+
+function cube(number: number) {
+	return Math.pow(number,3)
+}
+
+// console.log(cube(2))
+
+//avg2
+//Напишите функцию avg2, которая рассчитывает среднюю для двух чисел:
+//формула для подсчета среднего: (a + b) / 2
+//напишите функцию тут
+//avg2(1,2) // возвращает 1.5
+//avg2(10,5) // возвращает 7.5
+const avgOfTwo = (a: number, b: number) => (a + b) / 2
+// console.log(avgOfTwo(1,2))
+// console.log(avgOfTwo(10,5))
+
+//sum3
+//Напишите функцию sum3 для суммирования 3 чисел:
+//Обратите внимание, что sum3 от двух параметров тоже работает корректно. 
+//sum3(1,2,3) // => 6
+//sum3(5,10,100500) // => 100515
+//sum3(5,10) // => 15
+const sumThree = (a: number = 0, b: number = 0, c: number = 0) => (a + b + c)
+// console.log(sumThree(1,2,3))
+// console.log(sumThree(5,10,100500))
+// console.log(sumThree(5, 10))
+
+//intRandom
+//Напишите функцию intRandom, которая принимает два параметра: нижнюю и верхнюю границу, и возвращает целое
+//случайное число из этого диапазона включительно:
+//Обратите внимание, что если передан один параметр (intRandom(10) в примере выше), то функция работает
+//как будто первый параметр равен 0, а переданный параметр становится вторым параметром(intRandom(0, 10))
+//Используйте умножение для расширения значения встроенной функции Math.random c диапозона 1, сложениe для
+//смещения результата на первый параметр, и Math.round для округления результата
+//intRandom(2,15) // возвращает целое случайное число от 2 до 15 (включительно)
+//intRandom(-1,-1) // вернет -1
+//intRandom(0,1) // вернет 0 или 1
+//intRandom(10) // вернет 0 до 10 включительно
+
+const intRandom = (min: number = 0, max?: number) =>
+	Math.round(Math.random() * ((max ? max : min) - (max ? min : 0)) + (max ? min : 0))
+
+// console.log(intRandom(2,15))
+// console.log(intRandom(-1,-1))
+// console.log(intRandom(0,1))
+// console.log(intRandom(10))
+
+//greetAll
+//Сделайтей функцию, которая приветствует всех, кто передан в качестве параметров.
+//Вам поможет arguments и for
+//greetAll("Superman") // выводит alert "Hello Superman"
+//greetAll("Superman", "SpiderMan") // выводит alert "Hello Superman, SpiderMan"
+//greetAll("Superman", "SpiderMan", "Captain Obvious") // выводит alert "Hello Superman, SpiderMan, Captain Obvious"
+
+const greetAllDeclaration = function () {
+	for (const arg of arguments) {
+		console.log(`Hello darling ${arg} from function declaration`)
+	}
+}
+// greetAllDeclaration("Superman")
+// greetAllDeclaration("Superman", "SpiderMan")
+// greetAllDeclaration("Superman", "SpiderMan", "Captain Obvious")
+
+const greetAllArrow = function (...argumentsArr:string[]) {
+	for (const arg of argumentsArr) {
+		console.log(`Hello darling ${arg} from arro function`)
+	}
+}
+// greetAllArrow("Superman")
+// greetAllArrow("Superman", "SpiderMan")
+// greetAllArrow("Superman", "SpiderMan", "Captain Obvious")
+
+//sum
+//Напишите функцию sum, которая сумирует любое количество параметров: Используйте псевдомассив 
+//arguments для получения всех параметров, и for для итерирования по нему
+//sum(1) // => 1
+//sum(2) // => 2
+//sum(10,20,40,100) // => 170
+const sumDeclaration = function () {
+	let sum = 0;
+	for(const arg of arguments ){
+		sum +=arg
+	}
+	return sum
+}
+
+// sumDeclaration(1)
+// sumDeclaration(2)
+// sumDeclaration(10,20,40,100)
+
+const sumArrow = function (...argumentsArr:number[]) {
+	let sum = 0;
+	for(const arg of argumentsArr ){
+		sum +=arg
+	}
+	return sum
+}
+
+// sumArrow(1)
+// sumArrow(2)
+// sumArrow(10,20,40,100)
+
+//Union
+//Всё предыдущие функции и примеры с ними объедините в функции, которые вызывайте в switch по имени задания:
+
+
+
+
+
+const eternalSample = () => {
+	const sample = prompt("Введите название задания")
+	!sample&&eternalSample()
+switch (sample.toLowerCase()){
+	case "a": greetings('Gorge')
+		break;
+	case "cube": console.log(cube(2))
+		break;
+	case "avg2": console.log(avgOfTwo(1, 2))
+		break;
+	case "sum3": console.log(sumThree(1, 2, 3))
+		break;
+	case "intrandom": console.log(intRandom(2, 15))
+		break;
+	case "greetall": greetAllArrow("Superman", "SpiderMan")
+		break;
+	case "sum": console.log(sumArrow(10, 20, 40, 100))
+		break;
+	default: console.log('Whoopps');
+	}
+	eternalSample()
+}
+// eternalSample()
+
+//Union declarative
+//made it but withou invoking , belive me id works
+const associativeArr = new Map()
+associativeArr.set("a",greetings)
+associativeArr.set("cube",cube)
+associativeArr.set("avg2",avgOfTwo)
+associativeArr.set("sum3",sumThree)
+associativeArr.set("intrandom",intRandom)
+associativeArr.set("greetall",greetAllArrow)
+associativeArr.set("sum", sumArrow)
+
+const eternalSampleAssociativeArr = () => {
+	const sample = prompt("Введите название задания")
+	!sample && eternalSampleAssociativeArr()
+	const getValue = associativeArr.get(sample.toLocaleLowerCase())
+	getValue ?console.log(getValue):console.log('Whoopps>Try again and writy more exat!');
+	eternalSampleAssociativeArr()
+}
+
+// eternalSampleAssociativeArr()
+
+
+

+ 21 - 0
tsconfig.json

@@ -0,0 +1,21 @@
+{
+    "compileOnSave": false,
+    "compilerOptions": {
+        "baseUrl": "./",
+        "rootDir": "./javascript",
+        "outDir": "./dist/out-tsc",
+        "sourceMap": true,
+        "declaration": false,
+        "moduleResolution": "node",
+        "emitDecoratorMetadata": true,
+        "experimentalDecorators": true,
+        "target": "es2017",
+        "typeRoots": [
+            "node_modules/@types"
+        ],
+        "lib": [
+            "es2017",
+            "dom"
+        ]
+    }
+}

+ 37 - 0
websockets/.gitignore

@@ -0,0 +1,37 @@
+# Logs
+logs
+*.log
+npm-debug.log*
+
+# Runtime data
+pids
+*.pid
+*.seed
+
+# Directory for instrumented libs generated by jscoverage/JSCover
+lib-cov
+
+# Coverage directory used by tools like istanbul
+coverage
+
+# nyc test coverage
+.nyc_output
+
+# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
+.grunt
+
+# node-waf configuration
+.lock-wscript
+
+# Compiled binary addons (http://nodejs.org/api/addons.html)
+build/Release
+
+# Dependency directories
+node_modules
+jspm_packages
+
+# Optional npm cache directory
+.npm
+
+# Optional REPL history
+.node_repl_history

+ 2 - 0
websockets/README.md

@@ -0,0 +1,2 @@
+# websockets-playlist
+All the course files for the WebSockets playlist on The Net Ninja YouTube channel.

+ 30 - 0
websockets/index.js

@@ -0,0 +1,30 @@
+var express = require('express');
+var socket = require('socket.io');
+
+// App setup
+var app = express();
+var server = app.listen(4000, function(){
+    console.log('listening for requests on port 4000,');
+});
+
+// Static files
+app.use(express.static('public'));
+
+// Socket setup & pass server
+var io = socket(server);
+io.on('connection', (socket) => {
+
+    console.log('made socket connection', socket.id);
+
+    // Handle chat event
+    socket.on('chat', function(data){
+        // console.log(data);
+        io.sockets.emit('chat', data);
+    });
+
+    // Handle typing event
+    socket.on('typing', function(data){
+        socket.broadcast.emit('typing', data);
+    });
+
+});

Разлика између датотеке није приказан због своје велике величине
+ 6188 - 0
websockets/package-lock.json


+ 26 - 0
websockets/package.json

@@ -0,0 +1,26 @@
+{
+  "name": "websockets-playlist",
+  "version": "1.0.0",
+  "description": "A chat app using WebSockets",
+  "main": "index.js",
+  "scripts": {
+    "test": "echo \"Error: no test specified\" && exit 1"
+  },
+  "repository": {
+    "type": "git",
+    "url": "git+https://github.com/iamshaunjp/websockets-playlist.git"
+  },
+  "author": "The Net Ninja",
+  "license": "ISC",
+  "bugs": {
+    "url": "https://github.com/iamshaunjp/websockets-playlist/issues"
+  },
+  "homepage": "https://github.com/iamshaunjp/websockets-playlist#readme",
+  "dependencies": {
+    "express": "^4.15.2",
+    "socket.io": "^1.7.3"
+  },
+  "devDependencies": {
+    "nodemon": "^1.11.0"
+  }
+}

+ 33 - 0
websockets/public/chat.js

@@ -0,0 +1,33 @@
+// Make connection
+var socket = io.connect('http://localhost:4000');
+
+// Query DOM
+var message = document.getElementById('message'),
+	nickName = document.getElementById('nick'),
+	btn = document.getElementById('send'),
+	output = document.getElementById('output'),
+	feedback = document.getElementById('feedback');
+
+// Emit events
+btn.addEventListener('click', function () {
+	socket.emit('chat', {
+		message: message.value,
+		nickName: nickName.value,
+	});
+	message.value = '';
+});
+
+message.addEventListener('keypress', function () {
+	socket.emit('typing', nickName.value);
+});
+
+// Listen for events
+socket.on('chat', function (data) {
+	feedback.innerHTML = '';
+	output.innerHTML +=
+		'<p><strong>' + data.nickName + ': </strong>' + data.message + '</p>';
+});
+
+socket.on('typing', function (data) {
+	feedback.innerHTML = '<p><em>' + data + ' is typing a message...</em></p>';
+});

+ 22 - 0
websockets/public/index.html

@@ -0,0 +1,22 @@
+<!DOCTYPE html>
+<html>
+	<head>
+		<meta charset="utf-8" />
+		<title>WebScockets 101</title>
+		<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.7.3/socket.io.js"></script>
+		<link href="/styles.css" rel="stylesheet" />
+	</head>
+	<body>
+		<div>
+			<h2>Nix Chat</h2>
+			<div id="chat-window">
+				<div id="output"></div>
+				<div id="feedback"></div>
+			</div>
+			<input id="nick" type="text" placeholder="Nick" />
+			<input id="message" type="text" placeholder="Message" />
+			<button id="send">Send</button>
+		</div>
+	</body>
+	<script src="/chat.js"></script>
+</html>

+ 69 - 0
websockets/public/styles.css

@@ -0,0 +1,69 @@
+body{
+    font-family: 'Nunito';
+}
+
+h2{
+    font-size: 18px;
+    padding: 10px 20px;
+    color: #575ed8;
+}
+
+#mario-chat{
+    max-width: 600px;
+    margin: 30px auto;
+    border: 1px solid #ddd;
+    box-shadow: 1px 3px 5px rgba(0,0,0,0.05);
+    border-radius: 2px;
+}
+
+#chat-window{
+    height: 400px;
+    overflow: auto;
+    background: #f9f9f9;
+}
+
+#output p{
+    padding: 14px 0px;
+    margin: 0 20px;
+    border-bottom: 1px solid #e9e9e9;
+    color: #555;
+}
+
+#feedback p{
+    color: #aaa;
+    padding: 14px 0px;
+    margin: 0 20px;
+}
+
+#output strong{
+    color: #575ed8;
+}
+
+label{
+    box-sizing: border-box;
+    display: block;
+    padding: 10px 20px;
+}
+
+input{
+    padding: 10px 20px;
+    box-sizing: border-box;
+    background: #eee;
+    border: 0;
+    display: block;
+    width: 100%;
+    background: #fff;
+    border-bottom: 1px solid #eee;
+    font-family: Nunito;
+    font-size: 16px;
+}
+
+button{
+    background: #575ed8;
+    color: #fff;
+    font-size: 18px;
+    border: 0;
+    padding: 12px 0;
+    width: 100%;
+    border-radius: 0 0 2px 2px;
+}