Skip to content

Instantly share code, notes, and snippets.

@kyptin
Created October 21, 2019 16:40
Show Gist options
  • Save kyptin/a698656949872aef646a4eb1fb4397ac to your computer and use it in GitHub Desktop.
Save kyptin/a698656949872aef646a4eb1fb4397ac to your computer and use it in GitHub Desktop.
Effects refactoring example (UNC COMP 523)
// Goal: assign students to seats
// Usage: node before.js
// Context: UNC COMP 523 (https://comp523.cs.unc.edu)
// Exercise: refactor to manage effects better
const makePref = ([pid, section, isVip]) =>
({pid, section, isVip, isAssigned: false})
const makePrefs = (rows) => rows.map(makePref)
const prefs = makePrefs([
['111222333', 'front', false],
['111222444', 'front', true],
['111222555', 'middle', false],
['111222666', 'front', true],
['111222777', 'back', false],
['111222888', 'back', true],
])
let seatsBySection = {
'front': 2,
'middle': 2,
'back': 2,
}
let assignments = {
'front': [],
'middle': [],
'back': [],
'overflow': [],
}
for (var i = 0; i < prefs.length; i++) {
const {pid, section, isVip, isAssigned} = prefs[i]
if (isAssigned) continue
if (!isVip) continue
if (seatsBySection[section] > 0) {
seatsBySection[section] -= 1
assignments[section].push(pid)
prefs[i].isAssigned = true
} else {
assignments.overflow.push(pid)
prefs[i].isAssigned = true
}
}
for (var i = 0; i < prefs.length; i++) {
const {pid, section, isVip, isAssigned} = prefs[i]
if (isAssigned) continue
if (seatsBySection[section] > 0) {
seatsBySection[section] -= 1
assignments[section].push(pid)
prefs[i].isAssigned = true
} else {
assignments.overflow.push(pid)
prefs[i].isAssigned = true
}
}
for (var section in assignments) {
console.log(`PIDs in '${section}' section: ` + assignments[section].join(', '));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment