JavaScript is a skill that makes a developer a valuable candidate for any front-end or back-end position. When more than 98% of websites use JavaScript, it is evident that no web development project can take place without JavaScript components. It is required for any interaction between the user and a web page.
Suppose you are building a website to display the score of an ongoing sports tournament. As a developer, you can take two approaches here. First, manually update the value on the server, and users have to refresh the browser screen for score updates. Second, the viewer screen updates automatically every time there is an update in the value on the server.
Without a doubt, the latter approach is preferable. This is what JavaScript can achieve. It can significantly automate the functionalities and components of a web application.
To truly utilize the functionality of JavaScript, you must master some algorithms. This article will list the top four algorithms a JavaScript developer should know.
1. Linear search
One of the simplest JavaScript algorithms is linear search used for searching a data set. This algorithm starts from the 0th element, comparing the user’s input to return the positional value of the element finally.
It is often used to find missing elements in an array using JavaScript code. Here’s an example:
Find the missing number in this array:
Input: [1, 2, 3, 4, 6, 7, 8, 9, 10]
Algorithm:
const find_missing = function(input) {
let n = input.length + 1; let sum = 0;
for (let i in input) {
sum += input[i];
}return Math.floor((n * (n + 1)) / 2) – sum;
};
Output: 5
2. Reversal algorithm
It is the algorithm used in JavaScript to reverse an array. The reversal algorithm creates subarrays and changes them to perform the rotation of an array.
Array alignment is one of the essential JavaScript skills to master. You can achieve the same with the reversal algorithm. Here is an example of a realignment in JavaScript:
Input: [1,2,3]
Code:
const permute = function(nums) {
let results = [];let go = (current) => {
if (current.length === nums.length){
results.push(current);
return;
}
nums.forEach(n => {
if (!current.includes(n)){
go([…current, n]);
}
});
}
go([]);
return results;
};
Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
The same algorithm can be used for string array alignment.
Here is an example of two input strings that we check for alignment using the reversal algorithm.
Input: s1 = “ab”, s2 = “eidbao”
Output: true
Input: s1 = “aa”, s2 = “eidbao”
Output: false
JavaScript code:
const checkPermutation = function(s1, s2) {
const len1 = s1.length, len2 = s2.length;
if (len1 > len2) return false;const count = Array(26).fill(0);
for (let i = 0; i < len1; i++) {
count[s1.charCodeAt(i)-97]++;
count[s2.charCodeAt(i)-97]–;
}
if (!count.some(e => e !== 0)) return true;for (let i = len1; i < len2; i++) {
count[s2.charCodeAt(i)-97]–;
count[s2.charCodeAt(i-len1)-97]++;
if (!count.some(e => e !== 0)) return true;
}
return false;
};
3. Number-to-word conversion
This algorithm converts any given number into an English word string. It uses some predefined strings, and the output is generated using the values from these strings.
Input: 786
Output: Seven hundred and eighty-six
JavaScript code:
#include<iostream>
using namespace std;
string getUnit(int n) {
//Return single digit to word
string unit[10] = {“Zero”, “One”,”Two”, “Three”,”Four”,”Five”, “Six”,”Seven”,”Eight”,”Nine”};
return unit[n];
}
string getTwoDigits(int n) {
//Here n is 2 digit number
string td[10] = {“Ten”, “Eleven”,”Twelve”,”Thirteen”, “Fourteen”,”Fifteen”,”Sixteen”,”Seventeen”,”Eighteen”,”Nineteen”};
return td[n%10];
}
string getTenMul(int n) {
//Here n is a multiple of 10
string tm[8] = {“Twenty”, “Thirty”,”Fourty”, “Fifty”,”Sixty”, “Seventy”,”Eighty”,”Ninty”};
return tm[n-2];
}
string getTenPow(int pow) {
//The power of ten in words
string power[2] = {“Hundred”, “Thousand”};
return power[pow-2];
}
void printNumToWord(int n) {
if(n >= 0 && n < 10)
cout << getUnit(n) << ” “;
//Unit values to word
else if(n >= 10 && n < 20)
cout << getTwoDigits(n) << ” “;
//from eleven to nineteen
else if(n >= 20 && n < 100) {
cout << getTenMul(n/10)<<” “;
if(n%10 != 0)
printNumToWord(n%10); //Recursive call to convert num to word
}else if(n >= 100 && n < 1000) {
cout << getUnit(n/100)<<” “;
cout <<getTenPow(2) << ” “;
if(n%100 != 0) {
cout << “And “;
printNumToWord(n%100);
}
}else if(n >= 1000 && n <= 32767) {
printNumToWord(n/1000);
cout <<getTenPow(3)<<” “;
if(n%1000 != 0)
printNumToWord(n%1000);
}else
printf(“Invalid Input”);
}
main() {
int number;
cout << “Enter a number between 0 to 32767: “; cin >> number;
printNumToWord(number);
}
4. 4sum algorithm
4sum is another important JavaScript algorithm that finds several uses in computational applications. It is used to find the four elements in an array whose sum equals the required answer.
JavaScript code example:
const fourSum = function(nums, target) {
let result = [];
let length = nums.length;
if (length < 4) return result;
nums = nums.sort((a, b) => a – b );for (let i = 0; i < length – 3; i++) {
if (nums[i] === nums[i – 1]) continue;
for (let j = i + 1; j < length – 2; j++) {
if (j > i + 1 && nums[j] === nums[j – 1]) continue;let k = j + 1;
let l = length – 1;while (k < l) {
const sum = nums[i] + nums[j] + nums[k] + nums[l];if (sum === target) {
result.push([nums[i], nums[j], nums[k], nums[l]])
}if (sum <= target) {
k += 1;
while (nums[k] === nums[k – 1]) {
k += 1;
}
}if (sum >= target) {
l -= 1;
while (nums[l] === nums[l + 1]) {
l -= 1;
}
}
}
}
}return result;
};
Conclusion
Whether you are a front-end or a back-end developer, these are four important JavaScript algorithms to learn. They are widely used in web applications, from delivery tracking websites to ticket booking apps.
Talent500 has some great learning resources for JavaScript developers. And, if you are looking for job opportunities, sign up here.
Add comment