Tuesday 12 March 2013

Quick Quiz

G'day:
Whilst writing some code, I disengaged my brain for a moment (I'm getting old: this happens), and ended up with some code I didn't mean to have, but before moving on and fixing it, I stopped to think... but there must be an easy way of doing what I had accidentally started to do.

Consider this code:

numbers = [
    {one="tahi"},
    {two="rua"},
    {three="toru"},
    {four="wha"}
];

substitute(numbers);

function substitute(array){
    for (var struct in array){
        // get the token
        // get the value of the token
        // do stuff
    }
}


What I've got is an array of structs; the structs being a substitution tokens & value: for example I want to swap "one" for "tahi". The structs are always just a single token and value. This array is passed into a function which - obviously - doesn't know what the tokens are. The function loops over the array, and then needs to extract the token and the value.

So how do you go about getting the token and then the value?

These two answers are too obvious, so don't count:

function substitute(array){
    for (var struct in array){
        for (var token in struct){ // it seems "wrong" to loop here
            writeOutput("token: #token#; value: #struct[token]#<br>");
        }
    }
}

function substitute(array){
    for (var struct in array){
        token = structKeyList(struct); // and this seems a bit hokey too
        writeOutput("token: #token#; value: #struct[token]#<br>");
    }
}

Go on: post some code. The answer I like the most will get a beer.

Warning:
If you post code as a comment here, make sure to escape any angle brackets (eg: &lt; and &gt;), otherwise Disqus will eat your code. Or use pastebin or something, and just post the link. Cheers.


PS:
In the end what I actually wanted to do was to have the structs like this:


numbers = [
    {token="one", value="tahi"},
    {token="two", value="rua"},
    {token="three", value="toru"},
    {token="four", value="wha"}
];

substitute(numbers);

function substitute(array){
    for (var struct in array){
        writeOutput("token: #struct.token#; value: #struct.value#<br>");
    }
}

Which is actually what I meant to be doing, but the initial approach has now piqued my interest, hence looking at how to solve it.

Righto.

--
Adam