|
| 1 | +/** |
| 2 | + * Using the JavaScript language, have the function wildcardCharacters(str) read |
| 3 | + * str which will contain two strings separated by a space. The first string |
| 4 | + * will consist of the following sets of characters: +, *, and {N} which is |
| 5 | + * optional. The plus (+) character represents a single alphabetic character, |
| 6 | + * the asterisk (*) represents a sequence of the same character of length 3 |
| 7 | + * unless it is followed by {N} which represents how many characters should |
| 8 | + * appear in the sequence where N will be at least 1. Your goal is to determine |
| 9 | + * if the second string exactly matches the pattern of the first string in the |
| 10 | + * input. |
| 11 | + * |
| 12 | + * For example: if str is "++*{5} gheeeee" then the second string in this case |
| 13 | + * does match the pattern, so your program should return the string true. If the |
| 14 | + * second string does not match the pattern your program should return the |
| 15 | + * string false. |
| 16 | + * |
| 17 | + * https://coderbyte.com/results/bhanson:Wildcard%20Characters:JavaScript |
| 18 | + * |
| 19 | + * @param {string} str |
| 20 | + * @return {string} 'true' or 'false' |
| 21 | + */ |
| 22 | +function wildcardCharacters(str) { |
| 23 | + // Separate inputs |
| 24 | + const pair = str.split(' '); |
| 25 | + const patternTokens = pair[0]; |
| 26 | + const matchString = pair[1]; |
| 27 | + |
| 28 | + // Step 1: Build a regular expression from the given pattern |
| 29 | + let matchRegex = '^'; |
| 30 | + |
| 31 | + for (let i = 0, n = 1; i < patternTokens.length; i++) { |
| 32 | + switch (patternTokens[i]) { |
| 33 | + case '+': |
| 34 | + matchRegex += '[a-z]'; |
| 35 | + break; |
| 36 | + case '*': |
| 37 | + let repeat = 0; |
| 38 | + if (tokenHasLengthParameter(i)) { |
| 39 | + // Custom length |
| 40 | + repeat = Number(str[i + 2]) - 1; |
| 41 | + i = i + 3; |
| 42 | + } else { |
| 43 | + // Default length 3 (one letter plus two repeats) |
| 44 | + repeat = 2; |
| 45 | + } |
| 46 | + |
| 47 | + matchRegex += '([a-z])\\' + n++ + '{' + repeat + '}'; |
| 48 | + break; |
| 49 | + default: |
| 50 | + break; |
| 51 | + } |
| 52 | + } |
| 53 | + matchRegex += '$'; |
| 54 | + |
| 55 | + // Step 2: Apply regex to matchString and return results |
| 56 | + matchRegex = new RegExp(matchRegex, 'i'); |
| 57 | + return String(matchRegex.test(matchString)); |
| 58 | + |
| 59 | + /* Helpers */ |
| 60 | + |
| 61 | + function tokenHasLengthParameter(index) { |
| 62 | + if (index + 1 < patternTokens.length && str[index + 1] === '{') { |
| 63 | + return true; |
| 64 | + } |
| 65 | + return false; |
| 66 | + } |
| 67 | +} |
| 68 | + |
| 69 | +module.exports = wildcardCharacters; |
0 commit comments