Skip to content

Instantly share code, notes, and snippets.

@chengsieuly
Created July 21, 2016 06:48
Show Gist options
  • Save chengsieuly/ad33ed059e3247dce20867c02cfae52e to your computer and use it in GitHub Desktop.
Save chengsieuly/ad33ed059e3247dce20867c02cfae52e to your computer and use it in GitHub Desktop.
Match pattern with array
/**
* 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