The purpose of this script is to enforce some rules for validating a keyboard shortcuts definition. In my case I want to reject duplicates keys improperly added in the combo
properties. This code rejects key combinations like CtrlAltPPwhich are not valid.
I would like to know what are the best practices regarding variable declaration placement (in/out) when method like Array.prototype.forEach
are used.
Which version of the code would you suggest as better? Also, for my understanding in the first snippet, variables declared inside the function in .forEach
are hoisted to that function and not to the check()
function, is my assumption correct?
window.app = {
combos: {
a: 'Ctrl-Alt-P',
b: 'Ctrl-Ctrl-Alt-P', // invalid
c: 'Ctrl-Alt-P-P'// invalid
},
check: function () {
var result = true,
combos = Object.keys(this.combos).forEach(function (combo) {
var comboWin = this.combos[combo],
parts = comboWin.split('-').sort(),
item,
itemNext;
for (var i = 0, len = parts.length; i < len; i++) {
item = parts[i];
itemNext = parts[i + 1];
if (item === itemNext) {
result = false;
alert('DUPLICATED PART IN: '+ comboWin + ' : ' + item);
}
}
}.bind(this));
return result;
}
}
window.app.check();
window.app = {
combos: {
a: 'Ctrl-Alt-P',
b: 'Ctrl-Ctrl-Alt-P', // invalid
c: 'Ctrl-Alt-P-P'// invalid
},
check: function () {
var result = true,
comboWin,
parts,
item,
itemNext;
combos = Object.keys(this.combos).forEach(function (combo) {
comboWin = this.combos[combo],
parts = comboWin.split('-').sort(),
item,
itemNext;
for (var i = 0, len = parts.length; i < len; i++) {
item = parts[i];
itemNext = parts[i + 1];
if (item === itemNext) {
result = false;
alert('DUPLICATED PART IN: ' + comboWin + ' : ' + item);
}
}
}.bind(this));
return result;
}
}
window.app.check();