I am worried about this each loop which progresses by deleting the things it is iterating over. It may well work, but we should verify (by reference to standards/MDN/stackexchange/whatever) that it works for good reason and portably.