Skip to content

Instantly share code, notes, and snippets.

@manekinekko
Last active August 29, 2015 14:05
Show Gist options
  • Save manekinekko/8b1f33f2733025759da5 to your computer and use it in GitHub Desktop.
Save manekinekko/8b1f33f2733025759da5 to your computer and use it in GitHub Desktop.
The purpose of this algorithm is to tell if a given pattern is found in a list of patterns. In this example, we're trying to find the pattern [2,3,6] in a "commands" array. This algorithm uses a threshold value to ignore certain patterns.
(function(){
var threshold = 6;
var service = {
isCommandEntered: function isCommandEntered(commands, commandToFind){
return commands.map(function(value, index, self){
var n=1;
while(self[++index]===value) ++n;
return {command: value, weight: n};
})
.filter(function(value, index, self){
return !(self[index-1] && (self[index-1].command===self[index].command)) && value.weight <= threshold;
})
.map(function(value, index, self){
return value.command;
})
.join('').indexOf(commandToFind.join('')) >= 0;
}
};
// the pattern to find in a given command-list
var commandToFind = [2,3,6];
var commands = [];
// cas 1: empty command-list
console.log(service.isCommandEntered(commands, commandToFind));
// cas 2: valid command-list
commands = [1,1,2,2,2,2,3,6,6];
console.log(service.isCommandEntered(commands, commandToFind));
// cas 3: valid command-list containing a non-valid sub-command
commands = [1,1,2,2,2,2,3,6,6,1,1,1,1,1,1,1,1];
console.log(service.isCommandEntered(commands, commandToFind));
// cas 4: valid command-list
commands = [4,4,4,4,4,4,4,1,1,2,2,2,2,3,6,6];
console.log(service.isCommandEntered(commands, commandToFind));
// cas 4: valid command-list
commands = [4,4,4,4,4,4,4,1,1,1,1,1,1,1,2,2,2,2,3,6,6,1,1,1,1];
console.log(service.isCommandEntered(commands, commandToFind));
// cas 4: non-valid command-list
commands = [4,4,4,4,4,4,4,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,3,6,6,1,1];
console.log(service.isCommandEntered(commands, commandToFind));
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment