📜 ⬆️ ⬇️

5 typical tasks for interviews on JavaScript: analysis and solutions



From the translator: The article by Maria Perna was published for you (Maria Antonietta Perna), which tells about typical JavaScript tasks , most often offered to job seekers-developers at interviews. The article will be useful, first of all, for novice programmers. Below are examples of solving problems, if it seems to you that they are not too good, and there is a better option - offer an alternative in the comments.

Interviews in technology companies have long been the talk of the town. You don’t have to be surprised - the successful completion of the interview gives you the opportunity to get a good job. But it is not so easy, because it is often necessary to solve complex problems.
')
And most often, most of these tasks are not related to the work that the applicant will perform, but they still need to be addressed. Sometimes you have to do it on a board, without checking with Google or any other source. Yes, the situation is gradually changing, and in some companies such interviews are refused, but many employers still adhere to this tradition. This article is devoted to the analysis of typical JavaScript-tasks that are often used as tasks for applicants.

We remind: for all readers of "Habr" - a discount of 10,000 rubles when writing to any Skillbox course on the promotional code "Habr".

Skillbox recommends: Practical course "Mobile Developer PRO" .

The main thing is a thorough preparation for your interview.


Yes, before you begin to sort out the tasks, let's look at general tips for preparing for the interview.

The main thing is to prepare in advance. Check how well you remember the algorithms and data structures, and tighten knowledge in areas that you are not very familiar with. There are many online platforms that will help prepare for interviews. We recommend GeeksforGeeks , Pramp , Interviewing.io and CodeSignal .

It is necessary to learn how to pronounce the decision out loud. It is advisable to tell applicants about what you are doing, and not just write on the blackboard (or type the code in the computer, also silently). Thus, if you make a mistake in the code, but the solution will be generally correct, you can increase your chances of success.

The task needs to be comprehended before proceeding to the solution. In some cases, you can superficially understand the task and then take the wrong path. It may be worth asking a few clarifying questions to the interviewer.

You need to practice writing the code manually, not on the PC. It happens that at the interviews the applicant is given a marker and a board, where there are no prompts or automatic formatting. When searching for a solution, write your code on a piece of paper or directly on the board. If you keep everything in your head, you can forget something important.

Template JavaScript Tasks


Probably some of these tasks are already familiar to you. You either had an interview where you had to solve something like this, or you practiced them while learning JavaScript. Well, now it's time to solve them again, and with a detailed explanation of the process.

Palindrome

A palindrome is a word, sentence, or sequence of characters that is read in the same way both in the usual direction and in the opposite. For example, “Anna” is a palindrome, and “table” and “John” are not.

Staging

A string is given; you need to write a function that allows you to return true if the string is a palindrome, and false if not. Thus it is necessary to consider spaces and punctuation marks.

palindrome ('racecar') === true
palindrome ('table') === false

Parse task

The main idea here is to flip the line in the opposite direction. If the "reverse" line is completely identical to the source, then we got a palindrome and the function should return true. If not, false.

Decision

Here is the code that lets you solve the palindrome.

const palindrome = str => { // turn the string to lowercase str = str.toLowerCase() // reverse input string and return the result of the // comparisong return str === str.split('').reverse().join('') } 

The first step is to convert the characters in the input string to lower case. This is a guarantee that the program will compare the characters themselves, and not the register or something else.

The second step is to reverse the line. This is easy to do: you need to convert it to an array using the .split () method (library String). Then we flip the array using .reverse () (Array library). The last stage is the conversion of the inverse array to a string using .join () (Array library).

Now all that is needed is to compare the “reverse” line with the original one, returning the result true or false.

Fizzbuzz

One of the most popular task interviews.

Staging

It is required to write a function that outputs numbers from 1 to n to the console, where n is an integer that the function takes as a parameter, with such conditions:


Example

Fizzbuzz (5)

Result

// one
// 2
// fizz
// four
// buzz

Parse task

The main thing here is a way to search for multiple numbers using JavaScript. It can be implemented using the module operator or the remainder -%, which allows you to show the remainder when dividing two numbers. If the remainder is 0, this means that the first number is a multiple of the second.

12% 5 // 2 -> 12 is not a multiple of 5
12% 3 // 0 -> 12 is multiple of 3

So, if we divide 12 by 5, we get 2 with the remainder 2. If we divide 12 by 3, then we get 4 with the remainder 0. In the first case, 12 is not a multiple of 5, in the second - 12 times a multiple of 3.

Decision

The optimal solution is the following code:

 const fizzBuzz = num => { for(let i = 1; i <= num; i++) { // check if the number is a multiple of 3 and 5 if(i % 3 === 0 && i % 5 === 0) { console.log('fizzbuzz') } // check if the number is a multiple of 3 else if(i % 3 === 0) { console.log('fizz') } // check if the number is a multiple of 5 else if(i % 5 === 0) { console.log('buzz') } else { console.log(i) } } } 

The function performs the necessary checks using conditional operators and outputs the result required by the user. The task should pay attention to the order of the if ... else operators: start with a double condition (&&) and end with the case when multiple numbers could not be found. As a result, we cover all options.

Anagram

So they call a word that contains all the letters of another word in the same quantity, but in a different order.

Staging

You need to write a function that checks whether two lines are anagrams, and the case of letters does not matter. Only characters are counted; spaces or punctuation are not taken into account.

anagram ('finder', 'Friend') -> true
anagram ('hello', 'bye') -> false

Parse task

Here it is important to consider that it is necessary to check each letter in the two input lines and their number in each line.

finder -> f: 1 friend -> f: 1
i: 1 r: 1
n: 1 i: 1
d: 1 e: 1
e: 1 n: 1
r: 1 d: 1

To store anagram data, choose a structure such as a JavaScript object literal. The key in this case is the letter symbol, the value is the number of its repetitions in the current line.

There are other conditions:


Decision

 // helper function that builds the // object to store the data const buildCharObject = str => { const charObj = {} for(let char of str.replace(/[^\w]/g).toLowerCase()) { // if the object has already a key value pair // equal to the value being looped over, // increase the value by 1, otherwise add // the letter being looped over as key and 1 as its value charObj[char] = charObj[char] + 1 || 1 } return charObj } // main function const anagram = (strA, strB) => { // build the object that holds strA data const aCharObject = buildCharObject(strA) // build the object that holds strB data const bCharObject = buildCharObject(strB) // compare number of keys in the two objects // (anagrams must have the same number of letters) if(Object.keys(aCharObject).length !== Object.keys(bCharObject).length) { return false } // if both objects have the same number of keys // we can be sure that at least both strings // have the same number of characters // now we can compare the two objects to see if both // have the same letters in the same amount for(let char in aCharObject) { if(aCharObject[char] !== bCharObject[char]) { return false } } // if both the above checks succeed, // you have an anagram: return true return true } 

Note the use of Object.keys () in the snippet above. This method returns an array containing the names or keys in the same order as they appear in the object. In this case, the array will be like this:

['f', 'i', 'n', 'd', 'e', ​​'r']

Thus, we obtain the properties of the object without the need to perform a volumetric cycle. In the task, you can use this method with the .length property — to check whether there are the same number of characters in both lines — this is an important feature of the anagrams.

Search for vowels

A fairly simple task that often comes across interviews.

Staging

You need to write a function that takes a string as an argument and returns the number of vowels that are contained in the string.
Vowels are “a”, “e”, “i”, “o”, “u”.

Example:

findVowels ('hello') // -> 2
findVowels ('why') // -> 0

Decision

Here is the easiest option:

 const findVowels = str => { let count = 0 const vowels = ['a', 'e', 'i', 'o', 'u'] for(let char of str.toLowerCase()) { if(vowels.includes(char)) { count++ } } return count } 

It is important to pay attention to the use of the .includes () method. It is available for both strings and arrays. It should be used to determine if the array contains a specific value. This method returns true if the array contains the specified value, and false if not.

There is a more concise solution to the problem:

 const findVowels = str => { const matched = str.match(/[aeiou]/gi) return matched ? matches.length : 0 } 

This involves the .match () method, which allows you to implement an effective search. If the regular expression as a method argument is found inside the specified string, then the return value becomes an array of matching characters. Well, if there is no match, then .match () returns null.

Fibonacci

A classic task that can be met at interviews of various levels. It is worth recalling that the Fibonacci sequence is a series of numbers, where each subsequent one is the sum of the two previous ones. So, the first ten numbers are as follows: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34.

Staging

You need to write a function that returns the nth entry in a specific sequence, with n being the number that is passed as the function argument.

fibonacci (3) // -> 2

This task involves looping the number of times specified in the argument, returning the value to the corresponding position. This way of setting the problem requires the use of cycles. If you use recursion instead, the interviewer may like it and give you some extra points.

Decision

 const fibonacci = num => { // store the Fibonacci sequence you're going // to generate inside an array and // initialize the array with the first two // numbers of the sequence const result = [0, 1] for(let i = 2; i <= num; i++) { // push the sum of the two numbers // preceding the position of i in the result array // at the end of the result array const prevNum1 = result[i - 1] const prevNum2 = result[i - 2] result.push(prevNum1 + prevNum2) } // return the last value in the result array return result[num] } 

In the results array, the first two numbers are contained in a row, since each entry in the sequence consists of the sum of the two previous numbers. At the very beginning of the two numbers that can be taken for the next number there, there is no, so the cycle can not generate them in automatic mode. But, as we know, the first two numbers are always 0 and 1. Therefore, you can manually initialize an array of results.

As for recursion, everything is simpler and more complicated at the same time:

 const fibonacci = num => { // if num is either 0 or 1 return num if(num < 2) { return num } // recursion here return fibonacci(num - 1) + fibonacci(num - 2) } 

We continue to call fibonacci (), passing in smaller numbers as arguments. We stop in the case when the argument passed is 0 or 1.

Conclusion


Most likely, you have already encountered any of these tasks if you have been interviewed by a frontend or JavaScript developer (especially if this is a junior level). But if they did not come across to you, then they can be useful in the future - at least for general development.
Skillbox recommends:

Source: https://habr.com/ru/post/445360/


All Articles