Giter Club home page Giter Club logo

basic-js's Introduction

BasicJS

⚠️ DO NOT SUBMIT PULL REQUESTS TO THIS REPO ⚠️


Prerequisites

  1. Install Node.js
  2. Fork this repository: https://github.com/AlreadyBored/basic-js
  3. Clone your newly created repo: https://github.com/<%your_github_username%>/basic-js/
  4. Go to folder basic-js
  5. To install all dependencies use npm install
  6. Run npm run test in command line.
  7. You will see the number of pending, passing and failing tests. 100% of passing tests is equal to max score for the task

Troubleshooting

  • If you catch error like this you can try to make npm install -g node-gyp

Submit to rs app

  1. Open rs app and login
  2. Go to submit task page
  3. Select your task (BasicJS)
  4. Press the submit button and enjoy

Notes

  1. We recommend you to use Node.js of version 16.x.x LTS. If you use any of features, that does not supported by Node.js v16, there may be problems with task submit.
  2. Please, be sure that each of your tests is limited to 30 sec.

General task description

Your task is to write several functions that are the solution to the subtasks. Subtasks descriptions, as well as instructions on how to run tests and submit solutions are below.


Count cats!

Count cats!
Your task is to count the cats hidden in the backyard (presented by two-dimensional Array). Cats hide well, but their ears ("^^") are clearly visible. Your task is to implement the countCats(backyard) function that will count cats. Good luck!

Number of cats found should be number. If no cats found, function should return 0.

For example:

countCats([ [0, 1, '^^'], [0, '^^', 2], ['^^', 1, 2] ]) => 3

Write your code in src/count-cats.js.


Carbon dating

Carbon dating
To determine the age of archaeological finds, radioisotope dating is widely used. One of its types is radiocarbon dating.

The approximate age of the sample is calculated by measuring the ratio of the modern activity of the C14 isotope to the activity of the same isotope in the sample.

Read about method

Reserved link


About calculations You can use the formula from the article at the link above. 0.693 is an approximation of the natural logarithm of two.

Your task is to implement the function dateSample(sampleActivity) that calculates sample approximate age (in years). Please use given MODERN_ACTIVITY and HALF_LIFE_PERIOD.

Function parameter sampleActivity is a string. Calculated sample age must be number.

Age must be integer. Age must be rounded up (ceiling). In case of wrong input parameter type or inadequate activity value or absence of argument function must return false.

For example:

dateSample('1') => 22387 (or 22392 depending on formula used)

dateSample('WOOT!') => false

Write your code in src/carbon-dating.js.


Dream team

Dream team
Imagine you and your friends decide to create a dream team. This team should have a cool secret name that contains encrypted information about it. For example, these may be the first letters of the names of its members in upper case sorted alphabetically. Your task is to implement the createDreamTeam(members) function that returns name of a newly made team (string) based on the names of its members (Array). Good luck!

Names of the members should be strings. Values with other type should be ignored. In case of wrong members type function must return false.

NB! Team member name may contain whitespaces.

For example:

createDreamTeam(['Matt', 'Ann', 'Dmitry', 'Max']) => 'ADMM'

createDreamTeam(['Olivia', 1111, 'Lily', 'Oscar', true, null]) => 'LOO'

Write your code in src/dream-team.js.


What season?

What season
Your task is to implement the function getSeason(date) that accepts Date object and returns the time of the year that matches it. Time of the year must be string.


Seasons in English The names of the seasons in English are: spring, summer, autumn (fall), winter.

If the date argument was not passed, the function must return the string 'Unable to determine the time of year!'. If the date argument is invalid, the function must throw an Error with message Invalid date!.

Shh! An enemy scout has lurked among the arguments that come into this function.

Disguised
He is guided by the famous proverb: “If it looks like a duck, swims like a duck and quacks like a duck, then it probably is a duck (who cares what it really is)”. He is expertly disguised as a real date, but a clever javascript developer can catch him and throw an Error with message Invalid date! just in time!

For example:

const springDate = new Date(2020, 02, 31)

getSeason(springDate) => 'spring'

Write your code in src/what-season.js.


Tower of Hanoi

Tower of hanoi visualisation
Tower of Hanoi is famous mathematical puzzle of the 18th century. It consists of three rods and a number of disks of different sizes, which can slide onto any rod. The puzzle starts with the disks in a neat stack in ascending order of size on one rod, the smallest at the top, thus making a conical shape.

The objective of the puzzle is to move the entire stack to another rod, obeying the following simple rules:

  • Only one disk can be moved at a time.
  • Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack or on an empty rod.
  • No larger disk may be placed on top of a smaller disk.

Your task is much easier than coming up with an algorithm that solves this puzzle :)

Implement the function calculateHanoi that accepts diskNumber and turnsSpeed parameters. diskNumber is a number of disks and turnsSpeed is the speed of moving discs (in turns per hour). Both parameters are numbers.

calculateHanoi function returns an object with 2 properties:

  • turns (minimum number of turns to solve the puzzle)
  • seconds (minimum number of seconds to solve the puzzle at a given turnsSpeed, seconds must be an integer, obtained from rounded down (floor) calculation result)

You don't need to validate parameters.

For example:

calculateHanoi(9, 4308) => { turns: 511, seconds: 427 }

Write your code in src/hanoi-tower.js.


Transform array

Transform array
Your task is to implement the function transform(arr) that takes an array and returns transformed array, based on the control sequences that arr contains. Control sequences are defined string elements of the mentioned array:

  • --discard-next excludes the next element of the array from the transformed array.
  • --discard-prev excludes the previous element of the array from the transformed array.
  • --double-next duplicates the next element of the array in the transformed array.
  • --double-prev duplicates the previous element of the array in the transformed array.

For example:

transform([1, 2, 3, '--double-next', 4, 5]) => [1, 2, 3, 4, 4, 5]

transform([1, 2, 3, '--discard-prev', 4, 5]) => [1, 2, 4, 5]

The function must not affect inital array. Control sequences are applied from left to right to initial array elements. Control sequences do not fall into the transformed array. Control sequences in initial array don't occur in a row. If there is no element next to the control sequence to which it can be applied in the initial array, or this element was previously deleted, it does nothing. The function should throw an Error with message 'arr' parameter must be an instance of the Array! if the arr is not an Array.

Write your code in src/transform-array.js.


Chain maker

Chaining
Let's practice in chaining!

Your task is to create the object chainMaker that creates chains. The finished chain is a string and looks like this: '( value1 )~~( value2 )~~( value3 )'. The chainMaker has several methods for creating chains and modifying them:

  • getLength returns the current chain length as a number;
  • addLink(value) adds a link containing a string representation of the value to the chain;
  • removeLink(position) removes a chain link in the specified position;
  • reverseChain reverses the chain;
  • finishChain ends the chain and returns it.

addLink, reverseChain and removeLink methods are chainable, while the another ones are not. If addLink is called with no arguments, it adds an empty link ('( )') to the chain. If removeLink accepts invalid position (e.g. not a number, or a fractional number, or corresponding to a nonexistent link), it must throw an Error with message You can't remove incorrect link!. After calling the finishChain method, the existing chain must be deleted, as if an Error was thrown.

For example:

chainMaker.addLink(1).addLink(2).addLink(3).finishChain() => '( 1 )~~( 2 )~~( 3 )'

chainMaker.addLink(1).addLink(2).removeLink(1).addLink(3).finishChain() => '( 2 )~~( 3 )'

chainMaker.addLink(1).addLink(2).reverseChain().addLink(3).finishChain() => '( 2 )~~( 1 )~~( 3 )'

Write your code in src/simple-chain.js.


Recursive depth calculator

Go deeper
Your task is to implement the class DepthCalculator with method calculateDepth that takes an array and returns its depth.

calculateDepth method must pass the given array recursively. Depth of a flat array is 1. Method must correctly work with arrays that contain no elements or contain empty arrays.

For example:

const depthCalc = new DepthCalculator();

depthCalc.calculateDepth([1, 2, 3, 4, 5]) => 1

depthCalc.calculateDepth([1, 2, 3, [4, 5]]) => 2

depthCalc.calculateDepth([[[]]]) => 3

Write your code in src/recursive-depth.js.


Extended repeater

Extended repater
Your task is to implement the function repeater(str, options). This function returns a repeating string based on the given parameters:

  • str is a string to repeat;
  • options is an object of options, that contains properties:
    • repeatTimes sets the number of repetitions of the str;
    • separator is a string separating repetitions of the str;
    • addition is an additional string that will be added to each repetition of the str;
    • additionRepeatTimes sets the number of repetitions of the addition;
    • additionSeparator is a string separating repetitions of the addition.

The str and addition parameters are strings by default. In case when type of these parameters is different, they must be converted to a string.

separator and additionSeparator parameters are strings.

repeatTimes and additionRepeatTimes are integer numbers (in the absence of any of them, the corresponding string is not repeated).

The only indispensable parameter is str, any others may be not defined. separator default value is '+'. additionSeparator default value is '|'.

For example: repeater('STRING', { repeatTimes: 3, separator: '**', addition: 'PLUS', additionRepeatTimes: 3, additionSeparator: '00' }) => 'STRINGPLUS00PLUS00PLUS**STRINGPLUS00PLUS00PLUS**STRINGPLUS00PLUS00PLUS'

Write your code in src/extended-repeater.js.


Vigenere cipher

Ciphering machine
Cryptography is awesome! Let's try to organize production of encryption machines. Our machines will use one of the encryption methods that are easy to understand, but also not amenable to simple cryptanalysis - the Vigenere cipher.

Our machine will have 2 modifications: direct and reverse (the type of machine is determined at the moment of creation). The direct machine simply encodes and decodes the string that was transmitted to it, and the reverse machine returns an inverted string after encoding and decoding.

Your task is to implement the class VigenereCipheringMachine. constructor of this class accepts true (or nothing) to create direct machine and false to create reverse machine. Each instance of VigenereCipheringMachine must have 2 methods: encrypt and decrypt.

encrypt method accepts 2 parameters: message (string to encode) and key (string-keyword).

decrypt method accepts 2 parameters: encryptedMessage (string to decode) and key (string-keyword).

These parameters for both methods are mandatory. If at least one of them has not been given, an Error with message Incorrect arguments! must be thrown. The text returned by these methods must be uppercase. Machines encrypt and decrypt only latin alphabet (all other symbols remain unchanged).

You don't need to validate value sent to constructor and to encrypt and decrypt methods (except throwing an Error on absence of argument for these methods).

For example:

const directMachine = new VigenereCipheringMachine();

const reverseMachine = new VigenereCipheringMachine(false);

directMachine.encrypt('attack at dawn!', 'alphonse') => 'AEIHQX SX DLLU!'

directMachine.decrypt('AEIHQX SX DLLU!', 'alphonse') => 'ATTACK AT DAWN!'

reverseMachine.encrypt('attack at dawn!', 'alphonse') => '!ULLD XS XQHIEA'

reverseMachine.decrypt('AEIHQX SX DLLU!', 'alphonse') => '!NWAD TA KCATTA'

Write your code in src/vigenere-cipher.js.


(ST) Common character count

Your task is to implement function that accepts two strings (s1 and s2) and returns number of common characters between them.

For example:

getCommonCharacterCount('aabcc', 'adcaa') => 3

Write your code in src/common-character-count.js.


(ST) Delete digit

Your task is to implement function that accepts integer number (n) and returns maximal number you can obtain by deleting exactly one digit of the given number.

For example:

deleteDigit(152) => 52

Write your code in src/delete-digit.js.


(ST) DNS stat

Your task is to implement function that accepts an array of domains (domains) and returns the object with the appearances of the DNS.

For example:

getDNSStats(['code.yandex.ru', 'music.yandex.ru', 'yandex.ru']) => {'.ru': 3, '.ru.yandex': 3, '.ru.yandex.code': 1,'.ru.yandex.music': 1}

Write your code in src/dns-stats.js.


(ST) Encode line

Your task is to implement function that accepts string (str) and returns its encoded version.

For example:

encodeLine('aabbbc') => '2a3bc'

Write your code in src/encode-line.js.


(ST) File names

There's a list of file, since two files cannot have equal names, the one which comes later will have a suffix (k), where k is the smallest integer such that the found name is not used yet. Your task is to implement function that accepts array of names (names) and returns an array of names that will be given to the files.

For example:

renameFiles(["file", "file", "image", "file(1)", "file"]) => ["file", "file(1)", "image", "file(1)(1)", "file(2)"]

Write your code in src/file-names.js.


(ST) Get email domain

Your task is to implement function that accepts email address (email) and returns it's domain.

For example:

getEmailDomain('[email protected]') => 'example.com'

Write your code in src/get-email-domain.js.


(ST) Is MAC-48 Address?

The MAC-48 address is six groups of two hexadecimal digits (0 to 9 or A to F) separated by hyphens. Your task is to implement function that accepts string (inputString) and returns true if string is valid MAC-48 address.

For example:

isMAC48Address('00-1B-63-84-45-E6') => true

Write your code in src/mac-adress.js.


(ST) Matrix elements sum

Given matrix, a rectangular matrix of integers, just add up all the values that don't appear below a "0".

For example:

const matrix = [
 [0, 1, 1, 2],
 [0, 5, 0, 0],
 [2, 0, 3, 3]
];

getMatrixElementsSum(matrix) => 9

Write your code in src/matrix-elements-sum.js.


(ST) Minesweeper

In the popular Minesweeper game you have a board with some mines and cells that have a number in it that indicates the total number of mines in the neighboring cells. Starting off with some arrangement of mines we want to create a Minesweeper game setup.

For example:

const matrix = [
 [true, false, false],
 [false, true, false],
 [false, false, false]
];

minesweeper(matrix) => [
 [1, 2, 1],
 [2, 1, 1],
 [1, 1, 1]
];

Write your code in src/mine-sweeper.js.


(ST) Sort by height

Given an array with heights, sort them except if the value is -1. Your task is to implement function that accepts array (arr) and returns it sorted

For example:

sortByHeight([-1, 150, 190, 170, -1, -1, 160, 180]) => [-1, 150, 160, 170, -1, -1, 180, 190]

Write your code in src/sort-by-height.js.


(ST) Sum digits

Your task is to implement function that accepts a number (n) and returns the sum of its digits until we get to a one digit number.

For example:

For 100, the result should be 1 (1 + 0 + 0 = 1)
getSumOfDigits(100) => 1

For 91, the result should be 1 (9 + 1 = 10, 1 + 0 = 1)
getSumOfDigits(91) => 1

Write your code in src/sum-digits.js.


© AlreadyBored

& tasks:

  • Common character count
  • Delete digit
  • DNS stat
  • Encode line
  • File names
  • Get email domain
  • Is MAC-48 Adress?
  • Matrix elements sum
  • Minesweeper
  • Sort by height
  • Sum digits

are integrated from Short track 2021 repo

& Thanks mikhama for assistance!

basic-js's People

Contributors

abadire avatar alreadybored avatar dependabot[bot] avatar f19m avatar gittadm avatar ipipka avatar ksarise avatar liquidvacuum avatar madkorney avatar maksumov avatar mikhama avatar romanwrites avatar thorsangervanet avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

basic-js's Issues

Transform array (error in test and need explanation)

Hello!

  1. Look at the screenshot. Infinity should be at the first place.
    Error
  2. Explain please what "--double-prev" should do: double previous item of the input array or simply add another instance of the previos item.
    Situation: ["--discard-next", x, "--double-prev, y"]
    a. y - we discard x, so nothing to double
    b. [x, y] - discard x then add another x when double
    c. [ x, x, y] - simply double previous.

Best regards,
Slava

FYI: ELIFECYCLE error

Уже у двух студентов JS/FE 2022Q1 обнаружилась такая ошибка, почему-то помогает глобальная установка node-gyp:
npm install -g node-gyp
image
image
Просто решил проинформировать.

Transform array. Unclear order

I added some console.log() in the test for the Transform Array task and found that when the input array looks like this:
["--discard-next", 22, "--double-prev"]
The output result of the transformation looks like this:
[22]
This means that the control sequences were resolved starting from the end. But I did not find any info about the side from which I should start. I used to think that we start from the first element and should get the following result in this case:
[] (an empty array)

Could you please clarify this?
Thanks

So many parameters

Let's rewrite it with two parameters:

module.exports = function repeater(str, repeatTimes, separator, addition, additionRepeatTimes, additionSeparator) {

Like this:

function repeater(str, options) {

}

That function's signature is more convenient and clear.
Students could write it like this (using destructing, or some another way):

function repeater(str, { repeatTimes = 1, separator = '+', addition = 'no-addition', additionRepeatTimes = 1, additionSeparator = '|' })

Предлагаю усложнить тест

Думаю будет немного веселее, если просить возвращать отрицательное число, если на входе оно отрицательное.

Transform array

В условиях Control sequences are applied from left to right.
В тестах doubleDiscarded: {
input: [1, 2, 3, '--discard-next', 1337, '--double-prev', 4, 5],
output: [1, 2, 3, 4, 5]
}
Разве ответ не [1, 2, 3, 3, 4, 5].
Сначала происходит удаление 1337, затем дублируется 3.

input: [1, 2, 3, '--discard-next', 1337, '--discard-prev', 4, 5],
output: [1, 2, 3, 4, 5]
Аналогично, сначала удаляется 1337, затем удаляется 3 и ответ [1, 2, 4, 5]

carbon-dating.test bag

в строке 54 теста carbon-dating.test.js ожидается параметром функции число с плавающей точкой.
имеется лишняя точка.
assert.equal(dateSample('11.3231.3213124'), 2326);
на сколько я понимаю должно быть
assert.equal(dateSample('11.32313213124'), 2326);

Typo in test

In "Carbon dating" we check solition on floating-point numbers, but one of test "it" contains an error (two points in number).

assert.equal(dateSample('11.3231.3213124'), 2326);

file "test/carbon-dating.test.js", line 54

Улучшить тест на "Recursive depth" или добавить уточнение в условия задачи по DepthCalculator

Здравствуйте.

Просьба подправить тест или внести уточнение в задание, чтобы кто еще не сделал или след. набор не застревали, где и я.

Не проходит тест на рекурсия. + информация теста не репрезентативна.
image

Как подсказали в Discorde, все из-за того, что функция может и не заходит в рекурсию (но она есть) при текущем тесте проверки.

module.exports = class DepthCalculator {
  calculateDepth(arr, n = 1) {
    if (n === 1 && arr.findIndex((el) => Array.isArray(el)) === -1) {
      return 1;
    }
    
    arr = arr.flat();
    
    n++;
    if (arr.findIndex((el) => Array.isArray(el)) === -1) {
      return n;
    }

    return this.calculateDepth(arr, n);
  }
};

Ошибка в тесте для "Расширенный повторитель"

В ТЗ написано: "repeatTimes и additionRepeatTimes являются целыми числами (в случае отсутствия любого из них соответствующая строка не повторяется)."
И тут же от меня хотят:
assert.equal(repeater('TESTstr', { repeatTimes: undefined, separator: 'ds', addition: 'ADD!', additionRepeatTimes: undefined, additionSeparator: ')))000' }), 'TESTstrADD!');
Ожидаемое поведение противоречит условиям ТЗ. undefined- не число. При этом почему-то на выходе ожидается str + options.addition, но без сепараторов.

Решил задачу вот так:
if (options.repeatTimes === undefined && options.additionRepeatTimes === undefined) {
return "TESTstrADD!";
}

Ошибка в тесте для задания "recursive-depth.js"

Скрипт для проверки recursive-depth.js отрабатывает не правильно в третьем блоке - 'works recursively'. А именно не проходят тесты на определение глубины массива - тест, независимо от массива, передаваемого в функцию, всегда выдаёт 31. При этом два первых теста пройдены успешно, т.е. функция правильно измеряет глубину. На проверку самой рекурсии не ругается. Пожалуйста посмотрите.

There can be issue with 'transform array' task

image
original array
[--discard-next,555,--discard-next,[object Object],DEF,--double-prev]

should not require such output
[[object Object],DEF,DEF]

Control sequences are applied from left to right
555 should be skipped, after that object should be skipped with a similar rule.

Seems like createSample method in a tests doesn't work correct.
image

Test case is invalid?

Carbon-dating test in 'should handle floating-point numbers' section contain date-sample like '11.3231.3213124', but that value is not valid floating point number.

"it.optional is not a function" TypeError in carbon-dating tests

I have a TypeError thrown after launching tests for carbon-dating task:
"it.optional is not a function".

ATTENTION! Only reproduced after passing "npm run test ./test/carbon-dating.test.js" command to the prompt (not "npm run test").

I believe that is because there is "it.optional" nested in another "it.optional" function, as we have two valid returns for each 1 parameter passed to our function and that nesting causes context being lost.
Screen1

See when I comment upper-level "it.optional" function (screenshot is attached) the error disappears and all tests pass.
I would also recommend replacing the "it.optional" nested function with describe. In this very case tests pass too.
Screen2

Please resolve this problem.

Looking forward to your soonest reply.

Hanoi Tower tests

Hanoi Tower:

I think that it is necessary to reduce the accuracy of the check, because there are 16 decimal places here, which exceeds machine accuracy. Reduce to at least 12 will be good I think :)

{
-  "seconds": 1.6502813140731935e+217
+  "seconds": 1.6502813140731933e+217
"turns": 3.6147378671465184e+221
}

Extended repeater

Добрый день.
В Extended repeater есть условие

"The str and addition parameters are strings by default. In case when type of these parameters is different, they must be converted to a string."

Но в тестах это условие кажется не проверяется.

Uncorrect description for Tower of Hanoi in russian

in english: "seconds must be an integer, obtained from rounded down (floor) calculation result)"
in russian: "должно быть целым числом, полученным в результате округления результата расчетов в большую сторону)"

P.S. Sorry if I'm doing it wrong in the form, this is my first issue :)

In some cases tests just don't run

I have been having this issue with some other basicJS problems as well, curently having it with vigenere cipher
When I run npm run test i get:

> [email protected] test
> mocha

and test just ends with no errors.

Here is my code for this problem:

const { NotImplementedError } = require('../extensions/index.js');

/**
 * Implement class VigenereCipheringMachine that allows us to create
 * direct and reverse ciphering machines according to task description
 * 
 * @example
 * 
 * const directMachine = new VigenereCipheringMachine();
 * 
 * const reverseMachine = new VigenereCipheringMachine(false);
 * 
 * directMachine.encrypt('attack at dawn!', 'alphonse') => 'AEIHQX SX DLLU!'
 * 
 * directMachine.decrypt('AEIHQX SX DLLU!', 'alphonse') => 'ATTACK AT DAWN!'
 * 
 * reverseMachine.encrypt('attack at dawn!', 'alphonse') => '!ULLD XS XQHIEA'
 * 
 * reverseMachine.decrypt('AEIHQX SX DLLU!', 'alphonse') => '!NWAD TA KCATTA'
 * 
 */
    // throw new NotImplementedError('Not implemented');
// write this to each method to mute it ^^^


class VigenereCipheringMachine {
  encrypt(message = null, key = null) {
    if(message === null || key === null) throw new Error('Incorrect arguments!')
    message = message.toUpperCase(); key = key.toUpperCase()
    
    let enc = [], ml = message.length, kl = key.length
    for(let i = 0; i < ml; i++){
      let x = message[i].charCodeAt(0) - 65, y = key[i % kl].charCodeAt(0) - 65
      enc.push((x >= 0 && x < 26)? this.table[x][y] : message[i])
    }
    return (this.direct)? enc.join("") : enc.reverse().join("")
  }
  decrypt(encrypted = null, key = null) {
    if(encrypted === null || key === null) throw new Error('Incorrect arguments!')
    encrypted = encrypted.toUpperCase(); key = key.toUpperCase()

    let dec = [], el = encrypted.length, kl = key.length
    for(let i = 0; i < el; i++){
      let x = message[i].charCodeAt(0) - 65
      dec.push(this.table[0][this.table[x].indexOf(key[i])])
    }
    return (this.direct)? dec.join("") : dec.reverse().join("")
  }
  constructor(dir = true){
    this.direct = dir
    this.table = generateTable()
  }
}

function generateTable(){
    let a = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
    let res = []
    res.push(a)
    for(let i = 0; i < 25; i++){
      let cp = [...res[res.length - 1]]
      cp.push(sp.shift())
      res.push(cp)
    }
    return res
  }

module.exports = {
  VigenereCipheringMachine
};

it runs normally and shows errors (as it should) when I remove the constructor from the class

Уточнение в условии таска

Добавление уточнения: "Необходимо почистить код от console.log() перед сабмитом, иначе автотест может не засчитать задание".

Carbon Dating - Invalid Test Case

We have test case:

describe('functional requirements ', () => {   
    it.optional('should handle floating-point numbers', () => {
        assert.equal(dateSample('11.3231.3213124'), 2326);
    }
}

11.3231.3213124 does not seem to be a valid floating-point value, so the aswer should be false instead of 2326

Transform array (need clarification)

Hello!
I understand, that it is another Infinity. From my point of view there should be another Infinity at the first place.

--discard-prev` excludes the previous element of the array from the transformed array

So, I assum, that it works like this:
Error1

If it works like you showed, so :
Error2

Clarification needed.

Best regards,
Slava

PS Sorry for quality.

Presence of Obfuscated and Minified JavaScript Files in Test Suite Poses Security Risk And Loss of User Data

Hello there,

I hope this message finds you well. I am writing to bring your attention to a critical issue identified in the test suite of the basic-js GitHub repository. The concern revolves around the presence of obfuscated and minified JavaScript files within the test suite, for which no corresponding source code is available.

Issue Description:
The current state of the test suite includes JavaScript files that have been obfuscated and minified, making it impossible to review and rebuild the code to confirm its content. This lack of transparency raises serious security concerns, as it introduces the risk of potential malicious code that could compromise the integrity of the repository and, consequently, the security of user data.

Potential Implications:
Security Risk: The obfuscated code may contain malicious elements that could compromise the security of the entire repository and, consequently, user data.

Inability to Verify Code:
Without access to the source code, it is challenging to verify the legitimacy and security of the obfuscated and minified files.

Proposed Possible Actions:

  1. Remove files with obfuscation
  2. Add description into README
    Unfortunately similar proposition was met harshly at RSSchool and was closed right after opening PR: rolling-scopes-school/core-js-conditions-n-loops-tasks#18
  3. Introduce running test in a Docker container, this way if a person doesn't trust obfuscation, they can run the tests in a isolated container. Similar to following:
    https://github.com/vetalapo/rsschool-projects/blob/main/basic-js/Dockerfile

Constants at inappropriate place

Let's move these constants outside the function:

const modernActivity = 15;
const halfLifePeriod = 5730;

Please make it like this:

const MODERN_ACTIVITY= 15; 
const HALF_LIFE_PERIOD= 5730;

module.exports = function dateSample(sampleActivity) {
  // write your code here
};

It will be more convenient and clear.

Sum digits test err

image

В строке №11 getSumOfDigits(91) должна вернуть 10, а не 1.
В строке №14 getSumOfDigits(99) должна вернуть 18, а не 9.

Vigenere Cipher Throwing Error.

Hello,
Task Vigenere Cipher has requirement: Functions have 2 parametrs. If at least one of them has not been given, an Error must be thrown.
The problem: My Cipher code can run all the tests without throwing any error:

// test shouldnt pass without that piece of code:
if (!string || !key)
      throw new Error();

My output without previous code:
изображение

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.