Javascript coding round - rs-hash/Learning GitHub Wiki
Javascript coding round
1. Todo app
2. Star rating
3. Progress bar
4. Search box with typeahead
5. Registration form
1. Polyfills for promise, bind, forEach, map
2. Array to object
In JavaScript, you can convert an array to an object using a loop or the reduce() method. The resulting object will have the array elements as values, with keys typically being indices or custom keys you specify. Here are examples of both methods:
Using a Loop:
function arrayToObject(arr) {
const obj = {};
for (let i = 0; i < arr.length; i++) {
obj[i] = arr[i];
}
return obj;
}
const myArray = ['apple', 'banana', 'cherry'];
const myObject = arrayToObject(myArray);
console.log(myObject);
In this example, we iterate through the array and use the indices as keys in the resulting object.
Using the reduce() Method:
function arrayToObject(arr) {
return arr.reduce((obj, item, index) => {
obj[index] = item;
return obj;
}, {});
}
const myArray = ['apple', 'banana', 'cherry'];
const myObject = arrayToObject(myArray);
console.log(myObject);
In this example, we use the reduce() method to transform the array into an object. The reduce() method iterates through the array, accumulating key-value pairs in the object. The initial value for the object is an empty object {}.
The resulting myObject will be:
{
0: 'apple',
1: 'banana',
2: 'cherry'
}
You can use either of these methods to convert an array to an object based on your specific requirements.
3. How to flatten nested array
You can flatten a nested array in JavaScript using different techniques. Below are some common methods to achieve this:
1. Using Recursion:
function flattenArray(arr) {
return arr.reduce((acc, current) => {
if (Array.isArray(current)) {
return acc.concat(flattenArray(current));
}
return acc.concat(current);
}, []);
}
const nestedArray = [1, [2, [3, 4], 5], 6];
const flattenedArray = flattenArray(nestedArray);
console.log(flattenedArray);
This code uses a recursive function that iterates through the array and flattens it by concatenating the subarrays. It continues to do so until all nested arrays are flattened.
2. Using flat() Method (ES6):
const nestedArray = [1, [2, [3, 4], 5], 6];
const flattenedArray = nestedArray.flat(Infinity);
console.log(flattenedArray);
The flat() method was introduced in ES6 and is a convenient way to flatten arrays. The Infinity argument means to flatten to any depth.
3. Using reduce() Method (ES5):
function flattenArray(arr) {
return arr.reduce(function (acc, current) {
return acc.concat(Array.isArray(current) ? flattenArray(current) : current);
}, []);
}
const nestedArray = [1, [2, [3, 4], 5], 6];
const flattenedArray = flattenArray(nestedArray);
console.log(flattenedArray);
This code achieves the same result as the first example, but it uses the reduce() method with an ES5-style function.
All of these methods will take a nested array and flatten it into a single array. The resulting flattenedArray will be [1, 2, 3, 4, 5, 6]. You can choose the method that best fits your project's compatibility and coding style.
1. Reverse array
You can reverse an array in JavaScript using the reverse() method, which reverses the elements of the array in place. Here's how you can use it:
const originalArray = [1, 2, 3, 4, 5];
originalArray.reverse();
console.log(originalArray); // Output: [5, 4, 3, 2, 1]
In this example, we have an array called originalArray, and we call the reverse() method on it. This method modifies the array in place, so the elements are reversed, as shown in the output.
If you want to create a new reversed array without modifying the original array, you can use the spread operator:
const originalArray = [1, 2, 3, 4, 5];
const reversedArray = [...originalArray].reverse();
console.log(reversedArray); // Output: [5, 4, 3, 2, 1]
console.log(originalArray); // Original array remains unchanged: [1, 2, 3, 4, 5]
In this case, the originalArray is copied to a new array reversedArray, and the reverse() method is applied to the copy, leaving the original array unaffected.
2. Anagram
An anagram is a word or phrase formed by rearranging the letters of another word or phrase, typically using all the original letters exactly once. To check if two strings are anagrams in JavaScript, you can use the following code:
function isAnagram(str1, str2) {
// Remove spaces and convert to lowercase
str1 = str1.replace(/\s/g, '').toLowerCase();
str2 = str2.replace(/\s/g, '').toLowerCase();
// Sort both strings and compare
return str1.split('').sort().join('') === str2.split('').sort().join('');
}
const word1 = "listen";
const word2 = "silent";
if (isAnagram(word1, word2)) {
console.log(`${word1} and ${word2} are anagrams.`);
} else {
console.log(`${word1} and ${word2} are not anagrams.`);
}
3. Fibbonacci
The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones, typically starting with 0 and 1. Here's how you can generate the Fibonacci sequence in JavaScript using a loop:
function generateFibonacci(n) {
const fibonacci = [0, 1];
for (let i = 2; i < n; i++) {
const nextFib = fibonacci[i - 1] + fibonacci[i - 2];
fibonacci.push(nextFib);
}
return fibonacci;
}
const n = 10; // Change this to the desired number of Fibonacci numbers
const fibonacciSequence = generateFibonacci(n);
console.log(fibonacciSequence);
4.
Actual Q/A
1. Return sum of 5 numbers, use currying
You can use currying in JavaScript to return the sum of 5 numbers. Currying involves creating a series of functions, each accepting one argument, which can be composed to achieve the desired result. Here's an example of a curried function that sums 5 numbers:
function curriedSum(a) {
return function(b) {
return function(c) {
return function(d) {
return function(e) {
return a + b + c + d + e;
};
};
};
};
}
// Usage
const sum = curriedSum(1)(2)(3)(4)(5);
console.log(sum); // Output: 15
In this example, curriedSum is a curried function that takes five arguments, each applied one at a time using a series of nested functions. The final function returns the sum of all five numbers.
You can call this curried function with individual arguments as shown in the sum variable. It allows you to calculate the sum of the numbers in a step-by-step fashion.
Currying is a functional programming technique that can be useful for building more modular and reusable functions, particularly in cases where you want to partially apply arguments.
2. Return max repeated chars in a string
3. return longest string
To return the longest string from an array of strings in JavaScript, you can use the reduce method to iterate through the array and keep track of the longest string encountered. Here's an example:
function findLongestString(strings) {
if (strings.length === 0) {
return null; // Handle the case when the array is empty
}
return strings.reduce((longest, current) => {
return current.length > longest.length ? current : longest;
}, strings[0]);
}
// Usage
const stringArray = ["apple", "banana", "cherry", "date", "elderberry"];
const longestString = findLongestString(stringArray);
console.log(`The longest string is: "${longestString}"`);
4. display hello every 1 second for 10 seconds
You can use the setInterval function to display "Hello" every 1 second for 10 seconds. Here's an example:
let count = 0;
const intervalId = setInterval(() => {
if (count < 10) {
console.log("Hello");
count++;
} else {
clearInterval(intervalId);
}
}, 1000);
In this code:
-
We initialize a
countvariable to keep track of the number of times "Hello" has been displayed. -
We use
setIntervalto execute a function every 1000 milliseconds (1 second). -
In the function, we check if
countis less than 10. If it is, we log "Hello" to the console and incrementcount. Ifcountreaches 10, we clear the interval usingclearInterval, which stops the execution.
This code will display "Hello" every second for 10 seconds.
5. shallow copy deep copy code example
In JavaScript, you can create shallow and deep copies of objects using various techniques. Here's an overview of how to do shallow and deep copies:
Shallow Copy:
A shallow copy creates a new object that is a copy of the original object with a new reference. However, if the original object contains nested objects, they will still reference the same objects. To perform a shallow copy, you can use methods like spread operators ({ ... }), Object.assign(), and array methods like slice().
- Spread Operator:
Using the spread operator ({ ... }) is a straightforward way to create a shallow copy of an object:
const originalObject = { a: 1, b: 2 };
const shallowCopy = { ...originalObject };
console.log(shallowCopy); // { a: 1, b: 2 }
- Object.assign():
The Object.assign() method can be used to copy the values of all enumerable properties from one or more source objects to a target object:
const originalObject = { a: 1, b: 2 };
const shallowCopy = Object.assign({}, originalObject);
console.log(shallowCopy); // { a: 1, b: 2 }
Deep Copy:
A deep copy creates a new object where all nested objects and their properties are recursively copied. This ensures that no references to the original object are maintained. To perform a deep copy, you can use methods like JSON.parse() and JSON.stringify() (although it has some limitations, e.g., it can't copy functions) or use custom deep copy functions.
Example of deep copy using JSON.parse() and JSON.stringify():
const originalObject = { a: 1, b: { c: 2 } };
const deepCopy = JSON.parse(JSON.stringify(originalObject));
console.log(deepCopy); // { a: 1, b: { c: 2 } }
Please note that the deep copy using JSON.parse() and JSON.stringify() has some limitations, such as not being able to copy functions or objects with circular references. To create a deep copy with custom logic, you'll need to write a custom function to recursively copy nested objects and handle circular references if necessary.
6. sort array of numbers
You can sort an array of numbers in JavaScript using the sort() method. By default, the sort() method will convert the elements to strings and then sort them lexicographically. To sort an array of numbers in ascending order, you can use the sort() method without any arguments. To sort in descending order, you can pass a custom comparison function.
Here's an example of sorting an array of numbers in both ascending and descending order:
// Sorting in ascending order (default behavior)
const numbersAscending = [5, 2, 9, 1, 5, 6];
const sortedAscending = numbersAscending.sort((a, b) => a - b);
console.log("Ascending Order:", sortedAscending);
// Sorting in descending order (using a custom comparison function)
const numbersDescending = [5, 2, 9, 1, 5, 6];
const sortedDescending = numbersDescending.sort((a, b) => b - a);
console.log("Descending Order:", sortedDescending);
Output:
Ascending Order: [1, 2, 5, 5, 6, 9]
Descending Order: [9, 6, 5, 5, 2, 1]
In the code above:
-
The
sort()method without any arguments sorts the array in ascending order. -
To sort the array in descending order, a custom comparison function is used. The function subtracts
bfroma, which will cause the sorting to be reversed.
This approach works for sorting arrays of numbers in both ascending and descending order.
7. sum of array using reduce
You can calculate the sum of an array of numbers in JavaScript using the reduce() method. Here's how to do it:
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
console.log("Sum:", sum); // Output: 15
8. use map to find probability of a string to be a palindrome
To check if a string is a palindrome in JavaScript, you can create a function that compares the string with its reverse. If the string is the same when reversed, it is a palindrome. Here's an example of how to do this:
function isPalindrome(str) {
// Remove non-alphanumeric characters and convert to lowercase
str = str.replace(/[^a-zA-Z0-9]/g, '').toLowerCase();
// Compare the string with its reverse
return str === str.split('').reverse().join('');
}
const inputString = "A man, a plan, a canal, Panama";
const result = isPalindrome(inputString);
if (result) {
console.log(`"${inputString}" is a palindrome.`);
} else {
console.log(`"${inputString}" is not a palindrome.`);
}
To check if a string is a palindrome using the map function in JavaScript, you can use the following code:
function isPalindrome(str) {
// Remove non-alphanumeric characters and convert to lowercase
str = str.replace(/[^a-zA-Z0-9]/g, '').toLowerCase();
// Create an array of characters from the cleaned string
const characters = str.split('');
// Use the `map` function to create a reversed array
const reversed = characters.map((char, index) => characters[characters.length - 1 - index]);
// Convert the reversed array back to a string
const reversedStr = reversed.join('');
// Compare the original string with the reversed string
return str === reversedStr;
}
const inputString = "A man, a plan, a canal, Panama";
const result = isPalindrome(inputString);
if (result) {
console.log(`"${inputString}" is a palindrome.`);
} else {
console.log(`"${inputString}" is not a palindrome.`);
}
9. Enter the numbers 1-10 into an array in ascending order using unshift
The unshift() method adds one or more elements to the beginning of an array. If you want to add numbers from 1 to 10 in ascending order to an array using unshift(), you can do it like this:
const numbersArray = [];
for (let i = 1; i <= 10; i++) {
numbersArray.unshift(i);
}
console.log(numbersArray); // Output: [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
10. display numbers multiples of 5 using filter and map method
You can display numbers that are multiples of 5 from an array using the filter and map methods in JavaScript. Here's an example:
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
// Use filter to select multiples of 5
const multiplesOf5 = numbers.filter((number) => number % 5 === 0);
// Use map to display the selected numbers
const displayMultiples = multiplesOf5.map((number) => `Multiple of 5: ${number}`);
console.log(displayMultiples);
[
'Multiple of 5: 5',
'Multiple of 5: 10'
]
Basic JavaScript Problems:
-
Write a function to add two numbers.
-
Create a function that checks if a given number is even or odd.
-
Implement a function to find the largest element in an array.
-
Write a JavaScript function to reverse a string.
-
Create a function to calculate the factorial of a number.
-
Implement a function to check if a given string is a palindrome.
-
Write a function to find the sum of all numbers in an array.
-
Create a function to remove duplicates from an array.
-
Implement a function to find the longest word in a sentence.
-
Write a JavaScript function to count the number of vowels in a string.
-
Intermediate JavaScript Problems:
-
Create a function to find the second smallest element in an array.
-
Implement a function to check if a given string is an anagram of another string.
-
Write a function to check if a string contains only unique characters.
-
Create a function to generate all permutations of a string.
-
Implement a function to merge two sorted arrays into a single sorted array.
-
Write a JavaScript function to reverse words in a sentence.
-
Create a function to find the first non-repeated character in a string.
-
Implement a function to find the intersection of two arrays.
-
Write a function to remove all even numbers from an array.
-
Create a function to find the missing number in an array of sequential integers.
-
Advanced JavaScript Problems:
-
Implement a function to flatten a nested array.
-
Write a JavaScript function to implement binary search.
-
Create a function to find the longest increasing subarray in an array.
-
Implement a function to implement a deep clone of an object.
-
Write a function to determine if a string has balanced parentheses.
-
Create a function to implement a basic calculator that evaluates arithmetic expressions.
-
Implement a function to find the common ancestor of two nodes in a binary tree.
-
Write a JavaScript function to implement a linked list.
-
Create a function to implement a priority queue.
-
Implement a function to find the shortest path in a graph (e.g., Dijkstra's algorithm).
-
JavaScript and Web Development Problems:
-
Create a simple to-do list web application using HTML, CSS, and JavaScript.
-
Implement a basic image slider or carousel using JavaScript and CSS.
-
Write JavaScript code to fetch and display data from a REST API.
-
Create a form validation script using regular expressions to validate user inputs.
-
Implement a responsive navigation menu that changes based on screen size.
-
Build a simple weather app that fetches and displays weather data for a given location using a weather API.
-
Create a basic chat application using WebSocket technology.
-
Implement a dynamic search functionality that filters and displays results as the user types.
-
Write a JavaScript program to convert between different units (e.g., temperature, length, currency).
-
Build a web-based calculator that handles basic and scientific calculations.