How to use Map In Javascript
- In this apporch, we are using the Maps in JavaScript where we have used the two map objects (map1 and map2).
- This objects establish the connection between the chacraters in the input pattern and words in the input string, as well as the reverse mapping.
- This assures that the mappings are proper and returns true if the character and words are aligned correctly else false will be returned.
Examples:
function checkPattern(str, pattern) {
let words = str.split(' ')
if (pattern.length !== words.length) return false
let map1 = new Map();
let map2 = new Map();
for (let i = 0; i < pattern.length; i++) {
let key = pattern[i];
let value = words[i];
if (map1.has(key) || map2.has(value)) {
if (map1.get(key) !== value) return false;
if (map2.get(value) !== key) return false;
} else {
map1.set(key, value);
map2.set(value, key);
}
}
return true;
};
console.log(checkPattern("engineers rock", "er"));
console.log(checkPattern("engineers rock", "egr"));
console.log(checkPattern("engineers rock", "gsr"));
Output
true false false
JavaScript Program to Check if String Follows Order of Characters Defined by a Pattern or Not
In this JavaScript article, we will see the solution to the problem of checking if a string follows the order of characters defined by a pattern or not. We have given a string and pattern as the input and our task is to develop a program that will check whether the input string follows the same pattern according to the pattern given.
Example:
To solve this problem, we have three different approaches which are mentioned below:
Table of Content
- Using JavaScript Loops
- Using JavaScript Map
- Using Builtin Functions ‘every’, ‘reduce’, and ‘split’
- Using Regular Expression: