Forum Moderators: open
For example:
a, one, red
a, one, green
a, two, pink
a, two, black
b, three, blue
c, foo
c, bar
At the moment I'm just using an if/else system but it's quite long winded, not easy to change and I'm sure there's a better way of doing it.
Ideally I'd like to set up the command structure in a data structure, and use a kinda loop to validate it. I've not done it before, I'm just not entirely sure how to go about it.
I'm thinking something like:
var commands = {
a: {
one: [ 'red', 'green'],
two: [ 'pink', 'black'],
},
b: {
three: [ 'blue'],
},
c: [ 'foo', 'bar']
}; As you can see the number of parameters won't always be the same, I'm just not sure of an efficient way of checking each parameter, without loads of if/else/if/else/switch/whatever/etc...
I want to be able to pass in the whole string, so I'd split the string into chunks, and check each one.
function checkCommand( str) {
var chunks = str.split( ",");
for( var c = 0; c <chunks.length; c++) {
...
// Determine if this chunk exists in the command structure?
...
}
} Anyone done anything like this?
function checkCommand(str) {
var chunks = str.split(",");
var c, node = null;
for (c = 0; c < chunks.length; c++) {
if (node == null) {
node = commands;
}
if (node[chunks[c]) {
node = node[chunks[0]];
}
else {
return false;
}
}
return true;
} In other words, keep assigning the node to each item in the path of the items in your string. If ever something is not found, return false.
Note, it's late Saturday night, I've had a couple glasses of wine, and I'm falling asleep at the keyboard, so I can't vouch for the quality of my code or my logic at this point. :-)
trying to see if it exists in the command structure
Yes I am. Checking that it's a number, or it's a string I can do as I go along.
Your logic is sound, I'd come up with a similar theory, problem I have it that I've ended up using arrays of OLN's, so I have to do a little more work but same kind of structure.
I think I may end up doing some recursive process to acomplish this.
The problem I'm having is that the initial value, of commands, is an array. This contains strings, and OLN. The OLN values also maybe a string, or another array.
This is making it difficult to examine each node, as it may be starting with either a string, array, or oln.
e.g.:
var commands = [
'this',
'that',
{ foo: 'bar' },
{ digits: [ 'fingers', 'toes']}
]
I wish I'd done something like this in my C++ days!
I've kinda got it working, I can test for an oln with an
eval( "node."+test)type thing but it's not very good.