SitePoint Sponsor

User Tag List

Results 1 to 23 of 23

Threaded View

  1. #1
    Perl/Mason Guru Flawless_koder's Avatar
    Join Date
    Feb 2002
    Location
    Gatwick, UK
    Posts
    1,206
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Post Overloading Arrays for multi-dimensional purposes

    VARIABLE1,VARIABLE1,PROPERTY1,PROPERTY2...PROPERTY6|\

    You have a number of lines - in the above format.
    They are in a single variable.
    You want to take it
    and create a multi-dimensional Array.
    MORE than that - you want it more in an hash ( list, dictionary ) format.

    I thought it couldn't be done in JS.
    I finally hit a problem which i couldn't overcome without
    working out how to handle this.

    For anyone that doesn't know how these look:
    Code:
    [VARIABLE 1a]
        | - [VARIABLE 2a] = [ PROPERTY 1, PROPERTY 2 ...]
        | - [VARIABLE 3a] = [ PROPERTY 1, PROPERTY 2 ...]
        | - [VARIABLE 4a] = [ PROPERTY 1, PROPERTY 2 ...]
        | - [VARIABLE 5a] = [ PROPERTY 1, PROPERTY 2 ...]
    [VARIABLE 1b]
        | - [VARIABLE 2b] = [ PROPERTY 1, PROPERTY 2 ...]
        | - [VARIABLE 3b] = [ PROPERTY 1, PROPERTY 2 ...]
        | - [VARIABLE 4b] = [ PROPERTY 1, PROPERTY 2 ...]
        | - [VARIABLE 5b] = [ PROPERTY 1, PROPERTY 2 ...]
    Now you want to be able to access these by name but not
    have multiples, and not overwrite the previous value.

    The method I've ended up with looks like this:
    Code:
    MAKES = new Array();
    TYPES = new Array();
    
    var str='\
    ECMN,AVIS,FORD,MONDEO,GREEN,1.5|\
    ECMN,HERTZ,FORD,MONDEO,GREEN,1.5|\
    ECAR,HERTZ,FORD,MONDEO,GREEN,1.5|\
    ';
    
    var all = str.split(/\|/);
    
    for (i=0;i<all.length;i++){
            var set = all[i].split(/,/);
            if (!TYPES[set[0]]){ TYPES.push(set[0]); TYPES[set[0]] = 1; }
            if (!MAKES[set[1]]){ MAKES.push(set[1]); MAKES[set[1]] = 1; }
            l=set[0]+"['"+set[1]+"']=new Array('"+set[2]+"','"+set[3]+"','"+set[4]+"','"+set[5]+"')";
            try { eval(l); }
            catch(e) { eval(set[0]+' = new Array();'); eval(l); }
            }
    
    alert(eval(TYPES[1]+'["'+MAKES[1]+'"]'));
    alert(MAKES);
    Effectively this gives you the ablility to say:
    alert ( ECMN['AVIS'] ) and you'll get an array returned
    containing Ford Mondeo Green 1.5!

    Now i don't know if i'm being stupid - but to me that
    seems like a very slight breakthrough.

    Am i rediscovering the wheel, and is there a common way of doing this?

    Can anyone think of how to improve this?

    Flawless
    Last edited by Flawless_koder; Jul 26, 2002 at 04:30.
    ---=| If you're going to buy a pet - get a Shetland Giraffe |=---


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •