Keeping the Waiting List in Order

Chloe Park is moving away, so plot 3 at the Brook Street Community Garden is free. Rosa’s report offers it to the first person on the waiting list, which is first come, first served, so the order of the names is the whole point.

In the Python script, the waiting list is a dict that maps member numbers to names. In this lesson, you’ll port that list to JavaScript, check that the right person still gets the plot, and see which JavaScript type keeps the order.

Port the Waiting List as an Object

Rosa’s script adds people in the order they asked and takes the first key with next(iter(waiting)). That works because a Python dict keeps every key in the order it was added, whatever the key’s type:

Language: Python
GIVEN_UP = 3
waiting = {
    214: "Dev Patel",
    187: "Hannah Cole",
    305: "Marek Nowak",
    42: "June Harris",
}
member = next(iter(waiting))
print(f"Plot {GIVEN_UP} goes to {waiting[member]} (member {member})")
print(f"Waiting list: {', '.join(waiting.values())}")

It prints Plot 3 goes to Dev Patel (member 214) and then Waiting list: Dev Patel, Hannah Cole, Marek Nowak, June Harris. Dev asked first, so Dev gets the plot.

A line-by-line port uses an object literal, the closest thing JavaScript has to a dict display. Object.keys() gives an array of the keys, so its first item stands in for next(iter(waiting)), and Object.values() gives the values, ready for .join(). The intro showed where the plot goes. Before running it, predict the waiting-list line:

Language: JavaScript
const GIVEN_UP = 3;
const waiting = {
  214: "Dev Patel",
  187: "Hannah Cole",
  305: "Marek Nowak",
  42: "June Harris",
};

const member = Object.keys(waiting)[0];
const name = waiting[member];
const names = Object.values(waiting).join(", ");
console.log(`Plot ${GIVEN_UP} goes to ${name} (member ${member})`);
console.log(`Waiting list: ${names}`);
console.log(waiting);

There’s no error, but the plot goes to the person who asked last:

Language: Program Output
Plot 3 goes to June Harris (member 42)
Waiting list: June Harris, Hannah Cole, Dev Patel, Marek Nowak
{
  '42': 'June Harris',
  '187': 'Hannah Cole',
  '214': 'Dev Patel',
  '305': 'Marek Nowak'
}

The logged object shows the keys in numerical order. June Harris is a long-standing member with a low number, and that number jumped her to the front of the queue.

See Why Member 42 Jumps the Queue

A number used as an object key is stored as a string, so 214 becomes '214'. JavaScript lists an object’s keys by a fixed rule. Keys that look like array indices come first, in ascending order. Other string keys follow, in the order they were added.

The rule exists because arrays are objects too. An array stores its indices as keys and has to list them as "0", "1", "2", in order. Plain objects share the rule, so member numbers get sorted like indices.

Reading the list from a file doesn’t help. JSON.parse() builds the same kind of object, so the text’s order is lost:

Language: JavaScript
const text = `{"214": "Dev Patel", "187": "Hannah Cole",
  "305": "Marek Nowak", "42": "June Harris"}`;
console.log(Object.keys(JSON.parse(text)));

The keys come back sorted, while Python’s json.loads() keeps them as the text lists them:

Language: Program Output
[ '42', '187', '214', '305' ]

Watch out for over-applying the rule, though, since only plain non-negative integers up to 4294967294 move, and a new half plot keyed "7A", or a plot number typed as "07", stays among the other keys in the order it was added, after the integer ones.

Keep the Order With a Map

A dict whose order matters needs a type that keeps it, and in JavaScript that’s a Map. A Map stores its entries apart from its properties, so neither the array index rule nor the conversion to strings touches them. It preserves insertion order, and 214 remains a number. You build one from an array of [key, value] pairs and read a value with .get().

A Map’s .keys() and .values() hand back iterators. As with Python’s waiting.keys(), you can’t index one, so you spread it into an array literal with ..., as list() does. [...waiting.keys()][0] is the port of next(iter(waiting)). Spreading is all you need from iterators here.

Here’s the port with a Map:

Language: JavaScript
const GIVEN_UP = 3;
const waiting = new Map([
  [214, "Dev Patel"],
  [187, "Hannah Cole"],
  [305, "Marek Nowak"],
  [42, "June Harris"],
]);

const member = [...waiting.keys()][0];
const name = waiting.get(member);
const names = [...waiting.values()].join(", ");
console.log(`Plot ${GIVEN_UP} goes to ${name} (member ${member})`);
console.log(`Waiting list: ${names}`);
console.log(typeof member);

Now the report matches Python’s, and member is a number, while the object gave the string '42':

Language: Program Output
Plot 3 goes to Dev Patel (member 214)
Waiting list: Dev Patel, Hannah Cole, Marek Nowak, June Harris
number

To get every pair, as Python’s for member, name in waiting.items(): does, you loop over the Map itself. Each pass gets a [key, value] array, and [member, name] in the loop header unpacks it, as tuple unpacking does:

Language: JavaScript
const waiting = new Map([
  [214, "Dev Patel"],
  [187, "Hannah Cole"],
  [305, "Marek Nowak"],
  [42, "June Harris"],
]);

for (const [member, name] of waiting) {
  console.log(member, name);
}

The pairs come out in the order people asked:

Language: Program Output
214 Dev Patel
187 Hannah Cole
305 Marek Nowak
42 June Harris

Watch out for porting .items() as Object.entries(waiting), because a Map’s entries aren’t its properties, as you saw, so the call returns an empty array and the loop runs zero times without an error.

So use a Map whenever key order or key types matter, loop over it with for...of, and spread .keys() or .values() for an array. Keep plain objects for records like a plot, whose fields you name in the code.

Next up is the video Updating a Map With set() and delete(). Ola Bakare, member 318, joins the waiting list, and Dev takes plot 3, so you’ll add and remove people.

Become a Member to join the conversation.