Forked from chengsieuly/Match pattern with array.markdown
Created
July 21, 2016 14:29
-
-
Save thonly/dd8f470837589f21641eb5eac945e350 to your computer and use it in GitHub Desktop.
Match pattern with array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Match pattern! | |
* | |
* Given a pattern (array) and an array of strings, see if the pattern exist in array | |
* pattern: ['a', 'b', 'a'], test: ['cat', 'dog', 'cat'] => true | |
* pattern: ['a', 'b', 'a'], test: ['cat', 'dog', 'cat', 'cat'] => true | |
* pattern: ['a', 'b', 'a'], test: ['cat', 'dog', 'bear'] => false | |
* | |
*/ | |
// Pseudocode | |
// | |
// loop through pattern | |
// if pattern[i] doesn't exist in hash table, | |
// store value of Test[i] in hash w/ key being pattern[i] | |
// else | |
// check if test[i] = pattern[i] | |
// if doesn't match | |
// return false | |
// return true | |
// Using for-loop | |
function testPattern1(pattern, test) { | |
var store = {}; | |
for (let i = 0; i < pattern.length; i++) { | |
if (store[pattern[i]] && store[pattern[i]] !== test[i]) return false; | |
store[pattern[i]] = test[i]; | |
} | |
return true; | |
} | |
// Using forEach | |
function testPattern2(pattern, test) { | |
var store = {}; | |
var result = true; | |
pattern.forEach((val, i) => { | |
if (store[val] && store[val] !== test[i]) { | |
result = false; | |
return; | |
} | |
store[val] = test[i]; | |
}); | |
return result; | |
} | |
// Test | |
var pattern = ['a', 'b', 'a'], | |
test1 = ['cat', 'dog', 'cat'], | |
test2 = ['cat', 'dog', 'cat', 'cat'], | |
test3 = ['cat', 'dog', 'bear']; | |
// for-loop | |
console.log('for-loop ----------------------------->') | |
console.log(testPattern1(pattern, test1)); // true | |
console.log(testPattern1(pattern, test2)); // true | |
console.log(testPattern1(pattern, test3)); // false | |
// forEach | |
console.log('forEach ----------------------------->') | |
console.log(testPattern2(pattern, test1)); // true | |
console.log(testPattern2(pattern, test2)); // true | |
console.log(testPattern2(pattern, test3)); // false |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment