From aff831563ecdc3ec802bd8ab71418b9df6f419d4 Mon Sep 17 00:00:00 2001 From: Siarhei Kalamiyets <34492748+Shagoysai@users.noreply.github.com> Date: Thu, 10 Jun 2021 16:57:52 +0300 Subject: [PATCH 01/40] Update the links --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index a81b5c08a..2bd66d216 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,5 @@ -[](http://brest.rollingscopes.com/) -#Brest Rolling Scopes School +[](http://brest.rollingscopes.com/) +#Brest Shagoysai School ## Javascript Assignments [](https://travis-ci.org/rolling-scopes-school/js-assignments) Yet another javascript assignments. There are a lot of interactive javascript resources for beginners, but most of them are online and do not cover the modern programming workflow. There are some excellent training resources on github (https://github.com/rmurphey/js-assessment, https://github.com/mrdavidlaing/javascript-koans, https://github.com/vasanthk/js-bits etc) but they are not exactly simulate the everyday programming process. So the motivation of this project is to show TDD process in the wild to the beginners. Assingment tests are implemented in various ways to feel a difference and gain the experience what manner is good, what is bad and what is ugly. From 6aa39cf36c95d6972f7f46a7ef47cfccd16b0061 Mon Sep 17 00:00:00 2001 From: Siarhei Kalamiyets <34492748+Shagoysai@users.noreply.github.com> Date: Thu, 10 Jun 2021 17:02:13 +0300 Subject: [PATCH 02/40] Update the links --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 2bd66d216..917524b39 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ [](http://brest.rollingscopes.com/) #Brest Shagoysai School -## Javascript Assignments [](https://travis-ci.org/rolling-scopes-school/js-assignments) +## Javascript Assignments [](https://travis-ci.org/Shagoysai/js-assignments) Yet another javascript assignments. There are a lot of interactive javascript resources for beginners, but most of them are online and do not cover the modern programming workflow. There are some excellent training resources on github (https://github.com/rmurphey/js-assessment, https://github.com/mrdavidlaing/javascript-koans, https://github.com/vasanthk/js-bits etc) but they are not exactly simulate the everyday programming process. So the motivation of this project is to show TDD process in the wild to the beginners. Assingment tests are implemented in various ways to feel a difference and gain the experience what manner is good, what is bad and what is ugly. @@ -22,14 +22,14 @@ To start javascript assignments please follow the next steps: ### How to setup travis-ci * Open [https://travis-ci.org/](https://travis-ci.org/) and sign in with your github account. * Activate your forked repo **js-assignments**. -* Edit local README.md file and update all links (just replace all occurrences of `'rolling-scopes-school'` with your account name). +* Edit local README.md file and update all links (just replace all occurrences of `'Shagoysai'` with your account name). * Commit and push updated README.md to github: ```bash git add README.md git commit -m "Update the links" git push origin master ``` -* Open https://github.com/rolling-scopes-school/js-assignments and test the build icon. Now it will run all tests and update status once you push changes to github. Keep this icon green! +* Open https://github.com/Shagoysai/js-assignments and test the build icon. Now it will run all tests and update status once you push changes to github. Keep this icon green! ### How to setup work environment @@ -73,7 +73,7 @@ and run the unit tests again. Find one test failed (red). Now it's time to fix i * Implement the function by any way and verify your solution by running tests until the failed test become passed (green). * Your solution work, but now time to refactor it. Try to make your code as pretty and simple as possible keeping up the test green. * Once you can't improve your code and tests are passed you can commit your solution. -* Push your updates to github server and check if tests passed on [travis-ci](https://travis-ci.org/rolling-scopes-school/js-assignments/builds). +* Push your updates to github server and check if tests passed on [travis-ci](https://travis-ci.org/Shagoysai/js-assignments/builds). * If everything is OK you can try to resolve the next task. ### How to debug tasks From 65b35c5e283cf106c4d51c18d8dd50734f9dd81a Mon Sep 17 00:00:00 2001 From: Shagoysai <34492748+Shagoysai@users.noreply.github.com> Date: Thu, 10 Jun 2021 17:20:24 +0300 Subject: [PATCH 03/40] Update .travis.yml another version of node js --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 008cbc167..afd0508c9 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,3 +1,3 @@ language: node_js node_js: - - "5.10.0" + - "14.17.0" From d2f1c19eca15f9c8c11a7d0d6624899ad490695b Mon Sep 17 00:00:00 2001 From: Siarhei Kalamiyets <34492748+Shagoysai@users.noreply.github.com> Date: Thu, 10 Jun 2021 17:26:30 +0300 Subject: [PATCH 04/40] Update .travis.yml --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 008cbc167..afd0508c9 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,3 +1,3 @@ language: node_js node_js: - - "5.10.0" + - "14.17.0" From bcf15c4afd64e1eb46efc13698827044337b6ab0 Mon Sep 17 00:00:00 2001 From: Shagoysai <34492748+Shagoysai@users.noreply.github.com> Date: Thu, 10 Jun 2021 17:53:39 +0300 Subject: [PATCH 05/40] Task1 Done --- task/01-strings-tasks.js | 62 +++++++++++++++++++++++++++++----------- 1 file changed, 46 insertions(+), 16 deletions(-) diff --git a/task/01-strings-tasks.js b/task/01-strings-tasks.js index e28054657..600f8f3c3 100644 --- a/task/01-strings-tasks.js +++ b/task/01-strings-tasks.js @@ -22,7 +22,7 @@ * '', 'bb' => 'bb' */ function concatenateStrings(value1, value2) { - throw new Error('Not implemented'); + return value1.concat(value2) } @@ -38,7 +38,7 @@ function concatenateStrings(value1, value2) { * '' => 0 */ function getStringLength(value) { - throw new Error('Not implemented'); + return value.length; } /** @@ -55,7 +55,7 @@ function getStringLength(value) { * 'Chuck','Norris' => 'Hello, Chuck Norris!' */ function getStringFromTemplate(firstName, lastName) { - throw new Error('Not implemented'); + return "Hello, " +firstName+ ' '+lastName+'!'; } /** @@ -69,7 +69,7 @@ function getStringFromTemplate(firstName, lastName) { * 'Hello, Chuck Norris!' => 'Chuck Norris' */ function extractNameFromTemplate(value) { - throw new Error('Not implemented'); + return value.slice(7, -1); } @@ -84,7 +84,7 @@ function extractNameFromTemplate(value) { * 'cat' => 'c' */ function getFirstChar(value) { - throw new Error('Not implemented'); + return value.substring(0,1); } /** @@ -99,8 +99,7 @@ function getFirstChar(value) { * '\tHello, World! ' => 'Hello, World!' */ function removeLeadingAndTrailingWhitespaces(value) { - throw new Error('Not implemented'); -} + return value.trim(); /** * Returns a string that repeated the specified number of times. @@ -114,7 +113,7 @@ function removeLeadingAndTrailingWhitespaces(value) { * 'cat', 3 => 'catcatcat' */ function repeatString(value, count) { - throw new Error('Not implemented'); + return value.repeat(count) } /** @@ -130,7 +129,7 @@ function repeatString(value, count) { * 'ABABAB','BA' => 'ABAB' */ function removeFirstOccurrences(str, value) { - throw new Error('Not implemented'); + return str.replace(value, ''); } /** @@ -145,7 +144,7 @@ function removeFirstOccurrences(str, value) { * '<a>' => 'a' */ function unbracketTag(str) { - throw new Error('Not implemented'); + return str.slice(1, str.length-1); } @@ -160,7 +159,7 @@ function unbracketTag(str) { * 'abcdefghijklmnopqrstuvwxyz' => 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' */ function convertToUpperCase(str) { - throw new Error('Not implemented'); + return str.toUpperCase(); } /** @@ -174,7 +173,7 @@ function convertToUpperCase(str) { * 'info@gmail.com' => ['info@gmail.com'] */ function extractEmails(str) { - throw new Error('Not implemented'); + return str.split(';'); } /** @@ -201,7 +200,14 @@ function extractEmails(str) { * */ function getRectangleString(width, height) { - throw new Error('Not implemented'); + var horizontal = '─'; + var vertical = '│'; + var breakline = '\n'; + var space = ' '; + + return '┌' + horizontal.repeat(width - 2) + '┐' + breakline + + (vertical + space.repeat(width - 2) + vertical + breakline).repeat(height - 2) + + '└' + horizontal.repeat(width - 2) + '┘' + breakline; } @@ -221,7 +227,25 @@ function getRectangleString(width, height) { * */ function encodeToRot13(str) { - throw new Error('Not implemented'); + var amount = 13 + var output = "" + + for (var i = 0; i < str.length; i++) { + var c = str[i] + if (c.match(/[a-z]/i)) { + var code = str.charCodeAt(i) + + if (code >= 65 && code <= 90) { + c = String.fromCharCode(((code - 65 + amount) % 26) + 65) + } + else if (code >= 97 && code <= 122) { + c = String.fromCharCode(((code - 97 + amount) % 26) + 97) + } + } + output += c + } + + return output } /** @@ -238,7 +262,7 @@ function encodeToRot13(str) { * isString(new String('test')) => true */ function isString(value) { - throw new Error('Not implemented'); + return typeof value === 'string' || value instanceof String; } @@ -267,7 +291,13 @@ function isString(value) { * 'K♠' => 51 */ function getCardId(value) { - throw new Error('Not implemented'); + const cards = [ + 'A♣','2♣','3♣','4♣','5♣','6♣','7♣','8♣','9♣','10♣','J♣','Q♣','K♣', + 'A♦','2♦','3♦','4♦','5♦','6♦','7♦','8♦','9♦','10♦','J♦','Q♦','K♦', + 'A♥','2♥','3♥','4♥','5♥','6♥','7♥','8♥','9♥','10♥','J♥','Q♥','K♥', + 'A♠','2♠','3♠','4♠','5♠','6♠','7♠','8♠','9♠','10♠','J♠','Q♠','K♠' + ]; + return cards.indexOf(value); } From 06859dff85da9f35c6368967da492e5e59e91cff Mon Sep 17 00:00:00 2001 From: Shagoysai <34492748+Shagoysai@users.noreply.github.com> Date: Thu, 10 Jun 2021 17:59:01 +0300 Subject: [PATCH 06/40] Task2 Done --- task/02-numbers-tasks.js | 34 ++++++++++++++++++++++------------ 1 file changed, 22 insertions(+), 12 deletions(-) diff --git a/task/02-numbers-tasks.js b/task/02-numbers-tasks.js index c9ed20208..cbdcb43a7 100644 --- a/task/02-numbers-tasks.js +++ b/task/02-numbers-tasks.js @@ -22,7 +22,7 @@ * 5, 5 => 25 */ function getRectangleArea(width, height) { - throw new Error('Not implemented'); + return width * height; } @@ -38,7 +38,7 @@ function getRectangleArea(width, height) { * 0 => 0 */ function getCicleCircumference(radius) { - throw new Error('Not implemented'); + return Math.PI * radius * 2; } /** @@ -54,7 +54,7 @@ function getCicleCircumference(radius) { * -3, 3 => 0 */ function getAverage(value1, value2) { - throw new Error('Not implemented'); + return value1/2 + value2/2; } /** @@ -73,7 +73,9 @@ function getAverage(value1, value2) { * (-5,0) (10,-10) => 18.027756377319946 */ function getDistanceBetweenPoints(x1, y1, x2, y2) { - throw new Error('Not implemented'); + var a = x1 - x2; + var b = y1 - y2; + return Math.sqrt(a*a + b*b) } /** @@ -89,7 +91,7 @@ function getDistanceBetweenPoints(x1, y1, x2, y2) { * 5*x = 0 => 0 */ function getLinearEquationRoot(a, b) { - throw new Error('Not implemented'); + return -b / a; } @@ -111,7 +113,11 @@ function getLinearEquationRoot(a, b) { * (0,1) (1,2) => 0 */ function getAngleBetweenVectors(x1, y1, x2, y2) { - throw new Error('Not implemented'); + var angle = Math.atan2(y2, x2) - Math.atan2(y1, x1) + if (angle < 0) { + angle += 2 * Math.PI; + } + return angle } /** @@ -127,7 +133,7 @@ function getAngleBetweenVectors(x1, y1, x2, y2) { * 0 => 0 */ function getLastDigit(value) { - throw new Error('Not implemented'); + return value % 10; } @@ -143,7 +149,7 @@ function getLastDigit(value) { * '-525.5' => -525.5 */ function parseNumberFromString(value) { - throw new Error('Not implemented'); + return Number(value) } /** @@ -160,7 +166,7 @@ function parseNumberFromString(value) { * 1,2,3 => 3.741657386773941 */ function getParallelipidedDiagonal(a,b,c) { - throw new Error('Not implemented'); + return Math.sqrt(a * a + b * b + c * c); } /** @@ -181,7 +187,7 @@ function getParallelipidedDiagonal(a,b,c) { * 1678, 3 => 2000 */ function roundToPowerOfTen(num, pow) { - throw new Error('Not implemented'); + return Math.round(num / Math.pow(10, pow)) * Math.pow(10, pow); } /** @@ -202,7 +208,11 @@ function roundToPowerOfTen(num, pow) { * 17 => true */ function isPrime(n) { - throw new Error('Not implemented'); + for (let i = 2; i < n / 2 + 1; i++) { + if (n % i == 0) + return false; + } + return true; } /** @@ -221,7 +231,7 @@ function isPrime(n) { * toNumber(new Number(42), 0) => 42 */ function toNumber(value, def) { - throw new Error('Not implemented'); + return typeof +value == 'number' && !isNaN(+value) ? +value : def; } module.exports = { From 09cddaa81da086b37ff27c97446ad9dea0c1ddb6 Mon Sep 17 00:00:00 2001 From: Shagoysai <34492748+Shagoysai@users.noreply.github.com> Date: Thu, 10 Jun 2021 18:00:37 +0300 Subject: [PATCH 07/40] Task3 Done --- task/03-date-tasks.js | 26 ++++++++++++++++++++------ 1 file changed, 20 insertions(+), 6 deletions(-) diff --git a/task/03-date-tasks.js b/task/03-date-tasks.js index 83c6266bc..a5dcb3557 100644 --- a/task/03-date-tasks.js +++ b/task/03-date-tasks.js @@ -22,7 +22,7 @@ * 'Sun, 17 May 1998 03:00:00 GMT+01' => Date() */ function parseDataFromRfc2822(value) { - throw new Error('Not implemented'); + return Date.parse(value) } /** @@ -37,7 +37,7 @@ function parseDataFromRfc2822(value) { * '2016-01-19T08:07:37Z' => Date() */ function parseDataFromIso8601(value) { - throw new Error('Not implemented'); + return Date.parse(value) } @@ -56,7 +56,10 @@ function parseDataFromIso8601(value) { * Date(2015,1,1) => false */ function isLeapYear(date) { - throw new Error('Not implemented'); + var year = date.getFullYear() + if (year % 400 === 0) return true + if (year % 100 === 0) return false + return year % 4 === 0 } @@ -76,14 +79,14 @@ function isLeapYear(date) { * Date(2000,1,1,10,0,0), Date(2000,1,1,15,20,10,453) => "05:20:10.453" */ function timeSpanToString(startDate, endDate) { - throw new Error('Not implemented'); + return (new Date(endDate - startDate)).toISOString().slice(11, -1); } /** * Returns the angle (in radians) between the hands of an analog clock for the specified Greenwich time. * If you have problem with solution please read: https://en.wikipedia.org/wiki/Clock_angle_problem - * + * * @param {date} date * @return {number} * @@ -94,7 +97,18 @@ function timeSpanToString(startDate, endDate) { * Date.UTC(2016,3,5,21, 0) => Math.PI/2 */ function angleBetweenClockHands(date) { - throw new Error('Not implemented'); + let hour = date.getUTCHours(); + if (hour > 12) { + hour -= 12; + } + let minutes = date.getUTCMinutes(); + let hours = 0.5 * (60 * hour + minutes); + minutes *= 6; + let diff = hours - minutes; + if (diff > 180) { + diff -= 180; + } + return Math.PI * Math.abs(diff) / 180; } From 4fcff37d9efba85905db9922a76bd838d388b88b Mon Sep 17 00:00:00 2001 From: Shagoysai <34492748+Shagoysai@users.noreply.github.com> Date: Thu, 10 Jun 2021 18:01:50 +0300 Subject: [PATCH 08/40] Update 04-arrays-tasks.js --- task/04-arrays-tasks.js | 424 ++++++++++++++++++++++++---------------- 1 file changed, 259 insertions(+), 165 deletions(-) diff --git a/task/04-arrays-tasks.js b/task/04-arrays-tasks.js index ff3a4c019..75a9bbb7e 100644 --- a/task/04-arrays-tasks.js +++ b/task/04-arrays-tasks.js @@ -9,257 +9,282 @@ * * *********************************************************************************************/ - + /** * Returns an index of the specified element in array or -1 if element is not found - * + * * @param {array} arr * @param {any} value * @return {number} - * + * * @example - * ['Ace', 10, true], 10 => 1 - * ['Array', 'Number', 'string'], 'Date' => -1 + * ['Ace', 10, true], 10 => 1 + * ['Array', 'Number', 'string'], 'Date' => -1 * [0, 1, 2, 3, 4, 5], 5 => 5 */ function findElement(arr, value) { - throw new Error('Not implemented'); + return arr.indexOf(value); } /** * Generates an array of odd numbers of the specified length - * + * * @param {number} len * @return {array} - * + * * @example - * 1 => [ 1 ] - * 2 => [ 1, 3 ] + * 1 => [ 1 ] + * 2 => [ 1, 3 ] * 5 => [ 1, 3, 5, 7, 9 ] */ function generateOdds(len) { - throw new Error('Not implemented'); + let arr = new Array(len); + arr.fill(1); + return arr.map((elem, index) => + { + return elem = index*2 + 1; + }); } /** * Returns the doubled array - elements of the specified array are repeated twice using original order - * + * * @param {array} arr * @return {array} - * + * * @example - * ['Ace', 10, true] => ['Ace', 10, true, 'Ace', 10, true] + * ['Ace', 10, true] => ['Ace', 10, true, 'Ace', 10, true] * [0, 1, 2, 3, 4, 5] => [0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5] - * [] => [] + * [] => [] */ function doubleArray(arr) { - throw new Error('Not implemented'); + arr.map(elem => + { + return arr.push(elem); + }); + return arr; } /** * Returns an array of positive numbers from the specified array in original order - * + * * @param {array} arr * @return {array} - * + * * @example * [ 0, 1, 2, 3, 4, 5 ] => [ 1, 2, 3, 4, 5 ] * [-1, 2, -5, -4, 0] => [ 2 ] - * [] => [] + * [] => [] */ function getArrayOfPositives(arr) { - throw new Error('Not implemented'); + return arr.filter((item, i, arr) => item > 0); } /** * Returns the array with strings only in the specified array (in original order) - * + * * @param {array} arr * @return {array} - * + * * @example * [ 0, 1, 'cat', 3, true, 'dog' ] => [ 'cat', 'dog' ] * [ 1, 2, 3, 4, 5 ] => [] * [ 'cat, 'dog', 'raccon' ] => [ 'cat', 'dog', 'racoon' ] */ function getArrayOfStrings(arr) { - throw new Error('Not implemented'); + return arr.filter(elem => typeof elem === 'string' || elem instanceof String); } /** * Removes falsy values from the specified array * Falsy values: false, null, 0, "", undefined, and NaN. * (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean#Description) - * + * * @param {array} arr * @return {array} - * + * * @example * [ 0, false, 'cat', NaN, true, '' ] => [ 'cat', true ] * [ 1, 2, 3, 4, 5, 'false' ] => [ 1, 2, 3, 4, 5, 'false' ] * [ false, 0, NaN, '', undefined ] => [ ] */ function removeFalsyValues(arr) { - throw new Error('Not implemented'); + return arr.filter((item, i, arr) => !!item); } /** * Returns the array of useprcase strings from the specified array - * + * * @param {array} arr * @return {array} - * + * * @example * [ 'permanent-internship', 'glutinous-shriek', 'multiplicative-elevation' ] => [ 'PERMANENT-INTERNSHIP', 'GLUTINOUS-SHRIEK', 'MULTIPLICATIVE-ELEVATION' ] * [ 'a', 'b', 'c', 'd', 'e', 'f', 'g' ] => [ 'A', 'B', 'C', 'D', 'E', 'F', 'G' ] */ function getUpperCaseStrings(arr) { - throw new Error('Not implemented'); + return arr.map(elem => + { + return elem.toUpperCase(); + }); } /** * Returns the array of string lengths from the specified string array. - * + * * @param {array} arr * @return {array} - * + * * @example * [ '', 'a', 'bc', 'def', 'ghij' ] => [ 0, 1, 2, 3, 4 ] * [ 'angular', 'react', 'ember' ] => [ 7, 5, 5 ] */ function getStringsLength(arr) { - throw new Error('Not implemented'); + return arr.map((item, i, arr) => item.length); } /** * Inserts the item into specified array at specified index - * + * * @param {array} arr * @param {any} item - * @param {number} index - * + * @param {number} index + * * @example * [ 1, 3, 4, 5 ], 2, 1 => [ 1, 2, 3, 4, 5 ] * [ 1, 'b', 'c'], 0, 'x' => [ 'x', 1, 'b', 'c' ] */ function insertItem(arr, item, index) { - throw new Error('Not implemented'); + return arr.splice(index, 0, item); } /** * Returns the n first items of the specified array - * + * * @param {array} arr - * @param {number} n - * + * @param {number} n + * * @example * [ 1, 3, 4, 5 ], 2 => [ 1, 2 ] * [ 'a', 'b', 'c', 'd'], 3 => [ 'a', 'b', 'c' ] */ function getHead(arr, n) { - throw new Error('Not implemented'); + return arr.slice(0, n); } /** * Returns the n last items of the specified array - * + * * @param {array} arr - * @param {number} n - * + * @param {number} n + * * @example * [ 1, 3, 4, 5 ], 2 => [ 4, 5 ] * [ 'a', 'b', 'c', 'd'], 3 => [ 'b', 'c', 'd' ] */ function getTail(arr, n) { - throw new Error('Not implemented'); + return arr.splice( -n); } /** * Returns CSV represebtation of two-dimentional numeric array. * https://en.wikipedia.org/wiki/Comma-separated_values - * + * * @param {array} arr * @return {string} - * + * * @example * [ * [ 0, 1, 2, 3, 4 ], * [ 10,11,12,13,14 ], * [ 20,21,22,23,24 ], * [ 30,31,32,33,34 ] - * ] - * => + * ] + * => * '0,1,2,3,4\n' * +'10,11,12,13,14\n' * +'20,21,22,23,24\n' * +'30,31,32,33,34' */ function toCsvText(arr) { - throw new Error('Not implemented'); + let arrStr = arr.map((elem, index) => + { + if (index != arr.length-1) + return elem.join(',') + '\n'; + else + return elem.join(','); + }).join(''); + return arrStr; } /** * Transforms the numeric array into the according array of squares: * f(x) = x * x - * + * * @param {array} arr * @return {array} - * + * * @example * [ 0, 1, 2, 3, 4, 5 ] => [ 0, 1, 4, 9, 16, 25 ] * [ 10, 100, -1 ] => [ 100, 10000, 1 ] */ function toArrayOfSquares(arr) { - throw new Error('Not implemented'); + return arr.map((item, i, arr) => item ** 2); } /** * Transforms the numeric array to the according moving sum array: - * f[n] = x[0] + x[1] + x[2] +...+ x[n] + * f[n] = x[0] + x[1] + x[2] +...+ x[n] * or f[n] = f[n-1] + x[n] - * + * * @param {array} arr * @return {array} - * + * * Example : * [ 1, 1, 1, 1, 1 ] => [ 1, 2, 3, 4, 5 ] * [ 10, -10, 10, -10, 10 ] => [ 10, 0, 10, 0, 10 ] - * [ 0, 0, 0, 0, 0] => [ 0, 0, 0, 0, 0] + * [ 0, 0, 0, 0, 0] => [ 0, 0, 0, 0, 0] * [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ] => [ 1, 3, 6, 10, 15, 21, 28, 36, 45, 55 ] */ function getMovingSum(arr) { - throw new Error('Not implemented'); + let sum = 0; + return arr.map((elem) => + { + elem += sum; + sum = elem; + return elem; + }); } /** * Returns every second item from the specified array: - * + * * @param {array} arr * @return {array} - * + * * Example : * [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ] => [ 2, 4, 6, 8, 10 ] * [ 'a', 'b', 'c' , null ] => [ "b", null ] * [ "a" ] => [] */ function getSecondItems(arr) { - throw new Error('Not implemented'); + return arr.filter((elem, index) => index % 2); } /** * Propagates every item in sequence its position times - * Returns an array that consists of: one first item, two second items, tree third items etc. - * - * @param {array} arr + * Returns an array that consists of: one first item, two second items, tree third items etc. + * + * @param {array} arr * @return {array} - * + * * @example : * [] => [] * [ 1 ] => [ 1 ] @@ -268,13 +293,15 @@ function getSecondItems(arr) { * [ 1,2,3,4,5 ] => [ 1, 2,2, 3,3,3, 4,4,4,4, 5,5,5,5,5 ] */ function propagateItemsByPositionIndex(arr) { - throw new Error('Not implemented'); + return arr.reduce((acc, elem, index) => acc.concat( + Array.from({length: index + 1}, () => elem)), [] + ); } -/** +/** * Returns the 3 largest numbers from the specified array - * + * * @param {array} arr * @return {array} * @@ -286,16 +313,16 @@ function propagateItemsByPositionIndex(arr) { * [ 10, 10, 10, 10 ] => [ 10, 10, 10 ] */ function get3TopItems(arr) { - throw new Error('Not implemented'); + return arr.sort((a, b) => b - a).slice(0, 3); } - - -/** + + +/** * Returns the number of positive numbers from specified array - * + * * @param {array} arr * @return {number} - * + * * @example * [ ] => 0 * [ -1, 0, 1 ] => 1 @@ -306,13 +333,13 @@ function get3TopItems(arr) { function getPositivesCount(arr) { throw new Error('Not implemented'); } - -/** + +/** * Sorts digit names - * + * * @param {array} arr * @return {array} - * + * * @example * [] => [] * [ 'nine','one' ] => [ 'one', 'nine' ] @@ -321,15 +348,17 @@ function getPositivesCount(arr) { * [ 'one','one','one','zero' ] => [ 'zero','one','one','one' ] */ function sortDigitNamesByNumericOrder(arr) { - throw new Error('Not implemented'); + const mapped1 = { 0: 'zero', 1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five', 6: 'six', 7: 'seven', 8: 'eight', 9: 'nine' }; + const mapped2 = { 'zero': 0, 'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6, 'seven': 7, 'eight': 8, 'nine': 9 }; + return arr.map(x => mapped2[x]).sort().map(x => mapped1[x]); } -/** +/** * Returns the sum of all items in the specified array of numbers - * + * * @param {array} arr * @return {number} - * + * * @example * [] => 0 * [ 1, 2, 3 ] => 6 @@ -337,15 +366,15 @@ function sortDigitNamesByNumericOrder(arr) { * [ 1, 10, 100, 1000 ] => 1111 */ function getItemsSum(arr) { - throw new Error('Not implemented'); + return arr.reduce((acc, elem) => acc + elem, 0); } - -/** + +/** * Returns the number of all falsy value in the specified array - * + * * @param {array} arr * @return {array} - * + * * @example * [] => 0 * [ 1, '', 3 ] => 1 @@ -353,49 +382,61 @@ function getItemsSum(arr) { * [ null, undefined, NaN, false, 0, '' ] => 6 */ function getFalsyValuesCount(arr) { - throw new Error('Not implemented'); + let sum = 0; + arr.map(elem => + { + if (Boolean(elem) == 0) + return sum++; + }); + return sum; } /** - * Returns a number of all occurences of the specified item in an array - * + * Returns a number of all occurences of the specified item in an array + * * @param {array} arr - * @param {any} item + * @param {any} item * @return {number} - * + * * @example * [ 0, 0, 1, 1, 1, 2 ], 1 => 3 * [ 1, 2, 3, 4, 5 ], 0 => 0 * [ 'a','b','c','c' ], 'c'=> 2 - * [ null, undefined, null ], null => 2 + * [ null, undefined, null ], null => 2 * [ true, 0, 1, 'true' ], true => 1 */ function findAllOccurences(arr, item) { - throw new Error('Not implemented'); + let num = 0; + arr.map(elem => + { + if (elem === item) + return num++; + }) + return num; } /** - * Concatenates all elements from specified array into single string with ',' delimeter - * - * @param {array} arr + * Concatenates all elements from specified array into single string with ',' delimeter + * + * @param {array} arr * @return {string} - * + * * @example * [0, false, 'cat', NaN, true, ''] => '0,false,cat,NaN,true,' * [1, 2, 3, 4, 5] => '1,2,3,4,5' * ['rock', 'paper', 'scissors'] => 'rock,paper,scissors' */ function toStringList(arr) { - throw new Error('Not implemented'); + return arr.join(); } /** * Sorts the specified array by country name first and city name (if countries are equal) in ascending order. - * + * * @param {array} arr * @return {array} - * + * * @example * [ * { country: 'Russia', city: 'Moscow' }, @@ -404,7 +445,7 @@ function toStringList(arr) { * { country: 'Russia', city: 'Saint Petersburg' }, * { country: 'Poland', city: 'Krakow' }, * { country: 'Belarus', city: 'Brest' } - * ] + * ] * => * [ * { country: 'Belarus', city: 'Brest' }, @@ -415,38 +456,61 @@ function toStringList(arr) { * { country: 'Russia', city: 'Saint Petersburg' } */ function sortCitiesArray(arr) { - throw new Error('Not implemented'); + function compareLocation(a, b) { + if (a.country < b.country) { + return -1; + } + if (a.country > b.country) { + return 1; + } + if (a.country === b.country) { + if (a.city < b.city) { + return -1; + } + if (a.city > b.city) { + return 1; + } + if (a.city === b.city) { + return 0; + } + } + } + return arr.sort(compareLocation); } /** * Creates an indentity matrix of the specified size - * + * * @param {number} n * @return {array} - * + * * @example * 1 => [[1]] - * + * * 2 => [[1,0], * [0,1]] - * + * * [[1,0,0,0,0], * [0,1,0,0,0], * 5 => [0,0,1,0,0], * [0,0,0,1,0], - * [0,0,0,0,1]] + * [0,0,0,0,1]] */ function getIdentityMatrix(n) { - throw new Error('Not implemented'); + return Array.from({length: n}, function (elem, index) { + let row = new Array(n).fill(0, 0, n); + row[index] = 1; + return row; + }); } /** * Creates an array of integers from the specified start to end (inclusive) - * + * * @param {number} start * @param {number} end * @return {array} - * + * * @example * 1, 5 => [ 1, 2, 3, 4, 5 ] * -2, 2 => [ -2, -1, 0, 1, 2 ] @@ -454,7 +518,7 @@ function getIdentityMatrix(n) { * 3, 3 => [ 3 ] */ function getIntervalArray(start, end) { - throw new Error('Not implemented'); + return Array.from({length: end - start + 1}, (elem, index) => index + start); } /** @@ -462,14 +526,21 @@ function getIntervalArray(start, end) { * * @param {array} arr * @return {array} - * + * * @example * [ 1, 2, 3, 3, 2, 1 ] => [ 1, 2, 3 ] * [ 'a', 'a', 'a', 'a' ] => [ 'a' ] * [ 1, 1, 2, 2, 3, 3, 4, 4] => [ 1, 2, 3, 4] */ function distinct(arr) { - throw new Error('Not implemented'); + let resArr = []; + arr.map(elem => + { + if (resArr.indexOf(elem) == -1) + resArr.push(elem); + return resArr; + }); + return resArr; } /** @@ -491,19 +562,27 @@ function distinct(arr) { * { country: 'Belarus', city: 'Grodno' }, * { country: 'Belarus', city: 'Minsk' }, * { country: 'Poland', city: 'Lodz' } - * ], - * item => item.country, + * ], + * item => item.country, * item => item.city * ) - * => + * => * Map { * "Belarus" => ["Brest", "Grodno", "Minsk"], - * "Russia" => ["Omsk", "Samara"], + * "Russia" => ["Omsk", "Samara"], * "Poland" => ["Lodz"] * } */ function group(array, keySelector, valueSelector) { - throw new Error('Not implemented'); + let _map = new Map(); + array.map((x, ind) => + { + if( _map.has(keySelector(x)) ) + _map.get(keySelector(x)).push(valueSelector(x)); + else + _map.set(keySelector(x), [valueSelector(x)]); + }); + return _map; } @@ -513,13 +592,18 @@ function group(array, keySelector, valueSelector) { * @param {array} arr * @param {Function} childrenSelector, a transform function to apply to each element that returns an array of children * @return {array} - * + * * @example * [[1, 2], [3, 4], [5, 6]], (x) => x => [ 1, 2, 3, 4, 5, 6 ] * ['one','two','three'], x=>x.split('') => ['o','n','e','t','w','o','t','h','r','e','e'] */ function selectMany(arr, childrenSelector) { - throw new Error('Not implemented'); + let myArr = []; + arr.map(elem => + { + myArr.push(...childrenSelector(elem)); + }); + return myArr; } @@ -529,70 +613,80 @@ function selectMany(arr, childrenSelector) { * @param {array} arr * @param {array} indexes * @return {any} element from array - * + * * @example - * [[1, 2], [3, 4], [5, 6]], [0,0] => 1 (arr[0][0]) - * ['one','two','three'], [2] => 'three' (arr[2]) + * [[1, 2], [3, 4], [5, 6]], [0,0] => 1 (arr[0][0]) + * ['one','two','three'], [2] => 'three' (arr[2]) * [[[ 1, 2, 3]]], [ 0, 0, 1 ] => 2 (arr[0][0][1]) */ function getElementByIndexes(arr, indexes) { - throw new Error('Not implemented'); + return indexes.map(elem => arr = arr[elem])[indexes.length - 1]; } /** * Swaps the head and tail of the specified array: - * the head (first half) of array move to the end, the tail (last half) move to the start. + * the head (first half) of array move to the end, the tail (last half) move to the start. * The middle element (if exists) leave on the same position. - * - * + * + * * @param {array} arr * @return {array} - * + * * @example * [ 1, 2, 3, 4, 5 ] => [ 4, 5, 3, 1, 2 ] - * \----/ \----/ - * head tail + * \----/ \----/ + * head tail + * + * [ 1, 2 ] => [ 2, 1 ] + * [ 1, 2, 3, 4, 5, 6, 7, 8 ] => [ 5, 6, 7, 8, 1, 2, 3, 4 ] * - * [ 1, 2 ] => [ 2, 1 ] - * [ 1, 2, 3, 4, 5, 6, 7, 8 ] => [ 5, 6, 7, 8, 1, 2, 3, 4 ] - * */ function swapHeadAndTail(arr) { - throw new Error('Not implemented'); + let len = Math.floor(arr.length / 2); + let head = arr.splice(0, len); + let tail = arr.splice(arr.length-len, len); + let array = []; + array.push(...tail); + if(arr.length % 2) { + let middle = arr.splice(0, 1); + array.push(...middle) + } + array.push(...head); + return array; } module.exports = { - findElement: findElement, - generateOdds: generateOdds, - doubleArray: doubleArray, - getArrayOfPositives: getArrayOfPositives, - getArrayOfStrings: getArrayOfStrings, - removeFalsyValues: removeFalsyValues, - getUpperCaseStrings: getUpperCaseStrings, - getStringsLength: getStringsLength, - insertItem: insertItem, - getHead: getHead, - getTail: getTail, - toCsvText: toCsvText, - toStringList: toStringList, - toArrayOfSquares: toArrayOfSquares, - getMovingSum: getMovingSum, - getSecondItems: getSecondItems, - propagateItemsByPositionIndex: propagateItemsByPositionIndex, - get3TopItems: get3TopItems, - getPositivesCount: getPositivesCount, - sortDigitNamesByNumericOrder: sortDigitNamesByNumericOrder, - getItemsSum: getItemsSum, - getFalsyValuesCount: getFalsyValuesCount, - findAllOccurences: findAllOccurences, - sortCitiesArray: sortCitiesArray, - getIdentityMatrix: getIdentityMatrix, - getIntervalArray: getIntervalArray, - distinct: distinct, - group: group, - selectMany: selectMany, - getElementByIndexes: getElementByIndexes, - swapHeadAndTail: swapHeadAndTail + findElement: findElement, + generateOdds: generateOdds, + doubleArray: doubleArray, + getArrayOfPositives: getArrayOfPositives, + getArrayOfStrings: getArrayOfStrings, + removeFalsyValues: removeFalsyValues, + getUpperCaseStrings: getUpperCaseStrings, + getStringsLength: getStringsLength, + insertItem: insertItem, + getHead: getHead, + getTail: getTail, + toCsvText: toCsvText, + toStringList: toStringList, + toArrayOfSquares: toArrayOfSquares, + getMovingSum: getMovingSum, + getSecondItems: getSecondItems, + propagateItemsByPositionIndex: propagateItemsByPositionIndex, + get3TopItems: get3TopItems, + getPositivesCount: getPositivesCount, + sortDigitNamesByNumericOrder: sortDigitNamesByNumericOrder, + getItemsSum: getItemsSum, + getFalsyValuesCount: getFalsyValuesCount, + findAllOccurences: findAllOccurences, + sortCitiesArray: sortCitiesArray, + getIdentityMatrix: getIdentityMatrix, + getIntervalArray: getIntervalArray, + distinct: distinct, + group: group, + selectMany: selectMany, + getElementByIndexes: getElementByIndexes, + swapHeadAndTail: swapHeadAndTail }; From 5552fe4aa07297c60a2cedb34b89696013f1e5c8 Mon Sep 17 00:00:00 2001 From: Shagoysai <34492748+Shagoysai@users.noreply.github.com> Date: Thu, 10 Jun 2021 18:02:26 +0300 Subject: [PATCH 09/40] Update 05-regex-tasks.js --- task/05-regex-tasks.js | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/task/05-regex-tasks.js b/task/05-regex-tasks.js index b1c60f2d4..929d9a533 100644 --- a/task/05-regex-tasks.js +++ b/task/05-regex-tasks.js @@ -31,7 +31,8 @@ * @return {RegExp} */ function getRegexForGuid() { - throw new Error('Not implemented'); + let reg = '[0-9a-f]'; + return new RegExp('^{'+reg+'{8}-'+reg+'{4}-'+reg+'{4}-'+reg+'{4}-'+reg+'{12}}$', 'i'); } @@ -53,7 +54,7 @@ function getRegexForGuid() { * */ function getRegexForPitSpot() { - throw new Error('Not implemented'); + return new RegExp(/.*p.t.*/); } @@ -72,7 +73,7 @@ function getRegexForPitSpot() { * @return {RegExp} */ function getRegexForIPv4() { - throw new Error('Not implemented'); + return /^(([0-2][0-9]{2}|[0-9]{1,2})\.){3}([0-2][0-9]{2}|[0-9]{1,2})$/; } @@ -91,7 +92,7 @@ function getRegexForIPv4() { * @return {RegExp} */ function getRegexForSSN() { - throw new Error('Not implemented'); + return /\d{2}[1-9]-\d{1}[1-9]-\d{3}[1-9]/; } @@ -116,7 +117,7 @@ function getRegexForSSN() { * 'Pa55'.match(validator) => false */ function getPasswordValidator(minLength) { - throw new Error('Not implemented'); + return new RegExp('^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)[A-Za-z\\d]{'+minLength+',}'); } From 895428a85574f414448717b1d840f3f39d77f0f6 Mon Sep 17 00:00:00 2001 From: Shagoysai <34492748+Shagoysai@users.noreply.github.com> Date: Thu, 10 Jun 2021 18:07:40 +0300 Subject: [PATCH 10/40] Update 06-conditions-n-loops-tasks.js --- task/06-conditions-n-loops-tasks.js | 99 +++++++++++++++++++++++++---- 1 file changed, 85 insertions(+), 14 deletions(-) diff --git a/task/06-conditions-n-loops-tasks.js b/task/06-conditions-n-loops-tasks.js index 249194c34..cabade980 100644 --- a/task/06-conditions-n-loops-tasks.js +++ b/task/06-conditions-n-loops-tasks.js @@ -30,7 +30,14 @@ * */ function getFizzBuzz(num) { - throw new Error('Not implemented'); + if((num % 3 === 0) && (num % 5 === 0)) { + return 'FizzBuzz' + } else if(num % 5 === 0) { + return'Buzz' + } else if (num % 3 === 0) { + return 'Fizz' + } + return num } @@ -46,7 +53,13 @@ function getFizzBuzz(num) { * 10 => 3628800 */ function getFactorial(n) { - throw new Error('Not implemented'); + if (n < 0) + return -1; + else if (n === 0) + return 1; + else { + return (n * getFactorial(n - 1)); + } } @@ -63,7 +76,11 @@ function getFactorial(n) { * -1,1 => 0 ( = -1 + 0 + 1 ) */ function getSumBetweenNumbers(n1, n2) { - throw new Error('Not implemented'); + let count = 0; + for(let i = n1; i <=n2; i++ ) { + count +=i + } + return count; } @@ -82,7 +99,7 @@ function getSumBetweenNumbers(n1, n2) { * 10,10,10 => true */ function isTriangle(a,b,c) { - throw new Error('Not implemented'); + return a < b + c && b < a + c && c < a + b; } @@ -119,7 +136,12 @@ function isTriangle(a,b,c) { * */ function doRectanglesOverlap(rect1, rect2) { - throw new Error('Not implemented'); + return !( + rect1.left + rect1.width < rect2.left || + rect2.left + rect2.width < rect1.left || + rect1.top + rect1.height < rect2.top || + rect2.top + rect2.height < rect1.top + ); } @@ -150,7 +172,9 @@ function doRectanglesOverlap(rect1, rect2) { * */ function isInsideCircle(circle, point) { - throw new Error('Not implemented'); + let dx = point.x - circle.center.x; + let dy = point.y - circle.center.y; + return (dx*dx + dy*dy) < (circle.radius * circle.radius); } @@ -166,7 +190,13 @@ function isInsideCircle(circle, point) { * 'entente' => null */ function findFirstSingleChar(str) { - throw new Error('Not implemented'); + for (let i = 0; i < str.length; i++) { + if (str.indexOf(str[i]) == str.lastIndexOf(str[i])) { + return str[i]; + } + } + + return null; } @@ -192,7 +222,11 @@ function findFirstSingleChar(str) { * */ function getIntervalString(a, b, isStartIncluded, isEndIncluded) { - throw new Error('Not implemented'); + let res = ""; + res += (isStartIncluded && res.length === 0) ? "[" : "("; + res += a <= b ? `${a}, ${b}` : `${b}, ${a}`; + res += isEndIncluded ? "]" : ")"; + return res; } @@ -209,7 +243,7 @@ function getIntervalString(a, b, isStartIncluded, isEndIncluded) { * 'noon' => 'noon' */ function reverseString(str) { - throw new Error('Not implemented'); + return str.split('').reverse().join(''); } @@ -226,7 +260,7 @@ function reverseString(str) { * 34143 => 34143 */ function reverseInteger(num) { - throw new Error('Not implemented'); + return Number.parseInt(reverseString(num.toString())); } @@ -251,7 +285,17 @@ function reverseInteger(num) { * 4916123456789012 => false */ function isCreditCardNumber(ccn) { - throw new Error('Not implemented'); + ccn = [...String(ccn)].reverse(); + ccn = ccn.reduce(function(sum, val, ind) + { + let dig = Number(val); + if(ind % 2) + dig *= 2; + sum += Math.floor(dig / 10); + sum += dig % 10; + return sum; + }, 0); + return (ccn * 3) % 10 == 0; } @@ -270,7 +314,15 @@ function isCreditCardNumber(ccn) { * 165536 (1+6+5+5+3+6 = 26, 2+6 = 8) => 8 */ function getDigitalRoot(num) { - throw new Error('Not implemented'); + do{ + let sum = 0; + while(num > 0){ + sum += num % 10; + num = Math.floor(num / 10); + } + num = sum; + }while(num > 9); + return num; } @@ -296,7 +348,26 @@ function getDigitalRoot(num) { * '{[(<{[]}>)]}' = true */ function isBracketsBalanced(str) { - throw new Error('Not implemented'); + let pair = { + '>': '<', + ')': '(', + ']': '[', + '}': '{' + } + let res = [...str].reduce(function(acc, x, ind) + { + if (['(', '{', '[', '<'].indexOf(x) != -1) + acc.push(x); + else + { + if (acc.length > 0 && acc[acc.length - 1] == pair[x]) + acc.pop(); + else + acc.push(x); + } + return acc; + }, []); + return res.length == 0; } @@ -356,7 +427,7 @@ function timespanToHumanString(startDate, endDate) { * 365, 10 => '365' */ function toNaryString(num, n) { - throw new Error('Not implemented'); + return num.toString(n); } From 26a7e3f503d08d74e74d2413a2acec0731a819a8 Mon Sep 17 00:00:00 2001 From: Shagoysai <34492748+Shagoysai@users.noreply.github.com> Date: Thu, 10 Jun 2021 18:08:38 +0300 Subject: [PATCH 11/40] Update 07-yield-tasks.js --- task/07-yield-tasks.js | 69 +++++++++++++++++++++++++++++++++++++++--- 1 file changed, 64 insertions(+), 5 deletions(-) diff --git a/task/07-yield-tasks.js b/task/07-yield-tasks.js index a2369790a..f975baff5 100644 --- a/task/07-yield-tasks.js +++ b/task/07-yield-tasks.js @@ -33,7 +33,19 @@ * */ function* get99BottlesOfBeer() { - throw new Error('Not implemented'); + for (let bottles = 99; bottles > 2; bottles--) { + yield `${bottles} bottles of beer on the wall, ${bottles} bottles of beer.`; + yield `Take one down and pass it around, ${bottles - 1} bottles of beer on the wall.`; + } + + yield `2 bottles of beer on the wall, 2 bottles of beer.`; + yield `Take one down and pass it around, 1 bottle of beer on the wall.`; + + yield `1 bottle of beer on the wall, 1 bottle of beer.`; + yield `Take one down and pass it around, no more bottles of beer on the wall.`; + + yield 'No more bottles of beer on the wall, no more bottles of beer.'; + yield 'Go to the store and buy some more, 99 bottles of beer on the wall.'; } @@ -47,7 +59,19 @@ function* get99BottlesOfBeer() { * */ function* getFibonacciSequence() { - throw new Error('Not implemented'); + yield 0; + yield 1; + + let last = 0; + let current = 1; + let new_val = 1; + + while (true){ + yield new_val; + last = current; + current = new_val; + new_val = last + current; + } } @@ -82,7 +106,14 @@ function* getFibonacciSequence() { * */ function* depthTraversalTree(root) { - throw new Error('Not implemented'); + let q1 = [root]; + while (q1.length) { + let node = q1.pop(); + yield node; + if (node.children) { + q1.push(...node.children.reverse()); + } + } } @@ -108,7 +139,24 @@ function* depthTraversalTree(root) { * */ function* breadthTraversalTree(root) { - throw new Error('Not implemented'); + let queue = [root]; + + while (queue.length != 0) { + let node = queue.shift(); + yield node; + + if (node.children !== undefined) { + + for (let child of node.children) { + + if (queue.length == 0 && child.children === undefined) { + yield child; + } else { + queue.push(child); + } + } + } + } } @@ -126,7 +174,18 @@ function* breadthTraversalTree(root) { * [ 1, 3, 5, ... ], [ -1 ] => [ -1, 1, 3, 5, ...] */ function* mergeSortedSequences(source1, source2) { - throw new Error('Not implemented'); + const sources = [source1(), source2()]; + let it = [sources[0].next(), sources[1].next()]; + + while (true) { + if (it[0].value >= it[1].value || it[0].value === undefined) { + yield it[1].value; + it[1] = sources[1].next(); + } else { + yield it[0].value; + it[0] = sources[0].next(); + } + } } From 788ce68adf96480a17659d19767d76446878cc5d Mon Sep 17 00:00:00 2001 From: Shagoysai <34492748+Shagoysai@users.noreply.github.com> Date: Fri, 11 Jun 2021 11:16:57 +0300 Subject: [PATCH 12/40] Update 08-objects-tasks.js --- task/08-objects-tasks.js | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/task/08-objects-tasks.js b/task/08-objects-tasks.js index 610b1e7b2..aa120dd0b 100644 --- a/task/08-objects-tasks.js +++ b/task/08-objects-tasks.js @@ -23,7 +23,12 @@ * console.log(r.getArea()); // => 200 */ function Rectangle(width, height) { - throw new Error('Not implemented'); + this.width = width; + this.height = height; + + this.getArea = () => { + return this.width * this.height + } } From 8a5105249df8eb13fd95c637e2cb7ea5f0cbe362 Mon Sep 17 00:00:00 2001 From: Shagoysai <34492748+Shagoysai@users.noreply.github.com> Date: Fri, 11 Jun 2021 11:18:28 +0300 Subject: [PATCH 13/40] Update 09-functions-n-closures-tasks.js --- task/09-functions-n-closures-tasks.js | 34 ++++++++++++++++++++++----- 1 file changed, 28 insertions(+), 6 deletions(-) diff --git a/task/09-functions-n-closures-tasks.js b/task/09-functions-n-closures-tasks.js index 6ba9dcedd..e22e3ac4e 100644 --- a/task/09-functions-n-closures-tasks.js +++ b/task/09-functions-n-closures-tasks.js @@ -26,7 +26,9 @@ * */ function getComposition(f,g) { - throw new Error('Not implemented'); + return function (x) { + return f(g(x)); + } } @@ -47,7 +49,9 @@ function getComposition(f,g) { * */ function getPowerFunction(exponent) { - throw new Error('Not implemented'); + return function (number) { + return Math.pow(number, exponent); + }; } @@ -65,7 +69,10 @@ function getPowerFunction(exponent) { * getPolynom() => null */ function getPolynom() { - throw new Error('Not implemented'); + var tmp = Array.from(arguments).reverse(); + return (x) => { + return tmp.reduce((prev, curr, index) => prev+curr*Math.pow(x,index),0); + }; } @@ -84,7 +91,10 @@ function getPolynom() { * memoizer() => the same random number (next run, returns the previous cached result) */ function memoize(func) { - throw new Error('Not implemented'); + let cashed = func(); + return function() { + return cashed + } } @@ -104,7 +114,16 @@ function memoize(func) { * retryer() => 2 */ function retry(func, attempts) { - throw new Error('Not implemented'); + return()=>{ + for (var i = 0; i < attempts;){ + try{ + return func(); + } catch(err){ + i += 1; + } + } + return i; + }; } @@ -171,7 +190,10 @@ function partialUsingArguments(fn) { * getId10() => 11 */ function getIdGeneratorFunction(startFrom) { - throw new Error('Not implemented'); + var curr = startFrom; + return function() { + return startFrom++; + } } From aa9546994c7e247ee29e91be0bb8bce9adae5941 Mon Sep 17 00:00:00 2001 From: Shagoysai <34492748+Shagoysai@users.noreply.github.com> Date: Fri, 11 Jun 2021 11:19:40 +0300 Subject: [PATCH 14/40] Update 10-katas-1-tasks.js --- task/10-katas-1-tasks.js | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/task/10-katas-1-tasks.js b/task/10-katas-1-tasks.js index 5128b0695..353c390bf 100644 --- a/task/10-katas-1-tasks.js +++ b/task/10-katas-1-tasks.js @@ -17,8 +17,18 @@ * ] */ function createCompassPoints() { - throw new Error('Not implemented'); var sides = ['N','E','S','W']; // use array of cardinal directions only! + res = []; + + function getDoubleSide(side1, side2) { + switch (side1) { + case 'E': + return 'SE'; + case 'W': + return 'NW'; + default: + return side1 + side2; + } } From 39d8512bcef0b1b3e162d9c276cb010276b448fa Mon Sep 17 00:00:00 2001 From: Shagoysai <34492748+Shagoysai@users.noreply.github.com> Date: Fri, 11 Jun 2021 18:18:08 +0300 Subject: [PATCH 15/40] Update 01-strings-tasks.js added missing } --- task/01-strings-tasks.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/task/01-strings-tasks.js b/task/01-strings-tasks.js index 600f8f3c3..8fc5d95e8 100644 --- a/task/01-strings-tasks.js +++ b/task/01-strings-tasks.js @@ -100,7 +100,7 @@ function getFirstChar(value) { */ function removeLeadingAndTrailingWhitespaces(value) { return value.trim(); - +} /** * Returns a string that repeated the specified number of times. * @@ -113,7 +113,7 @@ function removeLeadingAndTrailingWhitespaces(value) { * 'cat', 3 => 'catcatcat' */ function repeatString(value, count) { - return value.repeat(count) + return value.repeat(count); } /** From 0c6010dd24fd48bc7c10d22aacb0141011f2362f Mon Sep 17 00:00:00 2001 From: Shagoysai <34492748+Shagoysai@users.noreply.github.com> Date: Fri, 11 Jun 2021 18:23:24 +0300 Subject: [PATCH 16/40] Update 02-numbers-tasks.js --- task/02-numbers-tasks.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/task/02-numbers-tasks.js b/task/02-numbers-tasks.js index cbdcb43a7..9287d5019 100644 --- a/task/02-numbers-tasks.js +++ b/task/02-numbers-tasks.js @@ -75,7 +75,7 @@ function getAverage(value1, value2) { function getDistanceBetweenPoints(x1, y1, x2, y2) { var a = x1 - x2; var b = y1 - y2; - return Math.sqrt(a*a + b*b) + return Math.sqrt(a*a + b*b); } /** @@ -149,7 +149,7 @@ function getLastDigit(value) { * '-525.5' => -525.5 */ function parseNumberFromString(value) { - return Number(value) + return Number(value); } /** From ebc2dc87a4b3d1bf0e9919243d3f97815b4a66f7 Mon Sep 17 00:00:00 2001 From: Shagoysai <34492748+Shagoysai@users.noreply.github.com> Date: Fri, 11 Jun 2021 18:25:24 +0300 Subject: [PATCH 17/40] Update .travis.yml --- .travis.yml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.travis.yml b/.travis.yml index afd0508c9..dc6955648 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,3 +1,6 @@ +install: + - bundle install --path vendor/bundle + - npm install language: node_js node_js: - "14.17.0" From 55214d357785b42cd0885d8cba63adea535ea99d Mon Sep 17 00:00:00 2001 From: Siarhei Kalamiyets <34492748+Shagoysai@users.noreply.github.com> Date: Sat, 12 Jun 2021 16:18:08 +0300 Subject: [PATCH 18/40] Initial commit --- .gitattributes | 2 ++ 1 file changed, 2 insertions(+) create mode 100644 .gitattributes diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 000000000..dfe077042 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +# Auto detect text files and perform LF normalization +* text=auto From c886aca7a114c7d11cf5ec5fbbc8f4d17620de90 Mon Sep 17 00:00:00 2001 From: Shagoysai <34492748+Shagoysai@users.noreply.github.com> Date: Sat, 12 Jun 2021 16:22:39 +0300 Subject: [PATCH 19/40] Add files via upload --- task/01-strings-tasks.js | 59 ++-- task/02-numbers-tasks.js | 16 +- task/03-date-tasks.js | 33 +- task/04-arrays-tasks.js | 471 ++++++++++---------------- task/05-regex-tasks.js | 32 +- task/06-conditions-n-loops-tasks.js | 392 +-------------------- task/07-yield-tasks.js | 69 +--- task/08-objects-tasks.js | 7 +- task/09-functions-n-closures-tasks.js | 34 +- task/10-katas-1-tasks.js | 12 +- 10 files changed, 245 insertions(+), 880 deletions(-) diff --git a/task/01-strings-tasks.js b/task/01-strings-tasks.js index 8fc5d95e8..3bd6e0c0a 100644 --- a/task/01-strings-tasks.js +++ b/task/01-strings-tasks.js @@ -22,7 +22,7 @@ * '', 'bb' => 'bb' */ function concatenateStrings(value1, value2) { - return value1.concat(value2) + return value1.concat(value2); } @@ -55,7 +55,7 @@ function getStringLength(value) { * 'Chuck','Norris' => 'Hello, Chuck Norris!' */ function getStringFromTemplate(firstName, lastName) { - return "Hello, " +firstName+ ' '+lastName+'!'; + return `Hello, ${firstName} ${lastName}!`; } /** @@ -69,7 +69,7 @@ function getStringFromTemplate(firstName, lastName) { * 'Hello, Chuck Norris!' => 'Chuck Norris' */ function extractNameFromTemplate(value) { - return value.slice(7, -1); + return new RegExp("Hello, (.+)!").exec(value)[1]; } @@ -101,6 +101,7 @@ function getFirstChar(value) { function removeLeadingAndTrailingWhitespaces(value) { return value.trim(); } + /** * Returns a string that repeated the specified number of times. * @@ -144,7 +145,7 @@ function removeFirstOccurrences(str, value) { * '<a>' => 'a' */ function unbracketTag(str) { - return str.slice(1, str.length-1); + return str.replace('<', '').replace('>', ''); } @@ -200,14 +201,10 @@ function extractEmails(str) { * */ function getRectangleString(width, height) { - var horizontal = '─'; - var vertical = '│'; - var breakline = '\n'; - var space = ' '; - - return '┌' + horizontal.repeat(width - 2) + '┐' + breakline + - (vertical + space.repeat(width - 2) + vertical + breakline).repeat(height - 2) + - '└' + horizontal.repeat(width - 2) + '┘' + breakline; + const top = `┌${'─'.repeat(width - 2)}┐\n`; + const mid = `│${' '.repeat(width - 2)}│\n`; + const bottom = `└${'─'.repeat(width - 2)}┘\n`; + return top + mid.repeat(height - 2) + bottom; } @@ -227,25 +224,10 @@ function getRectangleString(width, height) { * */ function encodeToRot13(str) { - var amount = 13 - var output = "" - - for (var i = 0; i < str.length; i++) { - var c = str[i] - if (c.match(/[a-z]/i)) { - var code = str.charCodeAt(i) - - if (code >= 65 && code <= 90) { - c = String.fromCharCode(((code - 65 + amount) % 26) + 65) - } - else if (code >= 97 && code <= 122) { - c = String.fromCharCode(((code - 97 + amount) % 26) + 97) - } - } - output += c - } - - return output + const input = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split(''); + const output = 'NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm'.split(''); + const lookup = input.reduce((m, k, i) => Object.assign(m, { [k]: output[i] }), {}); + return str.split('').map((x) => lookup[x] || x).join(''); } /** @@ -262,7 +244,7 @@ function encodeToRot13(str) { * isString(new String('test')) => true */ function isString(value) { - return typeof value === 'string' || value instanceof String; + return Object.prototype.toString.call(value) === "[object String]"; } @@ -292,12 +274,13 @@ function isString(value) { */ function getCardId(value) { const cards = [ - 'A♣','2♣','3♣','4♣','5♣','6♣','7♣','8♣','9♣','10♣','J♣','Q♣','K♣', - 'A♦','2♦','3♦','4♦','5♦','6♦','7♦','8♦','9♦','10♦','J♦','Q♦','K♦', - 'A♥','2♥','3♥','4♥','5♥','6♥','7♥','8♥','9♥','10♥','J♥','Q♥','K♥', - 'A♠','2♠','3♠','4♠','5♠','6♠','7♠','8♠','9♠','10♠','J♠','Q♠','K♠' - ]; - return cards.indexOf(value); + 'A♣', '2♣', '3♣', '4♣', '5♣', '6♣', '7♣', '8♣', '9♣', '10♣', 'J♣', 'Q♣', 'K♣', + 'A♦', '2♦', '3♦', '4♦', '5♦', '6♦', '7♦', '8♦', '9♦', '10♦', 'J♦', 'Q♦', 'K♦', + 'A♥', '2♥', '3♥', '4♥', '5♥', '6♥', '7♥', '8♥', '9♥', '10♥', 'J♥', 'Q♥', 'K♥', + 'A♠', '2♠', '3♠', '4♠', '5♠', '6♠', '7♠', '8♠', '9♠', '10♠', 'J♠', 'Q♠', 'K♠', + ]; + + return cards.indexOf(value); } diff --git a/task/02-numbers-tasks.js b/task/02-numbers-tasks.js index 9287d5019..0bd672ca7 100644 --- a/task/02-numbers-tasks.js +++ b/task/02-numbers-tasks.js @@ -91,7 +91,7 @@ function getDistanceBetweenPoints(x1, y1, x2, y2) { * 5*x = 0 => 0 */ function getLinearEquationRoot(a, b) { - return -b / a; + return -1 * b/a; } @@ -113,11 +113,7 @@ function getLinearEquationRoot(a, b) { * (0,1) (1,2) => 0 */ function getAngleBetweenVectors(x1, y1, x2, y2) { - var angle = Math.atan2(y2, x2) - Math.atan2(y1, x1) - if (angle < 0) { - angle += 2 * Math.PI; - } - return angle + return Math.hypot((Math.abs(x1 - x2)), (Math.abs(y1 - y2))); } /** @@ -133,7 +129,7 @@ function getAngleBetweenVectors(x1, y1, x2, y2) { * 0 => 0 */ function getLastDigit(value) { - return value % 10; + return Math.abs(value) % 10; } @@ -166,7 +162,7 @@ function parseNumberFromString(value) { * 1,2,3 => 3.741657386773941 */ function getParallelipidedDiagonal(a,b,c) { - return Math.sqrt(a * a + b * b + c * c); + return Math.sqrt(a*a + b*b + c*c); } /** @@ -187,7 +183,9 @@ function getParallelipidedDiagonal(a,b,c) { * 1678, 3 => 2000 */ function roundToPowerOfTen(num, pow) { - return Math.round(num / Math.pow(10, pow)) * Math.pow(10, pow); + let a = Math.pow(10, pow); + + return (a === 0) ? num : Math.round(num / a) * a; } /** diff --git a/task/03-date-tasks.js b/task/03-date-tasks.js index a5dcb3557..29b4400f1 100644 --- a/task/03-date-tasks.js +++ b/task/03-date-tasks.js @@ -22,7 +22,7 @@ * 'Sun, 17 May 1998 03:00:00 GMT+01' => Date() */ function parseDataFromRfc2822(value) { - return Date.parse(value) + return Date.parse(value); } /** @@ -37,7 +37,7 @@ function parseDataFromRfc2822(value) { * '2016-01-19T08:07:37Z' => Date() */ function parseDataFromIso8601(value) { - return Date.parse(value) + return Date.parse(value); } @@ -56,10 +56,8 @@ function parseDataFromIso8601(value) { * Date(2015,1,1) => false */ function isLeapYear(date) { - var year = date.getFullYear() - if (year % 400 === 0) return true - if (year % 100 === 0) return false - return year % 4 === 0 + const year = date.getFullYear(); + return ((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0); } @@ -79,14 +77,14 @@ function isLeapYear(date) { * Date(2000,1,1,10,0,0), Date(2000,1,1,15,20,10,453) => "05:20:10.453" */ function timeSpanToString(startDate, endDate) { - return (new Date(endDate - startDate)).toISOString().slice(11, -1); + return (new Date(endDate - startDate)).toISOString().slice(11, -1); } /** * Returns the angle (in radians) between the hands of an analog clock for the specified Greenwich time. * If you have problem with solution please read: https://en.wikipedia.org/wiki/Clock_angle_problem - * + * * @param {date} date * @return {number} * @@ -97,18 +95,13 @@ function timeSpanToString(startDate, endDate) { * Date.UTC(2016,3,5,21, 0) => Math.PI/2 */ function angleBetweenClockHands(date) { - let hour = date.getUTCHours(); - if (hour > 12) { - hour -= 12; - } - let minutes = date.getUTCMinutes(); - let hours = 0.5 * (60 * hour + minutes); - minutes *= 6; - let diff = hours - minutes; - if (diff > 180) { - diff -= 180; - } - return Math.PI * Math.abs(diff) / 180; + const hoursArrow = 0.5 * (60 * (date.getUTCHours() % 12) + date.getUTCMinutes()); + const minutesArrow = 6 * date.getUTCMinutes(); + let angle = Math.abs(hoursArrow - minutesArrow); + if (angle > 180) { + angle = 360 - angle; + } + return (angle * Math.PI / 180); } diff --git a/task/04-arrays-tasks.js b/task/04-arrays-tasks.js index 75a9bbb7e..c6e518b12 100644 --- a/task/04-arrays-tasks.js +++ b/task/04-arrays-tasks.js @@ -9,150 +9,131 @@ * * *********************************************************************************************/ - + /** * Returns an index of the specified element in array or -1 if element is not found - * + * * @param {array} arr * @param {any} value * @return {number} - * + * * @example - * ['Ace', 10, true], 10 => 1 - * ['Array', 'Number', 'string'], 'Date' => -1 + * ['Ace', 10, true], 10 => 1 + * ['Array', 'Number', 'string'], 'Date' => -1 * [0, 1, 2, 3, 4, 5], 5 => 5 */ function findElement(arr, value) { return arr.indexOf(value); } -/** - * Generates an array of odd numbers of the specified length - * - * @param {number} len - * @return {array} - * - * @example - * 1 => [ 1 ] - * 2 => [ 1, 3 ] - * 5 => [ 1, 3, 5, 7, 9 ] - */ -function generateOdds(len) { - let arr = new Array(len); - arr.fill(1); - return arr.map((elem, index) => - { - return elem = index*2 + 1; - }); -} - /** * Returns the doubled array - elements of the specified array are repeated twice using original order - * + * * @param {array} arr * @return {array} - * + * * @example - * ['Ace', 10, true] => ['Ace', 10, true, 'Ace', 10, true] + * ['Ace', 10, true] => ['Ace', 10, true, 'Ace', 10, true] * [0, 1, 2, 3, 4, 5] => [0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5] - * [] => [] + * [] => [] */ function doubleArray(arr) { arr.map(elem => - { - return arr.push(elem); - }); - return arr; + { + return arr.push(elem); + }); + return arr; } /** * Returns an array of positive numbers from the specified array in original order - * + * * @param {array} arr * @return {array} - * + * * @example * [ 0, 1, 2, 3, 4, 5 ] => [ 1, 2, 3, 4, 5 ] * [-1, 2, -5, -4, 0] => [ 2 ] - * [] => [] + * [] => [] */ function getArrayOfPositives(arr) { - return arr.filter((item, i, arr) => item > 0); + return arr.filter(function(value) { + return value > 0; + }); } /** * Returns the array with strings only in the specified array (in original order) - * + * * @param {array} arr * @return {array} - * + * * @example * [ 0, 1, 'cat', 3, true, 'dog' ] => [ 'cat', 'dog' ] * [ 1, 2, 3, 4, 5 ] => [] * [ 'cat, 'dog', 'raccon' ] => [ 'cat', 'dog', 'racoon' ] */ function getArrayOfStrings(arr) { - return arr.filter(elem => typeof elem === 'string' || elem instanceof String); + return arr.filter((x) => typeof (x) === 'string'); } /** * Removes falsy values from the specified array * Falsy values: false, null, 0, "", undefined, and NaN. * (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean#Description) - * + * * @param {array} arr * @return {array} - * + * * @example * [ 0, false, 'cat', NaN, true, '' ] => [ 'cat', true ] * [ 1, 2, 3, 4, 5, 'false' ] => [ 1, 2, 3, 4, 5, 'false' ] * [ false, 0, NaN, '', undefined ] => [ ] */ function removeFalsyValues(arr) { - return arr.filter((item, i, arr) => !!item); + return arr.filter(function(value) { + return Boolean(value); + }); } /** * Returns the array of useprcase strings from the specified array - * + * * @param {array} arr * @return {array} - * + * * @example * [ 'permanent-internship', 'glutinous-shriek', 'multiplicative-elevation' ] => [ 'PERMANENT-INTERNSHIP', 'GLUTINOUS-SHRIEK', 'MULTIPLICATIVE-ELEVATION' ] * [ 'a', 'b', 'c', 'd', 'e', 'f', 'g' ] => [ 'A', 'B', 'C', 'D', 'E', 'F', 'G' ] */ function getUpperCaseStrings(arr) { - return arr.map(elem => - { - return elem.toUpperCase(); - }); + return arr.map(value => value.toUpperCase()); } /** * Returns the array of string lengths from the specified string array. - * + * * @param {array} arr * @return {array} - * + * * @example * [ '', 'a', 'bc', 'def', 'ghij' ] => [ 0, 1, 2, 3, 4 ] * [ 'angular', 'react', 'ember' ] => [ 7, 5, 5 ] */ function getStringsLength(arr) { - return arr.map((item, i, arr) => item.length); + return arr.map(value => value.length); } /** * Inserts the item into specified array at specified index - * + * * @param {array} arr * @param {any} item - * @param {number} index - * + * @param {number} index + * * @example * [ 1, 3, 4, 5 ], 2, 1 => [ 1, 2, 3, 4, 5 ] * [ 1, 'b', 'c'], 0, 'x' => [ 'x', 1, 'b', 'c' ] @@ -163,10 +144,10 @@ function insertItem(arr, item, index) { /** * Returns the n first items of the specified array - * + * * @param {array} arr - * @param {number} n - * + * @param {number} n + * * @example * [ 1, 3, 4, 5 ], 2 => [ 1, 2 ] * [ 'a', 'b', 'c', 'd'], 3 => [ 'a', 'b', 'c' ] @@ -178,113 +159,100 @@ function getHead(arr, n) { /** * Returns the n last items of the specified array - * + * * @param {array} arr - * @param {number} n - * + * @param {number} n + * * @example * [ 1, 3, 4, 5 ], 2 => [ 4, 5 ] * [ 'a', 'b', 'c', 'd'], 3 => [ 'b', 'c', 'd' ] */ function getTail(arr, n) { - return arr.splice( -n); + return arr.slice(Math.max(arr.length - n, 1)); } /** * Returns CSV represebtation of two-dimentional numeric array. * https://en.wikipedia.org/wiki/Comma-separated_values - * + * * @param {array} arr * @return {string} - * + * * @example * [ * [ 0, 1, 2, 3, 4 ], * [ 10,11,12,13,14 ], * [ 20,21,22,23,24 ], * [ 30,31,32,33,34 ] - * ] - * => + * ] + * => * '0,1,2,3,4\n' * +'10,11,12,13,14\n' * +'20,21,22,23,24\n' * +'30,31,32,33,34' */ function toCsvText(arr) { - let arrStr = arr.map((elem, index) => - { - if (index != arr.length-1) - return elem.join(',') + '\n'; - else - return elem.join(','); - }).join(''); - return arrStr; + return arr.join('\n'); } /** * Transforms the numeric array into the according array of squares: * f(x) = x * x - * + * * @param {array} arr * @return {array} - * + * * @example * [ 0, 1, 2, 3, 4, 5 ] => [ 0, 1, 4, 9, 16, 25 ] * [ 10, 100, -1 ] => [ 100, 10000, 1 ] */ function toArrayOfSquares(arr) { - return arr.map((item, i, arr) => item ** 2); + return arr.map(value => value*value); } /** * Transforms the numeric array to the according moving sum array: - * f[n] = x[0] + x[1] + x[2] +...+ x[n] + * f[n] = x[0] + x[1] + x[2] +...+ x[n] * or f[n] = f[n-1] + x[n] - * + * * @param {array} arr * @return {array} - * + * * Example : * [ 1, 1, 1, 1, 1 ] => [ 1, 2, 3, 4, 5 ] * [ 10, -10, 10, -10, 10 ] => [ 10, 0, 10, 0, 10 ] - * [ 0, 0, 0, 0, 0] => [ 0, 0, 0, 0, 0] + * [ 0, 0, 0, 0, 0] => [ 0, 0, 0, 0, 0] * [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ] => [ 1, 3, 6, 10, 15, 21, 28, 36, 45, 55 ] */ function getMovingSum(arr) { - let sum = 0; - return arr.map((elem) => - { - elem += sum; - sum = elem; - return elem; - }); + return arr.map((x, y, arr) => arr.slice(0, y + 1).reduce((fs, val) => fs + val)); } /** * Returns every second item from the specified array: - * + * * @param {array} arr * @return {array} - * + * * Example : * [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ] => [ 2, 4, 6, 8, 10 ] * [ 'a', 'b', 'c' , null ] => [ "b", null ] * [ "a" ] => [] */ function getSecondItems(arr) { - return arr.filter((elem, index) => index % 2); + return arr.filter((x, y) => y % 2 === 1); } /** * Propagates every item in sequence its position times - * Returns an array that consists of: one first item, two second items, tree third items etc. - * - * @param {array} arr + * Returns an array that consists of: one first item, two second items, tree third items etc. + * + * @param {array} arr * @return {array} - * + * * @example : * [] => [] * [ 1 ] => [ 1 ] @@ -293,15 +261,18 @@ function getSecondItems(arr) { * [ 1,2,3,4,5 ] => [ 1, 2,2, 3,3,3, 4,4,4,4, 5,5,5,5,5 ] */ function propagateItemsByPositionIndex(arr) { - return arr.reduce((acc, elem, index) => acc.concat( - Array.from({length: index + 1}, () => elem)), [] - ); + let copy = []; + arr.map((x, y) => { + copy = copy.concat(new Array(y + 1).fill(x)); + return x; + }); + return copy; } -/** +/** * Returns the 3 largest numbers from the specified array - * + * * @param {array} arr * @return {array} * @@ -313,16 +284,17 @@ function propagateItemsByPositionIndex(arr) { * [ 10, 10, 10, 10 ] => [ 10, 10, 10 ] */ function get3TopItems(arr) { - return arr.sort((a, b) => b - a).slice(0, 3); + arr.sort(function(a, b){return b-a}); + return arr.slice(0,3); } - - -/** + + +/** * Returns the number of positive numbers from specified array - * + * * @param {array} arr * @return {number} - * + * * @example * [ ] => 0 * [ -1, 0, 1 ] => 1 @@ -331,34 +303,16 @@ function get3TopItems(arr) { * [ 1, '2' ] => 1 */ function getPositivesCount(arr) { - throw new Error('Not implemented'); + return arr.filter((x) => (x > 0) && (Number(x) === x)).length; } + -/** - * Sorts digit names - * - * @param {array} arr - * @return {array} - * - * @example - * [] => [] - * [ 'nine','one' ] => [ 'one', 'nine' ] - * [ 'one','two','three' ] => [ 'one','two', 'three' ] - * [ 'nine','eight','nine','eight'] => [ 'eight','eight','nine','nine'] - * [ 'one','one','one','zero' ] => [ 'zero','one','one','one' ] - */ -function sortDigitNamesByNumericOrder(arr) { - const mapped1 = { 0: 'zero', 1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five', 6: 'six', 7: 'seven', 8: 'eight', 9: 'nine' }; - const mapped2 = { 'zero': 0, 'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6, 'seven': 7, 'eight': 8, 'nine': 9 }; - return arr.map(x => mapped2[x]).sort().map(x => mapped1[x]); -} - -/** +/** * Returns the sum of all items in the specified array of numbers - * + * * @param {array} arr * @return {number} - * + * * @example * [] => 0 * [ 1, 2, 3 ] => 6 @@ -366,15 +320,15 @@ function sortDigitNamesByNumericOrder(arr) { * [ 1, 10, 100, 1000 ] => 1111 */ function getItemsSum(arr) { - return arr.reduce((acc, elem) => acc + elem, 0); + return arr.reduce((a, b) => a + b, 0); } - -/** + +/** * Returns the number of all falsy value in the specified array - * + * * @param {array} arr * @return {array} - * + * * @example * [] => 0 * [ 1, '', 3 ] => 1 @@ -382,61 +336,49 @@ function getItemsSum(arr) { * [ null, undefined, NaN, false, 0, '' ] => 6 */ function getFalsyValuesCount(arr) { - let sum = 0; - arr.map(elem => - { - if (Boolean(elem) == 0) - return sum++; - }); - return sum; + return arr.filter((x) => !x).length; } /** - * Returns a number of all occurences of the specified item in an array - * + * Returns a number of all occurences of the specified item in an array + * * @param {array} arr - * @param {any} item + * @param {any} item * @return {number} - * + * * @example * [ 0, 0, 1, 1, 1, 2 ], 1 => 3 * [ 1, 2, 3, 4, 5 ], 0 => 0 * [ 'a','b','c','c' ], 'c'=> 2 - * [ null, undefined, null ], null => 2 + * [ null, undefined, null ], null => 2 * [ true, 0, 1, 'true' ], true => 1 */ function findAllOccurences(arr, item) { - let num = 0; - arr.map(elem => - { - if (elem === item) - return num++; - }) - return num; + return arr.reduce(function(n, value) {return n + (value === item);}, 0); } /** - * Concatenates all elements from specified array into single string with ',' delimeter - * - * @param {array} arr + * Concatenates all elements from specified array into single string with ',' delimeter + * + * @param {array} arr * @return {string} - * + * * @example * [0, false, 'cat', NaN, true, ''] => '0,false,cat,NaN,true,' * [1, 2, 3, 4, 5] => '1,2,3,4,5' * ['rock', 'paper', 'scissors'] => 'rock,paper,scissors' */ function toStringList(arr) { - return arr.join(); + return arr.join(','); } /** * Sorts the specified array by country name first and city name (if countries are equal) in ascending order. - * + * * @param {array} arr * @return {array} - * + * * @example * [ * { country: 'Russia', city: 'Moscow' }, @@ -445,7 +387,7 @@ function toStringList(arr) { * { country: 'Russia', city: 'Saint Petersburg' }, * { country: 'Poland', city: 'Krakow' }, * { country: 'Belarus', city: 'Brest' } - * ] + * ] * => * [ * { country: 'Belarus', city: 'Brest' }, @@ -456,61 +398,54 @@ function toStringList(arr) { * { country: 'Russia', city: 'Saint Petersburg' } */ function sortCitiesArray(arr) { - function compareLocation(a, b) { - if (a.country < b.country) { - return -1; - } + return arr.sort((a, b) => { if (a.country > b.country) { - return 1; + return 1; + } + if (a.country < b.country) { + return -1; } - if (a.country === b.country) { - if (a.city < b.city) { - return -1; - } - if (a.city > b.city) { - return 1; - } - if (a.city === b.city) { - return 0; - } + if (a.city > b.city) { + return 1; } - } - return arr.sort(compareLocation); + return -1; + }); } /** * Creates an indentity matrix of the specified size - * + * * @param {number} n * @return {array} - * + * * @example * 1 => [[1]] - * + * * 2 => [[1,0], * [0,1]] - * + * * [[1,0,0,0,0], * [0,1,0,0,0], * 5 => [0,0,1,0,0], * [0,0,0,1,0], - * [0,0,0,0,1]] + * [0,0,0,0,1]] */ function getIdentityMatrix(n) { - return Array.from({length: n}, function (elem, index) { - let row = new Array(n).fill(0, 0, n); - row[index] = 1; - return row; - }); + return new Array(n).fill(0).map((x, y) => new Array(n).fill(0).map((x, y_) => { + if (y === y_) { + return 1; + } + return 0; + })); } /** * Creates an array of integers from the specified start to end (inclusive) - * + * * @param {number} start * @param {number} end * @return {array} - * + * * @example * 1, 5 => [ 1, 2, 3, 4, 5 ] * -2, 2 => [ -2, -1, 0, 1, 2 ] @@ -518,7 +453,7 @@ function getIdentityMatrix(n) { * 3, 3 => [ 3 ] */ function getIntervalArray(start, end) { - return Array.from({length: end - start + 1}, (elem, index) => index + start); + return Array(end - start + 1).fill().map((x, y) => start + y); } /** @@ -526,21 +461,14 @@ function getIntervalArray(start, end) { * * @param {array} arr * @return {array} - * + * * @example * [ 1, 2, 3, 3, 2, 1 ] => [ 1, 2, 3 ] * [ 'a', 'a', 'a', 'a' ] => [ 'a' ] * [ 1, 1, 2, 2, 3, 3, 4, 4] => [ 1, 2, 3, 4] */ function distinct(arr) { - let resArr = []; - arr.map(elem => - { - if (resArr.indexOf(elem) == -1) - resArr.push(elem); - return resArr; - }); - return resArr; + return arr.filter((x, y) => arr.indexOf(x) === y); } /** @@ -562,27 +490,30 @@ function distinct(arr) { * { country: 'Belarus', city: 'Grodno' }, * { country: 'Belarus', city: 'Minsk' }, * { country: 'Poland', city: 'Lodz' } - * ], - * item => item.country, + * ], + * item => item.country, * item => item.city * ) - * => + * => * Map { * "Belarus" => ["Brest", "Grodno", "Minsk"], - * "Russia" => ["Omsk", "Samara"], + * "Russia" => ["Omsk", "Samara"], * "Poland" => ["Lodz"] * } */ function group(array, keySelector, valueSelector) { - let _map = new Map(); - array.map((x, ind) => - { - if( _map.has(keySelector(x)) ) - _map.get(keySelector(x)).push(valueSelector(x)); - else - _map.set(keySelector(x), [valueSelector(x)]); - }); - return _map; + const map = new Map(); + array.map((x) => [keySelector(x), valueSelector(x)]).map((x) => { + if (map.has(x[0])) { + map.set(x[0], map.get(x[0]).concat(x[1])); + } else { + const arr = Array(1); + arr[0] = x[1]; + map.set(x[0], arr); + } + return x; + }); + return map; } @@ -592,18 +523,15 @@ function group(array, keySelector, valueSelector) { * @param {array} arr * @param {Function} childrenSelector, a transform function to apply to each element that returns an array of children * @return {array} - * + * * @example * [[1, 2], [3, 4], [5, 6]], (x) => x => [ 1, 2, 3, 4, 5, 6 ] * ['one','two','three'], x=>x.split('') => ['o','n','e','t','w','o','t','h','r','e','e'] */ function selectMany(arr, childrenSelector) { - let myArr = []; - arr.map(elem => - { - myArr.push(...childrenSelector(elem)); - }); - return myArr; + let retArr = []; + arr.map(childrenSelector).map((x) => retArr = retArr.concat(x)); + return retArr; } @@ -613,80 +541,47 @@ function selectMany(arr, childrenSelector) { * @param {array} arr * @param {array} indexes * @return {any} element from array - * + * * @example - * [[1, 2], [3, 4], [5, 6]], [0,0] => 1 (arr[0][0]) - * ['one','two','three'], [2] => 'three' (arr[2]) + * [[1, 2], [3, 4], [5, 6]], [0,0] => 1 (arr[0][0]) + * ['one','two','three'], [2] => 'three' (arr[2]) * [[[ 1, 2, 3]]], [ 0, 0, 1 ] => 2 (arr[0][0][1]) */ function getElementByIndexes(arr, indexes) { - return indexes.map(elem => arr = arr[elem])[indexes.length - 1]; -} - - -/** - * Swaps the head and tail of the specified array: - * the head (first half) of array move to the end, the tail (last half) move to the start. - * The middle element (if exists) leave on the same position. - * - * - * @param {array} arr - * @return {array} - * - * @example - * [ 1, 2, 3, 4, 5 ] => [ 4, 5, 3, 1, 2 ] - * \----/ \----/ - * head tail - * - * [ 1, 2 ] => [ 2, 1 ] - * [ 1, 2, 3, 4, 5, 6, 7, 8 ] => [ 5, 6, 7, 8, 1, 2, 3, 4 ] - * - */ -function swapHeadAndTail(arr) { - let len = Math.floor(arr.length / 2); - let head = arr.splice(0, len); - let tail = arr.splice(arr.length-len, len); - let array = []; - array.push(...tail); - if(arr.length % 2) { - let middle = arr.splice(0, 1); - array.push(...middle) - } - array.push(...head); - return array; + return arr.join().split(',')[indexes.reduce((accumulator, value) => accumulator + value)]; } module.exports = { - findElement: findElement, - generateOdds: generateOdds, - doubleArray: doubleArray, - getArrayOfPositives: getArrayOfPositives, - getArrayOfStrings: getArrayOfStrings, - removeFalsyValues: removeFalsyValues, - getUpperCaseStrings: getUpperCaseStrings, - getStringsLength: getStringsLength, - insertItem: insertItem, - getHead: getHead, - getTail: getTail, - toCsvText: toCsvText, - toStringList: toStringList, - toArrayOfSquares: toArrayOfSquares, - getMovingSum: getMovingSum, - getSecondItems: getSecondItems, - propagateItemsByPositionIndex: propagateItemsByPositionIndex, - get3TopItems: get3TopItems, - getPositivesCount: getPositivesCount, - sortDigitNamesByNumericOrder: sortDigitNamesByNumericOrder, - getItemsSum: getItemsSum, - getFalsyValuesCount: getFalsyValuesCount, - findAllOccurences: findAllOccurences, - sortCitiesArray: sortCitiesArray, - getIdentityMatrix: getIdentityMatrix, - getIntervalArray: getIntervalArray, - distinct: distinct, - group: group, - selectMany: selectMany, - getElementByIndexes: getElementByIndexes, - swapHeadAndTail: swapHeadAndTail + findElement: findElement, + generateOdds: generateOdds, + doubleArray: doubleArray, + getArrayOfPositives: getArrayOfPositives, + getArrayOfStrings: getArrayOfStrings, + removeFalsyValues: removeFalsyValues, + getUpperCaseStrings: getUpperCaseStrings, + getStringsLength: getStringsLength, + insertItem: insertItem, + getHead: getHead, + getTail: getTail, + toCsvText: toCsvText, + toStringList: toStringList, + toArrayOfSquares: toArrayOfSquares, + getMovingSum: getMovingSum, + getSecondItems: getSecondItems, + propagateItemsByPositionIndex: propagateItemsByPositionIndex, + get3TopItems: get3TopItems, + getPositivesCount: getPositivesCount, + sortDigitNamesByNumericOrder: sortDigitNamesByNumericOrder, + getItemsSum: getItemsSum, + getFalsyValuesCount: getFalsyValuesCount, + findAllOccurences: findAllOccurences, + sortCitiesArray: sortCitiesArray, + getIdentityMatrix: getIdentityMatrix, + getIntervalArray: getIntervalArray, + distinct: distinct, + group: group, + selectMany: selectMany, + getElementByIndexes: getElementByIndexes, + swapHeadAndTail: swapHeadAndTail }; diff --git a/task/05-regex-tasks.js b/task/05-regex-tasks.js index 929d9a533..a683f54d2 100644 --- a/task/05-regex-tasks.js +++ b/task/05-regex-tasks.js @@ -31,7 +31,7 @@ * @return {RegExp} */ function getRegexForGuid() { - let reg = '[0-9a-f]'; + let reg = '[0-9a-f]'; return new RegExp('^{'+reg+'{8}-'+reg+'{4}-'+reg+'{4}-'+reg+'{4}-'+reg+'{12}}$', 'i'); } @@ -54,7 +54,7 @@ function getRegexForGuid() { * */ function getRegexForPitSpot() { - return new RegExp(/.*p.t.*/); + return new RegExp(/.*p.t.*/); } @@ -73,7 +73,7 @@ function getRegexForPitSpot() { * @return {RegExp} */ function getRegexForIPv4() { - return /^(([0-2][0-9]{2}|[0-9]{1,2})\.){3}([0-2][0-9]{2}|[0-9]{1,2})$/; + return /^(([0-2][0-9]{2}|[0-9]{1,2})\.){3}([0-2][0-9]{2}|[0-9]{1,2})$/; } @@ -92,34 +92,10 @@ function getRegexForIPv4() { * @return {RegExp} */ function getRegexForSSN() { - return /\d{2}[1-9]-\d{1}[1-9]-\d{3}[1-9]/; + return /\d{2}[1-9]-\d{1}[1-9]-\d{3}[1-9]/; } -/** - * Returns the password validator regex. - * Regex will validate a password to make sure it meets the follwing criteria: - * - At least specified characters long (argument minLength) - * - Contains a lowercase letter - * - Contains an uppercase letter - * - Contains a number - * - Valid passwords will only be alphanumeric characters. - * - * @param {number} minLength - * @return {Regex} - * - * @example - * let validator = getPasswordValidator(6); - * 'password'.match(validator) => false - * 'Pa55Word'.match(validator) => true - * 'PASSw0rd'.match(validator) => true - * 'PASSW0RD'.match(validator) => false - * 'Pa55'.match(validator) => false - */ -function getPasswordValidator(minLength) { - return new RegExp('^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)[A-Za-z\\d]{'+minLength+',}'); -} - module.exports = { getRegexForGuid: getRegexForGuid, diff --git a/task/06-conditions-n-loops-tasks.js b/task/06-conditions-n-loops-tasks.js index cabade980..7b632835d 100644 --- a/task/06-conditions-n-loops-tasks.js +++ b/task/06-conditions-n-loops-tasks.js @@ -9,80 +9,6 @@ **************************************************************************************************/ -/** - * Returns the 'Fizz','Buzz' or an original number using the following rules: - * 1) return original number - * 2) but if number multiples of three return 'Fizz' - * 3) for the multiples of five return 'Buzz' - * 4) for numbers which are multiples of both three and five return 'FizzBuzz' - * - * @param {number} num - * @return {any} - * - * @example - * 2 => 2 - * 3 => 'Fizz' - * 5 => 'Buzz' - * 4 => 4 - * 15 => 'FizzBuzz' - * 20 => 'Buzz' - * 21 => 'Fizz' - * - */ -function getFizzBuzz(num) { - if((num % 3 === 0) && (num % 5 === 0)) { - return 'FizzBuzz' - } else if(num % 5 === 0) { - return'Buzz' - } else if (num % 3 === 0) { - return 'Fizz' - } - return num -} - - -/** - * Returns the factorial of the specified integer n. - * - * @param {number} n - * @return {number} - * - * @example: - * 1 => 1 - * 5 => 120 - * 10 => 3628800 - */ -function getFactorial(n) { - if (n < 0) - return -1; - else if (n === 0) - return 1; - else { - return (n * getFactorial(n - 1)); - } -} - - -/** - * Returns the sum of integer numbers between n1 and n2 (inclusive). - * - * @param {number} n1 - * @param {number} n2 - * @return {number} - * - * @example: - * 1,2 => 3 ( = 1+2 ) - * 5,10 => 45 ( = 5+6+7+8+9+10 ) - * -1,1 => 0 ( = -1 + 0 + 1 ) - */ -function getSumBetweenNumbers(n1, n2) { - let count = 0; - for(let i = n1; i <=n2; i++ ) { - count +=i - } - return count; -} - /** * Returns true, if a triangle can be built with the specified sides a,b,c and false in any other ways. @@ -103,48 +29,6 @@ function isTriangle(a,b,c) { } -/** - * Returns true, if two specified axis-aligned rectangles overlap, otherwise false. - * Each rectangle representing by object - * { - * top: 5, - * left: 5, - * width: 20, - * height: 10 - * } - * - * (5;5) - * ------------- - * | | - * | | height = 10 - * ------------- - * width=20 - * - * NOTE: Please use canvas coordinate space (https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Drawing_shapes#The_grid), - * it differs from Cartesian coordinate system. - * - * @param {object} rect1 - * @param {object} rect2 - * @return {bool} - * - * @example: - * { top: 0, left: 0, width: 10, height: 10 }, - * { top: 5, left: 5, width: 20, height: 20 } => true - * - * { top: 0, left: 0, width: 10, height: 10 }, - * { top:20, left:20, width: 20, height: 20 } => false - * - */ -function doRectanglesOverlap(rect1, rect2) { - return !( - rect1.left + rect1.width < rect2.left || - rect2.left + rect2.width < rect1.left || - rect1.top + rect1.height < rect2.top || - rect2.top + rect2.height < rect1.top - ); -} - - /** * Returns true, if point lies inside the circle, otherwise false. * Circle is an object of @@ -178,58 +62,6 @@ function isInsideCircle(circle, point) { } -/** - * Returns the first non repeated char in the specified strings otherwise returns null. - * - * @param {string} str - * @return {string} - * - * @example: - * 'The quick brown fox jumps over the lazy dog' => 'T' - * 'abracadabra' => 'c' - * 'entente' => null - */ -function findFirstSingleChar(str) { - for (let i = 0; i < str.length; i++) { - if (str.indexOf(str[i]) == str.lastIndexOf(str[i])) { - return str[i]; - } - } - - return null; -} - - -/** - * Returns the string representation of math interval, specified by two points and include / exclude flags. - * See the details: https://en.wikipedia.org/wiki/Interval_(mathematics) - * - * Please take attention, that the smaller number should be the first in the notation - * - * @param {number} a - * @param {number} b - * @param {bool} isStartIncluded - * @param {bool} isEndIncluded - * @return {string} - * - * @example - * 0, 1, true, true => '[0, 1]' - * 0, 1, true, false => '[0, 1)' - * 0, 1, false, true => '(0, 1]' - * 0, 1, false, false => '(0, 1)' - * Smaller number has to be first : - * 5, 3, true, true => '[3, 5]' - * - */ -function getIntervalString(a, b, isStartIncluded, isEndIncluded) { - let res = ""; - res += (isStartIncluded && res.length === 0) ? "[" : "("; - res += a <= b ? `${a}, ${b}` : `${b}, ${a}`; - res += isEndIncluded ? "]" : ")"; - return res; -} - - /** * Reverse the specified string (put all chars in reverse order) * @@ -243,7 +75,7 @@ function getIntervalString(a, b, isStartIncluded, isEndIncluded) { * 'noon' => 'noon' */ function reverseString(str) { - return str.split('').reverse().join(''); + return [...str].reverse().join(''); } @@ -260,150 +92,9 @@ function reverseString(str) { * 34143 => 34143 */ function reverseInteger(num) { - return Number.parseInt(reverseString(num.toString())); -} - - -/** - * Validates the CCN (credit card number) and return true if CCN is valid - * and false otherwise. - * - * See algorithm here : https://en.wikipedia.org/wiki/Luhn_algorithm - * - * @param {number} cnn - * @return {boolean} - * - * @example: - * 79927398713 => true - * 4012888888881881 => true - * 5123456789012346 => true - * 378282246310005 => true - * 371449635398431 => true - * - * 4571234567890111 => false - * 5436468789016589 => false - * 4916123456789012 => false - */ -function isCreditCardNumber(ccn) { - ccn = [...String(ccn)].reverse(); - ccn = ccn.reduce(function(sum, val, ind) - { - let dig = Number(val); - if(ind % 2) - dig *= 2; - sum += Math.floor(dig / 10); - sum += dig % 10; - return sum; - }, 0); - return (ccn * 3) % 10 == 0; -} - - -/** - * Returns the digital root of integer: - * step1 : find sum of all digits - * step2 : if sum > 9 then goto step1 otherwise return the sum - * - * @param {number} n - * @return {number} - * - * @example: - * 12345 ( 1+2+3+4+5 = 15, 1+5 = 6) => 6 - * 23456 ( 2+3+4+5+6 = 20, 2+0 = 2) => 2 - * 10000 ( 1+0+0+0+0 = 1 ) => 1 - * 165536 (1+6+5+5+3+6 = 26, 2+6 = 8) => 8 - */ -function getDigitalRoot(num) { - do{ - let sum = 0; - while(num > 0){ - sum += num % 10; - num = Math.floor(num / 10); - } - num = sum; - }while(num > 9); - return num; -} - - -/** - * Returns true if the specified string has the balanced brackets and false otherwise. - * Balanced means that is, whether it consists entirely of pairs of opening/closing brackets - * (in that order), none of which mis-nest. - * Brackets include [],(),{},<> - * - * @param {string} str - * @return {boolean} - * - * @example: - * '' => true - * '[]' => true - * '{}' => true - * '() => true - * '[[]' => false - * '][' => false - * '[[][][[]]]' => true - * '[[][]][' => false - * '{)' = false - * '{[(<{[]}>)]}' = true - */ -function isBracketsBalanced(str) { - let pair = { - '>': '<', - ')': '(', - ']': '[', - '}': '{' - } - let res = [...str].reduce(function(acc, x, ind) - { - if (['(', '{', '[', '<'].indexOf(x) != -1) - acc.push(x); - else - { - if (acc.length > 0 && acc[acc.length - 1] == pair[x]) - acc.pop(); - else - acc.push(x); - } - return acc; - }, []); - return res.length == 0; -} - - -/** - * Returns the human readable string of time period specified by the start and end time. - * The result string should be constrcuted using the folliwing rules: - * - * --------------------------------------------------------------------- - * Difference | Result - * --------------------------------------------------------------------- - * 0 to 45 seconds | a few seconds ago - * 45 to 90 seconds | a minute ago - * 90 seconds to 45 minutes | 2 minutes ago ... 45 minutes ago - * 45 to 90 minutes | an hour ago - * 90 minutes to 22 hours | 2 hours ago ... 22 hours ago - * 22 to 36 hours | a day ago - * 36 hours to 25 days | 2 days ago ... 25 days ago - * 25 to 45 days | a month ago - * 45 to 345 days | 2 months ago ... 11 months ago - * 345 to 545 days (1.5 years) | a year ago - * 546 days+ | 2 years ago ... 20 years ago - * --------------------------------------------------------------------- - * - * @param {Date} startDate - * @param {Date} endDate - * @return {string} - * - * @example - * Date('2000-01-01 01:00:00.100'), Date('2000-01-01 01:00:00.200') => 'a few seconds ago' - * Date('2000-01-01 01:00:00.100'), Date('2000-01-01 01:00:05.000') => '5 minutes ago' - * Date('2000-01-01 01:00:00.100'), Date('2000-01-02 03:00:05.000') => 'a day ago' - * Date('2000-01-01 01:00:00.100'), Date('2015-01-02 03:00:05.000') => '15 years ago' - * - */ -function timespanToHumanString(startDate, endDate) { - throw new Error('Not implemented'); + let str = ''; + str += num; + return [...str].reverse().join(''); } @@ -431,81 +122,6 @@ function toNaryString(num, n) { } -/** - * Returns the commom directory path for specified array of full filenames. - * - * @param {array} pathes - * @return {string} - * - * @example: - * ['/web/images/image1.png', '/web/images/image2.png'] => '/web/images/' - * ['/web/assets/style.css', '/web/scripts/app.js', 'home/setting.conf'] => '' - * ['/web/assets/style.css', '/.bin/mocha', '/read.me'] => '/' - * ['/web/favicon.ico', '/web-scripts/dump', '/webalizer/logs'] => '/' - */ -function getCommonDirectoryPath(pathes) { - throw new Error('Not implemented'); -} - - -/** - * Returns the product of two specified matrixes. - * See details: https://en.wikipedia.org/wiki/Matrix_multiplication - * - * @param {array} m1 - * @param {array} m2 - * @return {array} - * - * @example: - * [[ 1, 0, 0 ], [[ 1, 2, 3 ], [[ 1, 2, 3 ], - * [ 0, 1, 0 ], X [ 4, 5, 6 ], => [ 4, 5, 6 ], - * [ 0, 0, 1 ]] [ 7, 8, 9 ]] [ 7, 8, 9 ]] - * - * [[ 4 ], - * [[ 1, 2, 3]] X [ 5 ], => [[ 32 ]] - * [ 6 ]] - * - */ -function getMatrixProduct(m1, m2) { - throw new Error('Not implemented'); -} - - -/** - * Returns the evaluation of the specified tic-tac-toe position. - * See the details: https://en.wikipedia.org/wiki/Tic-tac-toe - * - * Position is provides as 3x3 array with the following values: 'X','0', undefined - * Function should return who is winner in the current position according to the game rules. - * The result can be: 'X','0',undefined - * - * @param {array} position - * @return {string} - * - * @example - * - * [[ 'X', ,'0' ], - * [ ,'X','0' ], => 'X' - * [ , ,'X' ]] - * - * [[ '0','0','0' ], - * [ ,'X', ], => '0' - * [ 'X', ,'X' ]] - * - * [[ '0','X','0' ], - * [ ,'X', ], => undefined - * [ 'X','0','X' ]] - * - * [[ , , ], - * [ , , ], => undefined - * [ , , ]] - * - */ -function evaluateTicTacToePosition(position) { - throw new Error('Not implemented'); -} - - module.exports = { getFizzBuzz: getFizzBuzz, getFactorial: getFactorial, diff --git a/task/07-yield-tasks.js b/task/07-yield-tasks.js index f975baff5..a2369790a 100644 --- a/task/07-yield-tasks.js +++ b/task/07-yield-tasks.js @@ -33,19 +33,7 @@ * */ function* get99BottlesOfBeer() { - for (let bottles = 99; bottles > 2; bottles--) { - yield `${bottles} bottles of beer on the wall, ${bottles} bottles of beer.`; - yield `Take one down and pass it around, ${bottles - 1} bottles of beer on the wall.`; - } - - yield `2 bottles of beer on the wall, 2 bottles of beer.`; - yield `Take one down and pass it around, 1 bottle of beer on the wall.`; - - yield `1 bottle of beer on the wall, 1 bottle of beer.`; - yield `Take one down and pass it around, no more bottles of beer on the wall.`; - - yield 'No more bottles of beer on the wall, no more bottles of beer.'; - yield 'Go to the store and buy some more, 99 bottles of beer on the wall.'; + throw new Error('Not implemented'); } @@ -59,19 +47,7 @@ function* get99BottlesOfBeer() { * */ function* getFibonacciSequence() { - yield 0; - yield 1; - - let last = 0; - let current = 1; - let new_val = 1; - - while (true){ - yield new_val; - last = current; - current = new_val; - new_val = last + current; - } + throw new Error('Not implemented'); } @@ -106,14 +82,7 @@ function* getFibonacciSequence() { * */ function* depthTraversalTree(root) { - let q1 = [root]; - while (q1.length) { - let node = q1.pop(); - yield node; - if (node.children) { - q1.push(...node.children.reverse()); - } - } + throw new Error('Not implemented'); } @@ -139,24 +108,7 @@ function* depthTraversalTree(root) { * */ function* breadthTraversalTree(root) { - let queue = [root]; - - while (queue.length != 0) { - let node = queue.shift(); - yield node; - - if (node.children !== undefined) { - - for (let child of node.children) { - - if (queue.length == 0 && child.children === undefined) { - yield child; - } else { - queue.push(child); - } - } - } - } + throw new Error('Not implemented'); } @@ -174,18 +126,7 @@ function* breadthTraversalTree(root) { * [ 1, 3, 5, ... ], [ -1 ] => [ -1, 1, 3, 5, ...] */ function* mergeSortedSequences(source1, source2) { - const sources = [source1(), source2()]; - let it = [sources[0].next(), sources[1].next()]; - - while (true) { - if (it[0].value >= it[1].value || it[0].value === undefined) { - yield it[1].value; - it[1] = sources[1].next(); - } else { - yield it[0].value; - it[0] = sources[0].next(); - } - } + throw new Error('Not implemented'); } diff --git a/task/08-objects-tasks.js b/task/08-objects-tasks.js index aa120dd0b..610b1e7b2 100644 --- a/task/08-objects-tasks.js +++ b/task/08-objects-tasks.js @@ -23,12 +23,7 @@ * console.log(r.getArea()); // => 200 */ function Rectangle(width, height) { - this.width = width; - this.height = height; - - this.getArea = () => { - return this.width * this.height - } + throw new Error('Not implemented'); } diff --git a/task/09-functions-n-closures-tasks.js b/task/09-functions-n-closures-tasks.js index e22e3ac4e..6ba9dcedd 100644 --- a/task/09-functions-n-closures-tasks.js +++ b/task/09-functions-n-closures-tasks.js @@ -26,9 +26,7 @@ * */ function getComposition(f,g) { - return function (x) { - return f(g(x)); - } + throw new Error('Not implemented'); } @@ -49,9 +47,7 @@ function getComposition(f,g) { * */ function getPowerFunction(exponent) { - return function (number) { - return Math.pow(number, exponent); - }; + throw new Error('Not implemented'); } @@ -69,10 +65,7 @@ function getPowerFunction(exponent) { * getPolynom() => null */ function getPolynom() { - var tmp = Array.from(arguments).reverse(); - return (x) => { - return tmp.reduce((prev, curr, index) => prev+curr*Math.pow(x,index),0); - }; + throw new Error('Not implemented'); } @@ -91,10 +84,7 @@ function getPolynom() { * memoizer() => the same random number (next run, returns the previous cached result) */ function memoize(func) { - let cashed = func(); - return function() { - return cashed - } + throw new Error('Not implemented'); } @@ -114,16 +104,7 @@ function memoize(func) { * retryer() => 2 */ function retry(func, attempts) { - return()=>{ - for (var i = 0; i < attempts;){ - try{ - return func(); - } catch(err){ - i += 1; - } - } - return i; - }; + throw new Error('Not implemented'); } @@ -190,10 +171,7 @@ function partialUsingArguments(fn) { * getId10() => 11 */ function getIdGeneratorFunction(startFrom) { - var curr = startFrom; - return function() { - return startFrom++; - } + throw new Error('Not implemented'); } diff --git a/task/10-katas-1-tasks.js b/task/10-katas-1-tasks.js index 353c390bf..5128b0695 100644 --- a/task/10-katas-1-tasks.js +++ b/task/10-katas-1-tasks.js @@ -17,18 +17,8 @@ * ] */ function createCompassPoints() { + throw new Error('Not implemented'); var sides = ['N','E','S','W']; // use array of cardinal directions only! - res = []; - - function getDoubleSide(side1, side2) { - switch (side1) { - case 'E': - return 'SE'; - case 'W': - return 'NW'; - default: - return side1 + side2; - } } From b01861a8ead1a02f6de460bd81a34d1559e74929 Mon Sep 17 00:00:00 2001 From: Shagoysai <34492748+Shagoysai@users.noreply.github.com> Date: Sat, 12 Jun 2021 16:23:39 +0300 Subject: [PATCH 20/40] Add files via upload From 9312979bc1ed13d322aded4ea2959272ed941abd Mon Sep 17 00:00:00 2001 From: Shagoysai <34492748+Shagoysai@users.noreply.github.com> Date: Sat, 12 Jun 2021 16:31:26 +0300 Subject: [PATCH 21/40] Update .travis.yml --- .travis.yml | 3 --- 1 file changed, 3 deletions(-) diff --git a/.travis.yml b/.travis.yml index dc6955648..afd0508c9 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,6 +1,3 @@ -install: - - bundle install --path vendor/bundle - - npm install language: node_js node_js: - "14.17.0" From e21126ed795fb23e9293e82efae025af99b5f1a2 Mon Sep 17 00:00:00 2001 From: Shagoysai <34492748+Shagoysai@users.noreply.github.com> Date: Sat, 12 Jun 2021 16:37:43 +0300 Subject: [PATCH 22/40] Update 04-arrays-tasks.js --- task/04-arrays-tasks.js | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/task/04-arrays-tasks.js b/task/04-arrays-tasks.js index c6e518b12..928f85e17 100644 --- a/task/04-arrays-tasks.js +++ b/task/04-arrays-tasks.js @@ -38,6 +38,11 @@ function findElement(arr, value) { * [0, 1, 2, 3, 4, 5] => [0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5] * [] => [] */ + +function generateOdds(len) { + throw new Error('Not implemented'); +} + function doubleArray(arr) { arr.map(elem => { From 65eda383fbbf3e86e9d3485993e2ebc51a090083 Mon Sep 17 00:00:00 2001 From: Shagoysai <34492748+Shagoysai@users.noreply.github.com> Date: Sat, 12 Jun 2021 16:41:58 +0300 Subject: [PATCH 23/40] Update 04-arrays-tasks.js --- task/04-arrays-tasks.js | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/task/04-arrays-tasks.js b/task/04-arrays-tasks.js index 928f85e17..79531683b 100644 --- a/task/04-arrays-tasks.js +++ b/task/04-arrays-tasks.js @@ -161,6 +161,9 @@ function getHead(arr, n) { return arr.slice(0, n); } +function sortDigitNamesByNumericOrder(arr) { + throw new Error('Not implemented'); +} /** * Returns the n last items of the specified array @@ -556,6 +559,9 @@ function getElementByIndexes(arr, indexes) { return arr.join().split(',')[indexes.reduce((accumulator, value) => accumulator + value)]; } +function swapHeadAndTail(arr) { + throw new Error('Not implemented'); +} module.exports = { findElement: findElement, From 19f4c53db7eaf14e99b9c860967d498398a656b1 Mon Sep 17 00:00:00 2001 From: Shagoysai <34492748+Shagoysai@users.noreply.github.com> Date: Sat, 12 Jun 2021 16:44:25 +0300 Subject: [PATCH 24/40] Update 05-regex-tasks.js --- task/05-regex-tasks.js | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/task/05-regex-tasks.js b/task/05-regex-tasks.js index a683f54d2..42027562e 100644 --- a/task/05-regex-tasks.js +++ b/task/05-regex-tasks.js @@ -95,7 +95,9 @@ function getRegexForSSN() { return /\d{2}[1-9]-\d{1}[1-9]-\d{3}[1-9]/; } - +function getPasswordValidator(minLength) { + throw new Error('Not implemented'); +} module.exports = { getRegexForGuid: getRegexForGuid, From 42dde8a4ae0a3335fc84f74c84ec2772d6d30bb8 Mon Sep 17 00:00:00 2001 From: Shagoysai <34492748+Shagoysai@users.noreply.github.com> Date: Sat, 12 Jun 2021 16:52:56 +0300 Subject: [PATCH 25/40] Update 05-regex-tasks.js --- task/05-regex-tasks.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/task/05-regex-tasks.js b/task/05-regex-tasks.js index 42027562e..ff4986ed7 100644 --- a/task/05-regex-tasks.js +++ b/task/05-regex-tasks.js @@ -96,7 +96,7 @@ function getRegexForSSN() { } function getPasswordValidator(minLength) { - throw new Error('Not implemented'); + return new RegExp('^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)[A-Za-z\\d]{'+minLength+',}'); } module.exports = { From 155cb47a8ac0de7ea28fab1fb040a57da5bfc2b6 Mon Sep 17 00:00:00 2001 From: Shagoysai <34492748+Shagoysai@users.noreply.github.com> Date: Sat, 12 Jun 2021 16:58:25 +0300 Subject: [PATCH 26/40] Update 06-conditions-n-loops-tasks.js --- task/06-conditions-n-loops-tasks.js | 126 +++++++++++++++++++++++++++- 1 file changed, 125 insertions(+), 1 deletion(-) diff --git a/task/06-conditions-n-loops-tasks.js b/task/06-conditions-n-loops-tasks.js index 7b632835d..f697cc9b8 100644 --- a/task/06-conditions-n-loops-tasks.js +++ b/task/06-conditions-n-loops-tasks.js @@ -24,6 +24,64 @@ * 10,1,1 => false * 10,10,10 => true */ +function getFizzBuzz(num) { + if((num % 3 === 0) && (num % 5 === 0)) { + return 'FizzBuzz' + } else if(num % 5 === 0) { + return'Buzz' + } else if (num % 3 === 0) { + return 'Fizz' + } + return num +} + +function getFactorial(n) { + if (n < 0) + return -1; + else if (n === 0) + return 1; + else { + return (n * getFactorial(n - 1)); + } +} + +function getSumBetweenNumbers(n1, n2) { + let count = 0; + for(let i = n1; i <=n2; i++ ) { + count +=i + } + return count; +} + +function doRectanglesOverlap(rect1, rect2) { + return !( + rect1.left + rect1.width < rect2.left || + rect2.left + rect2.width < rect1.left || + rect1.top + rect1.height < rect2.top || + rect2.top + rect2.height < rect1.top + ); +} + +function findFirstSingleChar(str) { + for (let i = 0; i < str.length; i++) { + if (str.indexOf(str[i]) == str.lastIndexOf(str[i])) { + return str[i]; + } + } + + return null; +} + +function getIntervalString(a, b, isStartIncluded, isEndIncluded) { + let res = ""; + res += (isStartIncluded && res.length === 0) ? "[" : "("; + res += a <= b ? `${a}, ${b}` : `${b}, ${a}`; + res += isEndIncluded ? "]" : ")"; + return res; +} + + + function isTriangle(a,b,c) { return a < b + c && b < a + c && c < a + b; } @@ -62,6 +120,8 @@ function isInsideCircle(circle, point) { } + + /** * Reverse the specified string (put all chars in reverse order) * @@ -121,6 +181,70 @@ function toNaryString(num, n) { return num.toString(n); } +function isCreditCardNumber(ccn) { + ccn = [...String(ccn)].reverse(); + ccn = ccn.reduce(function(sum, val, ind) + { + let dig = Number(val); + if(ind % 2) + dig *= 2; + sum += Math.floor(dig / 10); + sum += dig % 10; + return sum; + }, 0); + return (ccn * 3) % 10 == 0; +} + +function getDigitalRoot(num) { + do{ + let sum = 0; + while(num > 0){ + sum += num % 10; + num = Math.floor(num / 10); + } + num = sum; + }while(num > 9); + return num; +} + +function isBracketsBalanced(str) { + let pair = { + '>': '<', + ')': '(', + ']': '[', + '}': '{' + } + let res = [...str].reduce(function(acc, x, ind) + { + if (['(', '{', '[', '<'].indexOf(x) != -1) + acc.push(x); + else + { + if (acc.length > 0 && acc[acc.length - 1] == pair[x]) + acc.pop(); + else + acc.push(x); + } + return acc; + }, []); + return res.length == 0; +} + +function timespanToHumanString(startDate, endDate) { + throw new Error('Not implemented'); +} + +function getCommonDirectoryPath(pathes) { + throw new Error('Not implemented'); +} + +function getMatrixProduct(m1, m2) { + throw new Error('Not implemented'); +} + +function evaluateTicTacToePosition(position) { + throw new Error('Not implemented'); +} module.exports = { getFizzBuzz: getFizzBuzz, @@ -136,7 +260,7 @@ module.exports = { isCreditCardNumber: isCreditCardNumber, getDigitalRoot: getDigitalRoot, isBracketsBalanced: isBracketsBalanced, - timespanToHumanString : timespanToHumanString, + ToHumanString : timespanToHumanString, toNaryString: toNaryString, getCommonDirectoryPath: getCommonDirectoryPath, getMatrixProduct: getMatrixProduct, From b51537eff119695bc090be3ff3d3a7698c26d914 Mon Sep 17 00:00:00 2001 From: Shagoysai <34492748+Shagoysai@users.noreply.github.com> Date: Sat, 12 Jun 2021 17:00:53 +0300 Subject: [PATCH 27/40] Update 07-yield-tasks.js --- task/07-yield-tasks.js | 23 +++++++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-) diff --git a/task/07-yield-tasks.js b/task/07-yield-tasks.js index a2369790a..a504a845e 100644 --- a/task/07-yield-tasks.js +++ b/task/07-yield-tasks.js @@ -47,7 +47,19 @@ function* get99BottlesOfBeer() { * */ function* getFibonacciSequence() { - throw new Error('Not implemented'); + yield 0; + yield 1; + + let last = 0; + let current = 1; + let new_val = 1; + + while (true){ + yield new_val; + last = current; + current = new_val; + new_val = last + current; + } } @@ -82,7 +94,14 @@ function* getFibonacciSequence() { * */ function* depthTraversalTree(root) { - throw new Error('Not implemented'); + let q1 = [root]; + while (q1.length) { + let node = q1.pop(); + yield node; + if (node.children) { + q1.push(...node.children.reverse()); + } + } } From b1b94624f95cba339abb9f56c8ef66350704ad03 Mon Sep 17 00:00:00 2001 From: Shagoysai <34492748+Shagoysai@users.noreply.github.com> Date: Sat, 12 Jun 2021 17:01:16 +0300 Subject: [PATCH 28/40] Update 08-objects-tasks.js --- task/08-objects-tasks.js | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/task/08-objects-tasks.js b/task/08-objects-tasks.js index 610b1e7b2..aa120dd0b 100644 --- a/task/08-objects-tasks.js +++ b/task/08-objects-tasks.js @@ -23,7 +23,12 @@ * console.log(r.getArea()); // => 200 */ function Rectangle(width, height) { - throw new Error('Not implemented'); + this.width = width; + this.height = height; + + this.getArea = () => { + return this.width * this.height + } } From 50f9ee960de35c1beea1edc9c036607c6c0626b3 Mon Sep 17 00:00:00 2001 From: Shagoysai <34492748+Shagoysai@users.noreply.github.com> Date: Sat, 12 Jun 2021 17:03:19 +0300 Subject: [PATCH 29/40] Update 09-functions-n-closures-tasks.js --- task/09-functions-n-closures-tasks.js | 34 ++++++++++++++++++++++----- 1 file changed, 28 insertions(+), 6 deletions(-) diff --git a/task/09-functions-n-closures-tasks.js b/task/09-functions-n-closures-tasks.js index 6ba9dcedd..676ba55f3 100644 --- a/task/09-functions-n-closures-tasks.js +++ b/task/09-functions-n-closures-tasks.js @@ -26,7 +26,9 @@ * */ function getComposition(f,g) { - throw new Error('Not implemented'); + return function (x) { + return f(g(x)); + } } @@ -47,7 +49,9 @@ function getComposition(f,g) { * */ function getPowerFunction(exponent) { - throw new Error('Not implemented'); + return function (number) { + return Math.pow(number, exponent); + }; } @@ -65,7 +69,10 @@ function getPowerFunction(exponent) { * getPolynom() => null */ function getPolynom() { - throw new Error('Not implemented'); + var tmp = Array.from(arguments).reverse(); + return (x) => { + return tmp.reduce((prev, curr, index) => prev+curr*Math.pow(x,index),0); + }; } @@ -84,7 +91,10 @@ function getPolynom() { * memoizer() => the same random number (next run, returns the previous cached result) */ function memoize(func) { - throw new Error('Not implemented'); + let cashed = func(); + return function() { + return cashed + } } @@ -104,7 +114,16 @@ function memoize(func) { * retryer() => 2 */ function retry(func, attempts) { - throw new Error('Not implemented'); + return()=>{ + for (var i = 0; i < attempts;){ + try{ + return func(); + } catch(err){ + i += 1; + } + } + return i; + }; } @@ -171,7 +190,10 @@ function partialUsingArguments(fn) { * getId10() => 11 */ function getIdGeneratorFunction(startFrom) { - throw new Error('Not implemented'); + var curr = startFrom; + return function() { + return startFrom++; + } } From 7bd172cfa0747a2e6f3dc5312ebf494210f905e5 Mon Sep 17 00:00:00 2001 From: Shagoysai <34492748+Shagoysai@users.noreply.github.com> Date: Sat, 12 Jun 2021 17:06:12 +0300 Subject: [PATCH 30/40] Update 02-numbers-tasks.js --- task/02-numbers-tasks.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/task/02-numbers-tasks.js b/task/02-numbers-tasks.js index 0bd672ca7..33d728364 100644 --- a/task/02-numbers-tasks.js +++ b/task/02-numbers-tasks.js @@ -113,7 +113,7 @@ function getLinearEquationRoot(a, b) { * (0,1) (1,2) => 0 */ function getAngleBetweenVectors(x1, y1, x2, y2) { - return Math.hypot((Math.abs(x1 - x2)), (Math.abs(y1 - y2))); + throw new Error('Not implemented'); } /** From bd56f13e97ee3bed21d77c909e4070902414e4d9 Mon Sep 17 00:00:00 2001 From: Shagoysai <34492748+Shagoysai@users.noreply.github.com> Date: Sat, 12 Jun 2021 17:07:04 +0300 Subject: [PATCH 31/40] Update 06-conditions-n-loops-tasks.js --- task/06-conditions-n-loops-tasks.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/task/06-conditions-n-loops-tasks.js b/task/06-conditions-n-loops-tasks.js index f697cc9b8..4f58d2967 100644 --- a/task/06-conditions-n-loops-tasks.js +++ b/task/06-conditions-n-loops-tasks.js @@ -230,7 +230,7 @@ function isBracketsBalanced(str) { return res.length == 0; } -function timespanToHumanString(startDate, endDate) { +function ToHumanString(startDate, endDate) { throw new Error('Not implemented'); } From 25c54948dca82bdd680976c7e611238fc18e7a7e Mon Sep 17 00:00:00 2001 From: Shagoysai <34492748+Shagoysai@users.noreply.github.com> Date: Sat, 12 Jun 2021 17:10:13 +0300 Subject: [PATCH 32/40] Update 06-conditions-n-loops-tests.js --- test/06-conditions-n-loops-tests.js | 141 +--------------------------- 1 file changed, 1 insertion(+), 140 deletions(-) diff --git a/test/06-conditions-n-loops-tests.js b/test/06-conditions-n-loops-tests.js index 93ffa3eee..ce22fce03 100644 --- a/test/06-conditions-n-loops-tests.js +++ b/test/06-conditions-n-loops-tests.js @@ -468,146 +468,7 @@ describe('06-conditions-n-loops-tasks', function() { }); - it.optional('timespanToHumanString should return the human string representation of datetime period', () => { - [ - { - startDate: '2000-01-01 01:00:00.100', - endDate: '2000-01-01 01:00:00.200', - expected: 'a few seconds ago' - }, { - startDate: '2000-01-01 01:00:00.000', - endDate: '2000-01-01 01:00:30.000', - expected: 'a few seconds ago' - }, { - startDate: '2000-01-01 01:00:00.000', - endDate: '2000-01-01 01:00:45.000', - expected: 'a few seconds ago' - }, { - startDate: '2000-01-01 01:00:00.000', - endDate: '2000-01-01 01:00:45.001', - expected: 'a minute ago' - }, { - startDate: '2000-01-01 01:00:00.000', - endDate: '2000-01-01 01:01:00.000', - expected: 'a minute ago' - }, { - startDate: '2000-01-01 01:00:00.000', - endDate: '2000-01-01 01:01:30.000', - expected: 'a minute ago' - }, { - startDate: '2000-01-01 01:00:00.000', - endDate: '2000-01-01 01:01:30.001', - expected: '2 minutes ago' - }, { - startDate: '2000-01-01 01:00:00.000', - endDate: '2000-01-01 01:05:30.000', - expected: '5 minutes ago' - },{ - startDate: '2000-01-01 01:00:00.000', - endDate: '2000-01-01 01:45:00.000', - expected: '45 minutes ago' - },{ - startDate: '2000-01-01 01:00:00.000', - endDate: '2000-01-01 01:45:00.001', - expected: 'an hour ago' - },{ - startDate: '2000-01-01 01:00:00.000', - endDate: '2000-01-01 02:00:00.000', - expected: 'an hour ago' - },{ - startDate: '2000-01-01 01:00:00.000', - endDate: '2000-01-01 02:30:00.000', - expected: 'an hour ago' - },{ - startDate: '2000-01-01 01:00:00.000', - endDate: '2000-01-01 02:30:00.001', - expected: '2 hours ago' - },{ - startDate: '2000-01-01 01:00:00.000', - endDate: '2000-01-01 05:30:00.000', - expected: '4 hours ago' - },{ - startDate: '2000-01-01 01:00:00.000', - endDate: '2000-01-01 05:30:00.001', - expected: '5 hours ago' - },{ - startDate: '2000-01-01 01:00:00.000', - endDate: '2000-01-01 23:00:00.000', - expected: '22 hours ago' - },{ - startDate: '2000-01-01 01:00:00.000', - endDate: '2000-01-01 23:00:00.001', - expected: 'a day ago' - },{ - startDate: '2000-01-01 01:00:00.000', - endDate: '2000-01-02 01:00:00.000', - expected: 'a day ago' - },{ - startDate: '2000-01-01 00:00:00.000', - endDate: '2000-01-02 12:00:00.000', - expected: 'a day ago' - },{ - startDate: '2000-01-01 00:00:00.000', - endDate: '2000-01-02 12:00:00.001', - expected: '2 days ago' - },{ - startDate: '2000-01-01 00:00:00.000', - endDate: '2000-01-05 12:00:00.000', - expected: '4 days ago' - },{ - startDate: '2000-01-01 00:00:00.000', - endDate: '2000-01-26 00:00:00.000', - expected: '25 days ago' - },{ - startDate: '2000-01-01 00:00:00.000', - endDate: '2000-01-26 00:00:00.001', - expected: 'a month ago' - },{ - startDate: '2000-01-01 00:00:00.000', - endDate: '2000-02-01 00:00:00.000', - expected: 'a month ago' - },{ - startDate: '2000-01-01 00:00:00.000', - endDate: '2000-02-15 00:00:00.000', - expected: 'a month ago' - },{ - startDate: '2000-01-01 00:00:00.000', - endDate: '2000-02-16 00:00:00.000', - expected: '2 months ago' - },{ - startDate: '2000-01-01 00:00:00.000', - endDate: '2000-05-20 00:00:00.000', - expected: '5 months ago' - },{ - startDate: '2000-01-01 00:00:00.000', - endDate: '2000-12-10 00:00:00.000', - expected: '11 months ago' - },{ - startDate: '2000-01-01 00:00:00.000', - endDate: '2000-12-12 00:00:00.000', - expected: 'a year ago' - },{ - startDate: '2000-01-01 00:00:00.000', - endDate: '2001-02-15 00:00:00.001', - expected: 'a year ago' - },{ - startDate: '2000-01-01 00:00:00.000', - endDate: '2001-06-01 00:00:00.001', - expected: 'a year ago' - },{ - startDate: '2000-01-01 00:00:00.000', - endDate: '2015-02-15 00:00:00.001', - expected: '15 years ago' - } - ].forEach(data => { - var actual = tasks.timespanToHumanString(new Date(data.startDate), new Date(data.endDate)); - assert.equal( - actual, - data.expected, - `timespanToHumanString('${data.startDate}', '${data.endDate}') shoud return '${data.expected}', but actually '${actual}'` - ) - }); - }); + it.optional('evaluateTicTacToePosition should return the winner if defined', () => { From cbdb6c0b3b0747cab218b48e5e6b583dcf19b714 Mon Sep 17 00:00:00 2001 From: Shagoysai <34492748+Shagoysai@users.noreply.github.com> Date: Sat, 12 Jun 2021 17:12:15 +0300 Subject: [PATCH 33/40] Update 06-conditions-n-loops-tasks.js --- task/06-conditions-n-loops-tasks.js | 4 ---- 1 file changed, 4 deletions(-) diff --git a/task/06-conditions-n-loops-tasks.js b/task/06-conditions-n-loops-tasks.js index 4f58d2967..10e1ba261 100644 --- a/task/06-conditions-n-loops-tasks.js +++ b/task/06-conditions-n-loops-tasks.js @@ -230,9 +230,6 @@ function isBracketsBalanced(str) { return res.length == 0; } -function ToHumanString(startDate, endDate) { - throw new Error('Not implemented'); -} function getCommonDirectoryPath(pathes) { throw new Error('Not implemented'); @@ -260,7 +257,6 @@ module.exports = { isCreditCardNumber: isCreditCardNumber, getDigitalRoot: getDigitalRoot, isBracketsBalanced: isBracketsBalanced, - ToHumanString : timespanToHumanString, toNaryString: toNaryString, getCommonDirectoryPath: getCommonDirectoryPath, getMatrixProduct: getMatrixProduct, From 41a51c866a7de8c8d098d658cf274db6bda2fc58 Mon Sep 17 00:00:00 2001 From: Shagoysai <34492748+Shagoysai@users.noreply.github.com> Date: Mon, 14 Jun 2021 22:21:51 +0300 Subject: [PATCH 34/40] Update 02-numbers-tasks.js --- task/02-numbers-tasks.js | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/task/02-numbers-tasks.js b/task/02-numbers-tasks.js index 33d728364..15af81652 100644 --- a/task/02-numbers-tasks.js +++ b/task/02-numbers-tasks.js @@ -113,7 +113,11 @@ function getLinearEquationRoot(a, b) { * (0,1) (1,2) => 0 */ function getAngleBetweenVectors(x1, y1, x2, y2) { - throw new Error('Not implemented'); + var angle = Math.atan2(y2, x2) - Math.atan2(y1, x1) + if (angle < 0) { + angle += 2 * Math.PI; + } + return angle } /** From 30dd4823e6c4c67dfc18eaa08d27667509bae1d8 Mon Sep 17 00:00:00 2001 From: Shagoysai <34492748+Shagoysai@users.noreply.github.com> Date: Tue, 15 Jun 2021 00:26:54 +0300 Subject: [PATCH 35/40] Update 04-arrays-tasks.js --- task/04-arrays-tasks.js | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/task/04-arrays-tasks.js b/task/04-arrays-tasks.js index 79531683b..6d404f859 100644 --- a/task/04-arrays-tasks.js +++ b/task/04-arrays-tasks.js @@ -40,7 +40,12 @@ function findElement(arr, value) { */ function generateOdds(len) { - throw new Error('Not implemented'); + let arr = new Array(len); + arr.fill(1); + return arr.map((elem, index) => + { + return index*2 + 1; + }); } function doubleArray(arr) { @@ -162,7 +167,11 @@ function getHead(arr, n) { } function sortDigitNamesByNumericOrder(arr) { - throw new Error('Not implemented'); + let alph = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']; + return arr.sort((a, b) => + { + return alph.indexOf(a)-alph.indexOf(b); + }); } /** @@ -560,7 +569,11 @@ function getElementByIndexes(arr, indexes) { } function swapHeadAndTail(arr) { - throw new Error('Not implemented'); + let hlen = Math.floor(arr.length/2); + let headArr = arr.slice(0, hlen); + let middleArr = arr.slice(hlen, hlen + (arr.length & 1)); + let tailArr = arr.slice(arr.length - hlen, arr.length); + return tailArr.concat(middleArr).concat(headArr); } module.exports = { From 716f7c47dc9abebe9aa301c451522042e283aaa5 Mon Sep 17 00:00:00 2001 From: Shagoysai <34492748+Shagoysai@users.noreply.github.com> Date: Tue, 15 Jun 2021 00:46:11 +0300 Subject: [PATCH 36/40] Update 06-conditions-n-loops-tasks.js --- task/06-conditions-n-loops-tasks.js | 54 +++++++++++++++++++++++++++-- 1 file changed, 51 insertions(+), 3 deletions(-) diff --git a/task/06-conditions-n-loops-tasks.js b/task/06-conditions-n-loops-tasks.js index 10e1ba261..06dd524ac 100644 --- a/task/06-conditions-n-loops-tasks.js +++ b/task/06-conditions-n-loops-tasks.js @@ -232,15 +232,63 @@ function isBracketsBalanced(str) { function getCommonDirectoryPath(pathes) { - throw new Error('Not implemented'); + let answer = ''; + pathes = pathes.map(path => path.split('/')); + + while(pathes.length != 0) { + let tmp = pathes[0].shift(); + for (let i = 1; i < pathes.length; i++) { + if(pathes[i].shift() != tmp) { + return answer; + } + } + answer += tmp + '/'; + } + return answer; } function getMatrixProduct(m1, m2) { - throw new Error('Not implemented'); + let n = m1.length, m = m2[0].length; + let answer = new Array(n); + for (let i=0; i < n; i++) + { + answer[i]=new Array(m); + } + for (let i = 0; i < m; i++) + for (let j = 0; j < n; j++) + answer[i][j]=0; + + for(let i = 0; i < n; i++) + for(let j = 0; j < m; j++) + for(let k = 0; k < m1[0].length; k++) + answer[i][j] += m1[i][k] * m2[k][j]; + return answer; } function evaluateTicTacToePosition(position) { - throw new Error('Not implemented'); + for (let i = 0; i < position.length; i++) + { + if ((position[i][0] === position[i][1]) && (position[i][0] === position[i][2]) && (typeof position[i][0] != 'undefined')) + return position[i][0]; + } + let fl1 = true, fl2 = true; + for (let x = 1; x < position.length; x++) + { + if (position[x][x] !== position[0][0]) + fl1 = false; + if (position[x][position.length - 1 - x] !== position[0][2]) + fl2 = false; + } + if (fl1 && typeof position[0][0] != undefined) + return position[0][0]; + if (fl2 && typeof position[0][2] != undefined) + return position[0][2]; + + for (let i = 0; i < position.length; i++) { + if ((position[0][i] === position[1][i]) && (position[0][i] === position[2][i]) && (typeof position[0][i] !== 'undefined')) + return position[0][i]; + } + return undefined; } module.exports = { From f73f1d3934b6bcf5bfcf194db126446ca56441f8 Mon Sep 17 00:00:00 2001 From: Shagoysai <34492748+Shagoysai@users.noreply.github.com> Date: Tue, 15 Jun 2021 00:56:34 +0300 Subject: [PATCH 37/40] Update 07-yield-tasks.js --- task/07-yield-tasks.js | 44 +++++++++++++++++++++++++++++++++++++++--- 1 file changed, 41 insertions(+), 3 deletions(-) diff --git a/task/07-yield-tasks.js b/task/07-yield-tasks.js index a504a845e..5a18b97f3 100644 --- a/task/07-yield-tasks.js +++ b/task/07-yield-tasks.js @@ -33,7 +33,19 @@ * */ function* get99BottlesOfBeer() { - throw new Error('Not implemented'); + let count = 99; + while (count >= 3) { + yield count + ' bottles of beer on the wall, ' + count + ' bottles of beer.'; + yield 'Take one down and pass it around, ' + --count + ' bottles of beer on the wall.'; + } + if (count = 2) { + yield count + ' bottles of beer on the wall, ' + count + ' bottles of beer.'; + yield 'Take one down and pass it around, ' + --count + ' bottle of beer on the wall.'; + } + yield '1 bottle of beer on the wall, 1 bottle of beer.'; + yield 'Take one down and pass it around, no more bottles of beer on the wall.'; + yield 'No more bottles of beer on the wall, no more bottles of beer.'; + yield 'Go to the store and buy some more, 99 bottles of beer on the wall.'; } @@ -127,7 +139,15 @@ function* depthTraversalTree(root) { * */ function* breadthTraversalTree(root) { - throw new Error('Not implemented'); + let nodes = [root]; + for (let i = 0; i < nodes.length; i++) { + yield nodes[i]; + if ('children' in nodes[i]) { + for (let j = 0; j < nodes[i].children.length; j++) { + nodes.push(nodes[i].children[j]); + } + } + } } @@ -145,7 +165,25 @@ function* breadthTraversalTree(root) { * [ 1, 3, 5, ... ], [ -1 ] => [ -1, 1, 3, 5, ...] */ function* mergeSortedSequences(source1, source2) { - throw new Error('Not implemented'); + let src1 = source1(); + let src2 = source2(); + let i = src1.next().value; + let j = src2.next().value; + while (true) { + if ((i == undefined) && (j != undefined)) { + yield j; + j = src2.next().value; + } else if ((j == undefined) && (i != undefined)) { + yield i; + i = src1.next().value; + } else if ((i < j) && (i != undefined) && (j != undefined)) { + yield i; + i = src1.next().value; + } else if ((i >= j) && (i != undefined) && (j != undefined)) { + yield j; + j = src2.next().value; + } + } } From b56b855081f7d62678ba82a52384a0a1480d8779 Mon Sep 17 00:00:00 2001 From: Shagoysai <34492748+Shagoysai@users.noreply.github.com> Date: Tue, 15 Jun 2021 00:59:15 +0300 Subject: [PATCH 38/40] Update 08-objects-tasks.js --- task/08-objects-tasks.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/task/08-objects-tasks.js b/task/08-objects-tasks.js index aa120dd0b..91ec9e4b1 100644 --- a/task/08-objects-tasks.js +++ b/task/08-objects-tasks.js @@ -43,7 +43,7 @@ function Rectangle(width, height) { * { width: 10, height : 20 } => '{"height":10,"width":20}' */ function getJSON(obj) { - throw new Error('Not implemented'); + return JSON.stringify(obj); } @@ -59,7 +59,7 @@ function getJSON(obj) { * */ function fromJSON(proto, json) { - throw new Error('Not implemented'); + return Object.setPrototypeOf(JSON.parse(json), proto); } From 5e971e30c3744deebe0a2ade117f258581a30905 Mon Sep 17 00:00:00 2001 From: Shagoysai <34492748+Shagoysai@users.noreply.github.com> Date: Tue, 15 Jun 2021 00:59:59 +0300 Subject: [PATCH 39/40] Update 09-functions-n-closures-tasks.js --- task/09-functions-n-closures-tasks.js | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/task/09-functions-n-closures-tasks.js b/task/09-functions-n-closures-tasks.js index 676ba55f3..740553688 100644 --- a/task/09-functions-n-closures-tasks.js +++ b/task/09-functions-n-closures-tasks.js @@ -151,7 +151,13 @@ function retry(func, attempts) { * */ function logger(func, logFunc) { - throw new Error('Not implemented'); + return function(...props) { + const str = `${func.name}(${JSON.stringify(Array.from(props)).slice(1, -1)}) `; + logFunc(str + 'starts'); + const result = func.apply(null, props); + logFunc(str + 'ends'); + return result; + }; } @@ -169,7 +175,10 @@ function logger(func, logFunc) { * partialUsingArguments(fn, 'a','b','c','d')() => 'abcd' */ function partialUsingArguments(fn) { - throw new Error('Not implemented'); + let arg = Array.from(arguments).slice(1); + return function () { + return fn.apply(null, arg.concat(Array.from(arguments))); + } } From 034f0ef39d2953d3b706d5d274f230ff879b1992 Mon Sep 17 00:00:00 2001 From: Shagoysai <34492748+Shagoysai@users.noreply.github.com> Date: Tue, 15 Jun 2021 01:02:24 +0300 Subject: [PATCH 40/40] Update 08-objects-tasks.js --- task/08-objects-tasks.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/task/08-objects-tasks.js b/task/08-objects-tasks.js index 91ec9e4b1..0e6e3bc74 100644 --- a/task/08-objects-tasks.js +++ b/task/08-objects-tasks.js @@ -59,7 +59,7 @@ function getJSON(obj) { * */ function fromJSON(proto, json) { - return Object.setPrototypeOf(JSON.parse(json), proto); + throw new Error('Not implemented'); }