-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfunctions1.js
365 lines (286 loc) · 9.83 KB
/
functions1.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
// FUNCTIONS
let testString = "I love Netflix";
/*
Functions with NO RETURN:
- just prints values;
- doesn't return anything;
- can't be used further;
*/
const showGreeting = () => {
// tab before code
const text = 'Hello, world!'; // declaring a variable
console.log(text); // printing a variable
}
// function call - function();
showGreeting();
/*
Functions with RETURN:
- we will have an output as a result of function execution;
- this output can be used further in another functions or parts of a code;
- when program sees 'return' it terminates the function execution;
*/
const sumValues = () => {
let number1 = 238;
let number2 = 459;
return number1 + number2;
}
console.log(sumValues() + sumValues()); // using output of a function
const calcValues = () => {
let number1 = 238;
let number2 = 459;
return number1 - number2;
return number1 + number2; // won't be executed, because we have 'return' earlier in the function!
}
console.log(calcValues());
/*
Functions with arguments
*/
// str is argument in this function
const getLastChar = (str) => {
return str[str.length - 1];
};
// to call a function we need to pass an argument: function(argument);
console.log(getLastChar('Hello'));
console.log(getLastChar(testString));
// a and b are arguments in this function
const average = (a, b) => {
return (a + b) / 2;
};
// to call a function with several arguments: function(argument1, argument2, etc.);
console.log(average(1, 5));
console.log(average(1, 2));
// a function to truncate text from the beginning by length and adding '...' in the end;
const truncate = (text, length) => {
const result = `${text.slice(0, length)}...`;
return result;
};
console.log(truncate(testString, 9));
// function raises a number to a power
// by default our base is 2
const pow = (x, base = 2) => {
return x ** base;
};
console.log(pow(3)); // will be 9, because we didn't pass the base value and by default it's 2.
console.log(pow(3, 3)); // will be 27, because we pass the base value '3' and it replaces the default value.
// function to hide card number
// #1 option
const getHiddenCard1 = (cardNumber, stars = 4) => {
const slicedCardNumber = cardNumber.slice(cardNumber.length - 4, cardNumber.length); // slice only 4 last digits
const incrypted = "*".repeat(stars) + slicedCardNumber;
return incrypted;
}
// #2 option
const getHiddenCard2 = (cardNumber, starsCount = 4) => {
const visibleDigitsLine = cardNumber.slice(12); // slice only 12 digits out of 16
return `${'*'.repeat(starsCount)}${visibleDigitsLine}`;
};
console.log(getHiddenCard1("1234567812345678", 4));
console.log(getHiddenCard2("1234567812345678", 4));
// One-line function, what's after => will be returned as an output
const double = (x) => x ** 2; // with one argument
const power = (x, y) => x ** y; // with two arguments
console.log(double(5));
console.log(power(2, 3));
// Function to capitalize only first letter of the word
// Long version
const capitalize1 = (str) => {
const firstLetter = str[0].toUpperCase(); // capitalizing the first letter
const otherLetters = str.slice(1, str.length); // slice the rest of the word
return firstLetter + otherLetters;
}
// One-line version
const capitalize2 = (text) => `${text[0].toUpperCase()}${text.slice(1)}`;
console.log(capitalize1('fortnite'));
console.log(capitalize2('fortnite'));
/*
Predicate functions:
- functions that will return ONLY boolean value;
- should start with is__ or has__;
*/
// Checking age - will return true if age < 1 and false if anything else.
const isInfant = (age) => age <= 1;
console.log(`The person is infant? The answer is ${!isInfant(3)}.`);
console.log(`The person is infant? The answer is ${!isInfant(1)}.`);
/*
By using ! we deny the answer, so:
- of our answer is true - it will be false;
- if our answer is false - it will be true.
*/
// Checking age - will return true if age >= 60 and false if anything else.
const isPensioner = (age) => age >= 60;
console.log(isPensioner("l"));
console.log(isPensioner(18));
// Checking is our greeting for Mister or not. If yes - returns true, if no - returns false.
const isMister = (greeting) => greeting === 'Mister';
console.log(isMister('Baby'));
console.log(isMister('Mister'));
// Checking is phone number international (starts with '+') or not
// Long version
const isInternationalPhone1 = (string) => {
const firstSymbol = string[0];
return firstSymbol === "+";
}
// One-line version
const isInternationalPhone2 = (phone) => phone[0] === '+';
console.log(isInternationalPhone1('+79602223423'));
console.log(isInternationalPhone2('89602223423'));
/* Checking if our password strong or not (depending only on length)
- if passwords' length is more than 8 AND less than 20 - return TRUE
| condition #1 |
- else - return FALSE
*/
const isStrongPassword = (password) => {
const length = password.length;
return length > 8 && length < 20;
};
console.log(isStrongPassword('qwerty'));
console.log(isStrongPassword('qwerty1234'));
console.log(isStrongPassword('zxcvbnmasdfghjkqwertyui'));
/* Checking if our apartment id good by area and location
- if area >= 100 OR (area >= 80 AND located on the Main Street) - return TRUE
|condition #1 | OR | condition #2 |
- else - FALSE
*/
const isGoodApartment = (area, street) => {
const result = area >= 100 || (area >= 80 && street === 'Main Street');
return result;
};
console.log(isGoodApartment(120, 'Queens Street'));
console.log(isGoodApartment(120, 'Main Street'));
console.log(isGoodApartment(80, 'Main Street'));
// Checking if the year is leap or not
const isLeapYear = (year) => {
const result = year % 400 === 0 || (year % 4 === 0) && (year % 100 !== 0);
return result;
}
console.log(isLeapYear(2018));
console.log(isLeapYear(2016));
// Custom function for string reversing
const reverse = (s) => s.split('').reverse().join('');
console.log(reverse('fortnite'));
// Checking if our word is palindrome
const isPalindrome = (word) => reverse(word).toLowerCase() === word.toLowerCase();
console.log(isPalindrome('Wow'));
// Checking if our word is NOT a palindrome using denial (!)
const isNotPalindrome = (word) => !isPalindrome(word);
console.log(isNotPalindrome('Wow'));
/* OR (||) in such code works so:
- it looks through two arguments;
- chooses one that can be converted to TRUE;
- as we know TRUE is 1, FALSE is 0.
*/
console.log(0 || 1); // will return 1, because it stands for TRUE
/* AND (&&) in such code works so:
- it looks through two arguments;
- chooses one that can be converted to FALSE;
- as we know TRUE is 1, FALSE is 0.
*/
console.log(0 && 1); // will return 0, because it stands for FALSE
/*
GENERAL RULES
- 0, ''(nothing/empty), undefined, NaN(Not a Number), null converted to FALSE (so called falsy values);
- everything else converted to TRUE.
*/
// Returning the position of letter if exists or nothing
const getLetter = (text, position) => text[position - 1] || '';
console.log(getLetter('Library', 4));
console.log(getLetter('Library', 15));
// Functions with IF condition
// Guessing if our number is 42 or not
const guessNumber = (number) => {
if (number === 42){
return "You win!";
}
return "Try again!"
}
console.log(guessNumber(42));
console.log(guessNumber(23));
// Checking sentence type
const getTypeOfSentence = (sentence) => {
let sentenceType; // declaring a variable to store answer
if (sentence.endsWith('?')) {
sentenceType = 'Question'; // will return 'Question' if true and store it in the variable
} else {
sentenceType = 'General'; // will return 'General' if false and store it in the variable
}
return `${sentenceType} sentence`;
};
console.log(getTypeOfSentence('Hodor'));
console.log(getTypeOfSentence('Hodor?'));
// Normalizing websites' url
const normalizeUrl = (url) => {
if (url.startsWith('https://')){
return `${url}`;
}
else {
return `https://${url}`;
}
}
console.log(normalizeUrl("google.com"))
console.log(normalizeUrl("https://ai.fi"));
// Checking allies of the house Targaryen
const whoIsThisHouseToTargaryens = (house) => {
if (house === 'Stark' || house === 'Velaryon'){
return 'ally';
}
else if (house === 'Hightower' || house === 'Lannister'){
return 'enemy';
}
else {
return 'neutral';
}
}
console.log(whoIsThisHouseToTargaryens("Velaryon"))
console.log(whoIsThisHouseToTargaryens("Strong"));
/*
Ternary operators
expression ? returns this if true : returns this if false
__ ? __ : ___
*/
// Long version
const abs1 = (number) => {
return number >= 0 ? number : -number;
};
console.log(abs1(10)); // will return 10 because 10 is more than 0
console.log(abs1(-10)); // will return 10 because -10 is less than 0 (--10 = 10)
// One-line version
const abs2 = (number) => (number >= 0 ? number : -number);
console.log(abs2(10)); // will return 10 because 10 is more than 0
console.log(abs2(-10)); // will return 10 because -10 is less than 0 (--10 = 10)
// converting text
// using ordinary logical operators
const convertText1 = (string) => {
if (string === ''){
return '';
}
else if ((string[0] !== string[0].toUpperCase())){
return `${reverse(string)}`;
}
else if (string[0] === string[0].toUpperCase()){
return `${string}`;
}
}
console.log(convertText1(''));
// using ternary operators
const convertText2 = (string) => {
if (string === '') {
return '';
}
const reversable = string[0] !== string[0].toUpperCase();
return reversable ? reverse(string) : string;
};
console.log(convertText2(''));
/*
Function that swaps places in string every 2 consecutive characters.
If the length of the string is odd, then the last character remains in its place.
*/
const encrypt = (str) => {
let result = '';
for (let i = 0; i < str.length; i += 2) {
const nextSymbol = str[i + 1] || '';
result = `${result}${nextSymbol}${str[i]}`;
}
return result;
};
console.log(encrypt('Hello, World!')); // strings' length is odd -> '!' stays in its place;
console.log(encrypt('Dohaeras, Vermithor!')); // strings' length is even;