Data Structures

Let’s suppose we have all the information and we want to tell a person that she is Merlin and knows who everyone is… how would we organize that data?

Lists

Simple Lists

How about this database?

database = [ 'dogs', 32, 'cats', 42, 'birds', 5 ];

Access with subscripts?

database[1] // 'dogs'

Tuples

Better organization:

database = [ ['dogs', 32], ['cats', 42], ['birds', 5] ];

How many pets in our database?

database.length // 3

Helper Functions

Lists are fine if you have functions to help:

function pets(data, id) {
    return data[id];
}

function pet_name(data, id) {
    return pets(data, id)[0];
}

function pet_amount(data, id) {
    return pets(data, id)[1];
}

pet_name(database, 2)   // => 'birds'
pet_amount(database, 2) // => 5

Looping

Display all our pets?

for (var i=0; i < database.length; i++) {
   console.log( "We have " + pet_amount(database, i) +
                       " " + pet_name(database, i) );
}

Maps

Maps are better for data:

database = { 'dogs': 32, 'cats': 42, 'birds': 5 };

The pythonic approach (called dictionaries):

database['dogs']

JavaScript is easier:

database.dogs //> 32

Looping

Quite easy too:

for (var pet in database) {
   console.log("We have " + database[key] + " " + key);
}

Date: 2017 Apr 26

Created: 2024-01-12 Fri 17:05