UNPKG

unordered-set

Version:

A couple of functions that make it easy to maintain an unordered set as an array in an efficient way

37 lines (30 loc) 677 B
exports.add = add exports.has = has exports.remove = remove exports.swap = swap function add (list, item) { if (has(list, item)) return item item._index = list.length list.push(item) return item } function has (list, item) { return item._index < list.length && list[item._index] === item } function remove (list, item) { if (!has(list, item)) return null var last = list.pop() if (last !== item) { list[item._index] = last last._index = item._index } return item } function swap (list, a, b) { if (!has(list, a) || !has(list, b)) return var tmp = a._index a._index = b._index list[a._index] = a b._index = tmp list[b._index] = b }