Wednesday, October 17, 2012

array utility routines

In the previous post, I talked about how, for a while, I tried to do a "multiple opportunity" version of my "windows of opportunity" opportune.h extension. The final version ended up using property arrays, but originally, I approached the problem with regular arrays. I kept on wanting to do something and would think, huh, is there a routine for that? I'd then remember there wasn't and then would write it. I had mixed success.

The Good:
routine ClearArray(array_to_be_cleared)
{
    local n
    for (n=0;n< array array_to_be_cleared[] ; n++ )
        {
        array array_to_be_cleared[n] = ""
        }

}
Sometimes, hey, I like to clear arrays. Nothing wrong with a routine that saves me some time.

The Bad:
routine AddArrayValue(arr, val)
{
    local i
    for (i=0; i< array arr[]; i++)
    {
        if array arr[i] = 0, ""
        {
            array arr[i] = val
            return i
        }
    }
}
The problem with this one is that it doesn't distinguish from successfully placing the value in element 0 or being unable to place the value in an empty slot at all. It'd be slightly more successful if I just changed it to a return-true-on-success/return-false-on-failure thing.

The Ugly:
routine InDisArray(arr, val)
{
    local i

    for (i=0; i< array arr[] ; i++)
    {
        if array arr[i] = val:  return i
    }
}
Bad pun aside ("in this array", get it?), this array-based version of InList has the same problem as AddArrayValue but is even more hampered by it, as returning-the-element-number is pretty important in such a routine. I could get around this by having element 0 return something else (like a constant called ZERO or the string "zero"), but it seems kind of dumb to make people remember this hack.

If anything, I think this all is just a good reminder why property arrays can be favorable to regular arrays in these kinds of instances, as property arrays start at element 1 and therefore avoid the element-0 problem.

No comments:

Post a Comment