Made function more generic by adding an optional argument which defines the comparator function to be used for equality tests.