Taskcore
Remove duplicates from a list
Also called deduplicate a list, unique values, distinct elements, remove repeated items, dedupe by key.
Remove the repeated items from a list and keep the first copy of each item in its input order, and remove records that have the same key.
- Evidence
- Code in 10 languages
Task
Remove the repeated items from a list of strings. Keep the first copy of each item, and remove the later copies. The items that stay keep their input order. So ["apple", "pear", "apple", "fig", "pear"] becomes ["apple", "pear", "fig"].
Two items are equal only if they have the same code points. The function does not fold case, does not normalize Unicode and does not trim spaces. So "a" and "A" are two items, and " a" and "a" are two items. The precomposed é (U+00E9) and e followed by U+0301 look the same, but they are two items too.
A second function removes records that have the same key. Each user is a name and an email, and the emails are ASCII. The function keeps the first user for each email, and it compares the emails with the letters A to Z changed to lower case.
Solutions
Each solution reads the list one time. It keeps a set of the items that it saw. An item that is not in the set goes to the result and into the set. The order comes from the list, not from the set.
- Python.
list(dict.fromkeys(items)). A dict keeps its keys in insertion order, andfromkeysadds each key one time.unique_byuses a set of keys and a loop, andunique_by_emailgives it the keyu.email.lower(). - JavaScript and TypeScript.
[...new Set(items)]. ASetvisits its values in insertion order. A value that is already in the set does not move.uniqueBykeeps aSetof keys and a result array. - Java.
items.stream().distinct().toList(). For an ordered stream,distinctkeeps the first copy of each item.uniqueByusesHashSet.add, which returnsfalsewhen the set already has the key. The email key istoLowerCase(Locale.ROOT). - C#. A loop with
HashSet<TKey>.Add, which returnsfalsefor a key that is already present. The Remarks ofDistinctandDistinctBysay that their result is an unordered sequence. The loop gives the input order from its design. The email key isToLowerInvariant(). - Go. A generic
UniqueBy[T any, K comparable]with amap[K]struct{}and a result slice.Uniquecalls it with the item as its own key. The map does not give the order, because the order of arangeover a map is not specified. - Rust.
items.iter().filter(|&x| seen.insert(x)).cloned().collect().HashSet::insertreturnstrueonly if the set did not have the value. The set holds references, so it copies only the items that stay. The email key isto_ascii_lowercase(). - C++. A template
unique_bywith astd::unordered_setof keys.insert(key).secondistrueonly if the insertion took place.uniqueusesstd::string_viewkeys that point into the input. - C. The function works in place on an array of
const char *and returns the new length. It compares each item withstrcmpagainst the items that it kept, so the time grows with n². The email compare changes A to Z by hand, becausestrcasecmpuses the current locale. - Bash.
awk '!seen[$0]++'reads one item on each line. An uninitialized awk value is zero, so!seen[$0]++is true only for the first copy. A pattern with no action prints the line. For users,LC_ALL=C awk -F '\t' '!seen[tolower($2)]++'uses field 2 as the key. The items cannot hold a newline.
Edge cases
The cases are in cases/basic.jsonl and cases/edge.jsonl. The cases of the users are in cases/by-key.jsonl.
emptyandsingle: the result is the input.all-same: three copies of"x"become one.no-duplicates: the result is the input, in the input order. A solution that sorts fails here.not-adjacentandadjacent: copies apart and copies side by side. A solution that removes only adjacent copies failsnot-adjacent, and it keeps two"a"inadjacent.empty-string:""is an item, and its later copies go.case,whitespaceandnumber-like:"a"and"A"," a"and"a ", and"1","01"and"1.0"are all different items.normalization: U+00E9 andewith U+0301 are two items.non-ascii: CJK text, an emoji above U+FFFF andü.- In
cases/by-key.jsonl:ADA@Example.comis the same email asada@example.com, the first user wins, two users with the same name and two emails both stay, anda.b@example.comis notab@example.com.
Pitfalls
- A set does not keep the order. In Python,
list(set(items))removes the copies, but a set is an unordered collection. The order can change from one run to the next for strings, because Python gives the hashes ofstrobjects a random seed. Usedict.fromkeys:
This code runs but gives a wrong answer on purpose.
print(list(set([30, 10, 30, 20, 10])))
[10, 20, 30]
print(list(dict.fromkeys([30, 10, 30, 20, 10])))
[30, 10, 20]
The same problem is in Java HashSet, Go maps and Rust HashSet. Their iteration order is not specified.
- Removing only adjacent copies.
uniqcompares adjacent lines only.sort -uremoves all copies, but it changes the order. Goslices.Compactalso replaces only consecutive runs of equal elements:
This code runs but gives a wrong answer on purpose.
printf '%s\n' b a b a | uniq
echo ---
printf '%s\n' b a b a | sort -u
b
a
b
a
---
a
b
printf '%s\n' b a b a | awk '!seen[$0]++'
b
a
- NaN in JavaScript. A
Setcompares values with SameValueZero, soNaNis the same asNaN. The idiom withfilterandindexOfuses strict equality, andindexOf(NaN)is always -1. So it removes everyNaN. It also compares each item with all the items before it:
This code runs but gives a wrong answer on purpose.
console.log([NaN, 1, NaN].filter((v, i, a) => a.indexOf(v) === i));
[ 1 ]
console.log([...new Set([NaN, 1, NaN])]);
[ NaN, 1 ]
- NaN in Python. A NaN is not equal to itself. But the built-in containers assume that an object is equal to itself, so they skip the test for the same object. So two references to one NaN become one key, and two NaN objects stay two keys:
nan = float("nan")
print(list(dict.fromkeys([nan, nan])))
print(list(dict.fromkeys([float("nan"), float("nan")])))
[nan]
[nan, nan]
- A class with no equality. In Java, the
equalsofObjectis true only for the same object. SodistinctandHashSetkeep two objects with the same fields. A record getsequalsandhashCodefrom its components. If you writeequalsyourself, also writehashCode, because equal objects must have equal hash codes:
This code runs but gives a wrong answer on purpose.
import java.util.List;
public class Main {
static final class Point {
final int x;
final int y;
Point(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public String toString() {
return "(" + x + ", " + y + ")";
}
}
public static void main(String[] args) {
System.out.println(List.of(new Point(1, 2), new Point(1, 2)).stream().distinct().toList());
}
}
[(1, 2), (1, 2)]
import java.util.List;
public class Main {
record Point(int x, int y) {}
public static void main(String[] args) {
System.out.println(List.of(new Point(1, 2), new Point(1, 2)).stream().distinct().toList());
}
}
[Point[x=1, y=2]]
- A key that depends on the locale. Java
toLowerCase()uses the default locale. In a Turkish locale,Ibecomes a dotlessı(U+0131), soBILL@EXAMPLE.COMandbill@example.comget different keys. UsetoLowerCase(Locale.ROOT). In C#, useToLowerInvariant(). In C and C++,toloweruses the current C locale, and POSIXstrcasecmpuses the current locale too:
This code runs but gives a wrong answer on purpose.
import java.util.HashSet;
import java.util.Locale;
import java.util.Set;
public class Main {
public static void main(String[] args) {
Locale.setDefault(Locale.forLanguageTag("tr")); // as on a machine with a Turkish locale
Set<String> seen = new HashSet<>();
for (String email : new String[] {"bill@example.com", "BILL@EXAMPLE.COM"}) {
System.out.println(email + " is new: " + seen.add(email.toLowerCase()));
}
}
}
bill@example.com is new: true
BILL@EXAMPLE.COM is new: true
import java.util.HashSet;
import java.util.Locale;
import java.util.Set;
public class Main {
public static void main(String[] args) {
Locale.setDefault(Locale.forLanguageTag("tr"));
Set<String> seen = new HashSet<>();
for (String email : new String[] {"bill@example.com", "BILL@EXAMPLE.COM"}) {
System.out.println(email + " is new: " + seen.add(email.toLowerCase(Locale.ROOT)));
}
}
}
bill@example.com is new: true
BILL@EXAMPLE.COM is new: false
- A key that is too loose. Case folding, trimming and Unicode normalization make more items equal. Do them only when the data needs them, and do them in the key, so that the result keeps the original items. An email address is an example: the solution here lowers only the letters A to Z, and it keeps the dots.
Related tasks
- Sort a list of records: sort the records after you remove the copies, or sort them by the same key.
- Split a string: split a line into the items of a list.
- Read a file line by line: read the items from a file, one on each line.
- Read from standard input: read the lines that
awk '!seen[$0]++'gets. - Reverse a string: another job where code points and visible characters are not the same.
Code
The build runs the native tests of each language in a pinned toolchain.
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/remove-duplicates-from-a-list/.
from collections.abc import Callable, Hashable, Iterable
from typing import NamedTuple
class User(NamedTuple):
name: str
email: str
def unique[T: Hashable](items: Iterable[T]) -> list[T]:
"""Return the items without later copies. The first copies keep their order."""
# A dict keeps its keys in insertion order. A set does not.
return list(dict.fromkeys(items))
def unique_by[T, K: Hashable](items: Iterable[T], key: Callable[[T], K]) -> list[T]:
"""Return the first item for each key, in input order."""
seen: set[K] = set()
out: list[T] = []
for item in items:
k = key(item)
if k not in seen:
seen.add(k)
out.append(item)
return out
def unique_by_email(users: Iterable[User]) -> list[User]:
"""Return the first user for each email. Case does not matter in the emails."""
return unique_by(users, lambda u: u.email.lower())
test_unique.py 62 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/remove-duplicates-from-a-list/.
import pytest
from unique import User, unique, unique_by_email
CASES = {
"repeats": (["apple", "pear", "apple", "fig", "pear"], ["apple", "pear", "fig"]),
"words": (["to", "be", "or", "not", "to", "be"], ["to", "be", "or", "not"]),
"empty": ([], []),
"single": (["a"], ["a"]),
"all-same": (["x", "x", "x"], ["x"]),
"no-duplicates": (["c", "a", "b"], ["c", "a", "b"]),
"not-adjacent": (["a", "b", "a", "b"], ["a", "b"]),
"adjacent": (["a", "a", "b", "b", "a"], ["a", "b"]),
"empty-string": (["", "a", "", "b"], ["", "a", "b"]),
"case": (["a", "A", "a"], ["a", "A"]),
"normalization": (["\u00e9", "e\u0301", "\u00e9"], ["\u00e9", "e\u0301"]),
"whitespace": ([" a", "a", "a ", " a"], [" a", "a", "a "]),
"number-like": (["1", "01", "1.0", "1"], ["1", "01", "1.0"]),
"non-ascii": (["日本", "🙂", "日本", "🙂", "ü"], ["日本", "🙂", "ü"]),
}
# The cases of cases/by-key.jsonl.
BY_KEY = {
"case-insensitive": (
[("Ada", "ada@example.com"), ("Bob", "bob@example.com"), ("Ada L.", "ADA@Example.com")],
[("Ada", "ada@example.com"), ("Bob", "bob@example.com")],
),
"empty": ([], []),
"same-name-other-email": (
[("Sam", "sam@a.example"), ("Sam", "sam@b.example")],
[("Sam", "sam@a.example"), ("Sam", "sam@b.example")],
),
"first-record-wins": (
[("Old", "x@example.com"), ("New", "X@EXAMPLE.COM")],
[("Old", "x@example.com")],
),
"dots-differ": (
[("Al", "a.b@example.com"), ("Bo", "ab@example.com")],
[("Al", "a.b@example.com"), ("Bo", "ab@example.com")],
),
"not-adjacent": (
[("A", "a@example.com"), ("B", "b@example.com"), ("C", "A@example.com"), ("D", "B@EXAMPLE.com")],
[("A", "a@example.com"), ("B", "b@example.com")],
),
}
@pytest.mark.parametrize("name", CASES)
def test_unique(name: str) -> None:
given, want = CASES[name]
items = list(given)
assert unique(items) == want
assert items == given, "the input must not change"
@pytest.mark.parametrize("name", BY_KEY)
def test_unique_by_email(name: str) -> None:
given, want = BY_KEY[name]
assert unique_by_email([User(*u) for u in given]) == [User(*u) for u in want]
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/remove-duplicates-from-a-list/.
#include "unique.hpp"
#include <algorithm>
#include <string_view>
namespace dedupe {
std::vector<std::string> unique(const std::vector<std::string>& items) {
// The views point into items, so the set copies no string.
return unique_by(items, [](const std::string& s) { return std::string_view(s); });
}
std::vector<User> unique_by_email(const std::vector<User>& users) {
return unique_by(users, [](const User& u) {
// Not std::tolower: it uses the current C locale.
std::string key = u.email;
std::ranges::transform(key, key.begin(), [](unsigned char c) {
return static_cast<char>(c >= 'A' && c <= 'Z' ? c - 'A' + 'a' : c);
});
return key;
});
}
} // namespace dedupe
unique.hpp 39 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/remove-duplicates-from-a-list/.
#pragma once
#include <string>
#include <type_traits>
#include <unordered_set>
#include <vector>
namespace dedupe {
struct User {
std::string name;
std::string email; // ASCII
bool operator==(const User&) const = default;
};
// Returns the first item for each key, in input order.
template <class T, class Key>
std::vector<T> unique_by(const std::vector<T>& items, Key key) {
std::unordered_set<std::decay_t<std::invoke_result_t<Key&, const T&>>> seen;
std::vector<T> out;
for (const T& item : items) {
// insert(...).second is true only if the set did not have the key.
if (seen.insert(key(item)).second) {
out.push_back(item);
}
}
return out;
}
// Returns the items without later copies. The first copies keep their order.
std::vector<std::string> unique(const std::vector<std::string>& items);
// Returns the first user for each email. Case does not matter in the emails.
std::vector<User> unique_by_email(const std::vector<User>& users);
} // namespace dedupe
test_unique.cpp 64 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/remove-duplicates-from-a-list/.
#include "unique.hpp"
#include <cstdio>
#include <string>
#include <vector>
namespace {
using Strings = std::vector<std::string>;
using Users = std::vector<dedupe::User>;
int failures = 0;
void report(const std::string& name, bool ok) {
std::printf("%s %s\n", ok ? "ok" : "FAIL", name.c_str());
if (!ok) ++failures;
}
void check(const char* name, const Strings& given, const Strings& want) {
Strings input = given;
report(name, dedupe::unique(input) == want && input == given);
}
void check_users(const char* name, const Users& given, const Users& want) {
report(std::string("by-key ") + name, dedupe::unique_by_email(given) == want);
}
} // namespace
int main() {
check("repeats", {"apple", "pear", "apple", "fig", "pear"}, {"apple", "pear", "fig"});
check("words", {"to", "be", "or", "not", "to", "be"}, {"to", "be", "or", "not"});
check("empty", {}, {});
check("single", {"a"}, {"a"});
check("all-same", {"x", "x", "x"}, {"x"});
check("no-duplicates", {"c", "a", "b"}, {"c", "a", "b"});
check("not-adjacent", {"a", "b", "a", "b"}, {"a", "b"});
check("adjacent", {"a", "a", "b", "b", "a"}, {"a", "b"});
check("empty-string", {"", "a", "", "b"}, {"", "a", "b"});
check("case", {"a", "A", "a"}, {"a", "A"});
check("normalization", {"\u00e9", "e\u0301", "\u00e9"}, {"\u00e9", "e\u0301"});
check("whitespace", {" a", "a", "a ", " a"}, {" a", "a", "a "});
check("number-like", {"1", "01", "1.0", "1"}, {"1", "01", "1.0"});
check("non-ascii", {"日本", "🙂", "日本", "🙂", "ü"}, {"日本", "🙂", "ü"});
// The cases of cases/by-key.jsonl.
check_users("case-insensitive",
{{"Ada", "ada@example.com"}, {"Bob", "bob@example.com"}, {"Ada L.", "ADA@Example.com"}},
{{"Ada", "ada@example.com"}, {"Bob", "bob@example.com"}});
check_users("empty", {}, {});
check_users("same-name-other-email", {{"Sam", "sam@a.example"}, {"Sam", "sam@b.example"}},
{{"Sam", "sam@a.example"}, {"Sam", "sam@b.example"}});
check_users("first-record-wins", {{"Old", "x@example.com"}, {"New", "X@EXAMPLE.COM"}},
{{"Old", "x@example.com"}});
check_users("dots-differ", {{"Al", "a.b@example.com"}, {"Bo", "ab@example.com"}},
{{"Al", "a.b@example.com"}, {"Bo", "ab@example.com"}});
check_users("not-adjacent",
{{"A", "a@example.com"}, {"B", "b@example.com"}, {"C", "A@example.com"}, {"D", "B@EXAMPLE.com"}},
{{"A", "a@example.com"}, {"B", "b@example.com"}});
return failures == 0 ? 0 : 1;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/remove-duplicates-from-a-list/.
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import java.util.function.Function;
/** Removes duplicates from lists and keeps the input order. */
public final class Unique {
/** A record of a user. A record gets equals and hashCode from its components. */
public record User(String name, String email) {}
private Unique() {}
/** Returns a new list of the items without later copies. The first copies keep their order. */
public static <T> List<T> unique(List<T> items) {
// For an ordered stream, distinct keeps the first copy of each item.
return items.stream().distinct().toList();
}
/** Returns a new list of the first item for each key, in input order. */
public static <T, K> List<T> uniqueBy(List<T> items, Function<? super T, ? extends K> key) {
Set<K> seen = new HashSet<>();
List<T> out = new ArrayList<>();
for (T item : items) {
// add returns false if the set already has the key.
if (seen.add(key.apply(item))) {
out.add(item);
}
}
return out;
}
/** Returns the first user for each email. Case does not matter in the emails. */
public static List<User> uniqueByEmail(List<User> users) {
// Locale.ROOT: the rules of the default locale can change the letters, as in Turkish.
return uniqueBy(users, u -> u.email().toLowerCase(Locale.ROOT));
}
}
UniqueTest.java 80 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/remove-duplicates-from-a-list/.
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
class UniqueTest {
static Stream<Arguments> cases() {
return Stream.of(
Arguments.of("repeats", List.of("apple", "pear", "apple", "fig", "pear"), List.of("apple", "pear", "fig")),
Arguments.of("words", List.of("to", "be", "or", "not", "to", "be"), List.of("to", "be", "or", "not")),
Arguments.of("empty", List.of(), List.of()),
Arguments.of("single", List.of("a"), List.of("a")),
Arguments.of("all-same", List.of("x", "x", "x"), List.of("x")),
Arguments.of("no-duplicates", List.of("c", "a", "b"), List.of("c", "a", "b")),
Arguments.of("not-adjacent", List.of("a", "b", "a", "b"), List.of("a", "b")),
Arguments.of("adjacent", List.of("a", "a", "b", "b", "a"), List.of("a", "b")),
Arguments.of("empty-string", List.of("", "a", "", "b"), List.of("", "a", "b")),
Arguments.of("case", List.of("a", "A", "a"), List.of("a", "A")),
Arguments.of("normalization", List.of("\u00e9", "e\u0301", "\u00e9"), List.of("\u00e9", "e\u0301")),
Arguments.of("whitespace", List.of(" a", "a", "a ", " a"), List.of(" a", "a", "a ")),
Arguments.of("number-like", List.of("1", "01", "1.0", "1"), List.of("1", "01", "1.0")),
Arguments.of("non-ascii", List.of("日本", "🙂", "日本", "🙂", "ü"), List.of("日本", "🙂", "ü")));
}
@ParameterizedTest(name = "{0}")
@MethodSource("cases")
void keepsTheFirstCopies(String name, List<String> given, List<String> want) {
List<String> input = new ArrayList<>(given);
assertEquals(want, Unique.unique(input), name);
assertEquals(given, input, "the input must not change");
}
private static List<Unique.User> users(String... nameEmail) {
List<Unique.User> out = new ArrayList<>();
for (int i = 0; i < nameEmail.length; i += 2) {
out.add(new Unique.User(nameEmail[i], nameEmail[i + 1]));
}
return out;
}
/** The cases of cases/by-key.jsonl. Each list is name, email, name, email and so on. */
static Stream<Arguments> byKey() {
return Stream.of(
Arguments.of(
"case-insensitive",
users("Ada", "ada@example.com", "Bob", "bob@example.com", "Ada L.", "ADA@Example.com"),
users("Ada", "ada@example.com", "Bob", "bob@example.com")),
Arguments.of("empty", users(), users()),
Arguments.of(
"same-name-other-email",
users("Sam", "sam@a.example", "Sam", "sam@b.example"),
users("Sam", "sam@a.example", "Sam", "sam@b.example")),
Arguments.of(
"first-record-wins",
users("Old", "x@example.com", "New", "X@EXAMPLE.COM"),
users("Old", "x@example.com")),
Arguments.of(
"dots-differ",
users("Al", "a.b@example.com", "Bo", "ab@example.com"),
users("Al", "a.b@example.com", "Bo", "ab@example.com")),
Arguments.of(
"not-adjacent",
users("A", "a@example.com", "B", "b@example.com", "C", "A@example.com", "D", "B@EXAMPLE.com"),
users("A", "a@example.com", "B", "b@example.com")));
}
@ParameterizedTest(name = "by-key {0}")
@MethodSource("byKey")
void keepsTheFirstUserForEachEmail(String name, List<Unique.User> given, List<Unique.User> want) {
assertEquals(want, Unique.uniqueByEmail(given), name);
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/remove-duplicates-from-a-list/.
#include "unique.h"
#include <string.h>
// This version uses no hash table. It compares each item with the items that
// it kept, so the time grows with n * n.
size_t unique(const char **items, size_t n) {
size_t kept = 0;
for (size_t i = 0; i < n; i++) {
size_t j = 0;
while (j < kept && strcmp(items[j], items[i]) != 0) {
j++;
}
if (j == kept) {
items[kept++] = items[i];
}
}
return kept;
}
// Not tolower or strcasecmp: they use the current locale.
static unsigned char ascii_lower(unsigned char c) {
return c >= 'A' && c <= 'Z' ? (unsigned char)(c - 'A' + 'a') : c;
}
static bool same_email(const char *a, const char *b) {
for (;; a++, b++) {
unsigned char x = ascii_lower((unsigned char)*a);
if (x != ascii_lower((unsigned char)*b)) {
return false;
}
if (x == '\0') {
return true;
}
}
}
size_t unique_by_email(struct user *users, size_t n) {
size_t kept = 0;
for (size_t i = 0; i < n; i++) {
size_t j = 0;
while (j < kept && !same_email(users[j].email, users[i].email)) {
j++;
}
if (j == kept) {
users[kept++] = users[i];
}
}
return kept;
}
unique.h 24 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/remove-duplicates-from-a-list/.
#ifndef UNIQUE_H
#define UNIQUE_H
#include <stddef.h>
struct user {
const char *name;
const char *email; // ASCII
};
// unique removes the later copies of equal strings from items[0..n) in place.
// The first copies keep their order. It returns the new number of items.
// Two strings are equal if they have the same bytes.
size_t unique(const char **items, size_t n);
// unique_by_email keeps the first user for each email in users[0..n), in
// place, and returns the new number of users. Case does not matter in the
// emails.
size_t unique_by_email(struct user *users, size_t n);
#endif
test_unique.c 83 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/remove-duplicates-from-a-list/.
#include "unique.h"
#include <stdio.h>
#include <string.h>
static int failures = 0;
static void report(const char *name, bool ok) {
printf("%s %s\n", ok ? "ok" : "FAIL", name);
if (!ok) {
failures++;
}
}
static void check(const char *name, const char **given, size_t n, const char *const *want, size_t m) {
size_t k = unique(given, n);
bool ok = k == m;
for (size_t i = 0; ok && i < m; i++) {
ok = strcmp(given[i], want[i]) == 0;
}
report(name, ok);
}
static void check_users(const char *name, struct user *given, size_t n, const struct user *want, size_t m) {
size_t k = unique_by_email(given, n);
bool ok = k == m;
for (size_t i = 0; ok && i < m; i++) {
ok = strcmp(given[i].name, want[i].name) == 0 && strcmp(given[i].email, want[i].email) == 0;
}
report(name, ok);
}
#define L(...) {__VA_ARGS__}
#define CHECK(name, given, ...) \
do { \
const char *g[] = given; \
static const char *const w[] = __VA_ARGS__; \
check(name, g, sizeof g / sizeof g[0], w, sizeof w / sizeof w[0]); \
} while (0)
#define CHECK_USERS(name, given, ...) \
do { \
struct user g[] = given; \
static const struct user w[] = __VA_ARGS__; \
check_users(name, g, sizeof g / sizeof g[0], w, sizeof w / sizeof w[0]); \
} while (0)
int main(void) {
CHECK("repeats", L("apple", "pear", "apple", "fig", "pear"), {"apple", "pear", "fig"});
CHECK("words", L("to", "be", "or", "not", "to", "be"), {"to", "be", "or", "not"});
report("empty", unique(NULL, 0) == 0);
CHECK("single", L("a"), {"a"});
CHECK("all-same", L("x", "x", "x"), {"x"});
CHECK("no-duplicates", L("c", "a", "b"), {"c", "a", "b"});
CHECK("not-adjacent", L("a", "b", "a", "b"), {"a", "b"});
CHECK("adjacent", L("a", "a", "b", "b", "a"), {"a", "b"});
CHECK("empty-string", L("", "a", "", "b"), {"", "a", "b"});
CHECK("case", L("a", "A", "a"), {"a", "A"});
CHECK("normalization", L("\u00e9", "e\u0301", "\u00e9"), {"\u00e9", "e\u0301"});
CHECK("whitespace", L(" a", "a", "a ", " a"), {" a", "a", "a "});
CHECK("number-like", L("1", "01", "1.0", "1"), {"1", "01", "1.0"});
CHECK("non-ascii", L("日本", "🙂", "日本", "🙂", "ü"), {"日本", "🙂", "ü"});
// The cases of cases/by-key.jsonl.
CHECK_USERS("by-key case-insensitive",
L({"Ada", "ada@example.com"}, {"Bob", "bob@example.com"}, {"Ada L.", "ADA@Example.com"}),
{{"Ada", "ada@example.com"}, {"Bob", "bob@example.com"}});
report("by-key empty", unique_by_email(NULL, 0) == 0);
CHECK_USERS("by-key same-name-other-email", L({"Sam", "sam@a.example"}, {"Sam", "sam@b.example"}),
{{"Sam", "sam@a.example"}, {"Sam", "sam@b.example"}});
CHECK_USERS("by-key first-record-wins", L({"Old", "x@example.com"}, {"New", "X@EXAMPLE.COM"}),
{{"Old", "x@example.com"}});
CHECK_USERS("by-key dots-differ", L({"Al", "a.b@example.com"}, {"Bo", "ab@example.com"}),
{{"Al", "a.b@example.com"}, {"Bo", "ab@example.com"}});
CHECK_USERS("by-key not-adjacent",
L({"A", "a@example.com"}, {"B", "b@example.com"}, {"C", "A@example.com"}, {"D", "B@EXAMPLE.com"}),
{{"A", "a@example.com"}, {"B", "b@example.com"}});
return failures == 0 ? 0 : 1;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/remove-duplicates-from-a-list/.
/// <summary>A record of a user. A record gets Equals and GetHashCode from its members.</summary>
public sealed record User(string Name, string Email);
public static class Dedupe
{
/// <summary>Returns a new list of the items without later copies. The first copies keep their order.</summary>
public static List<T> Unique<T>(IEnumerable<T> items) => UniqueBy(items, x => x);
/// <summary>Returns a new list of the first item for each key, in input order.</summary>
public static List<T> UniqueBy<T, TKey>(IEnumerable<T> items, Func<T, TKey> key)
{
// Not Distinct or DistinctBy: their documentation calls the result unordered.
var seen = new HashSet<TKey>();
var result = new List<T>();
foreach (var item in items)
{
// Add returns false if the set already has the key.
if (seen.Add(key(item)))
{
result.Add(item);
}
}
return result;
}
/// <summary>Returns the first user for each email. Case does not matter in the emails.</summary>
public static List<User> UniqueByEmail(IEnumerable<User> users) =>
// ToLowerInvariant does not use the rules of the current culture.
UniqueBy(users, u => u.Email.ToLowerInvariant());
}
UniqueTests.cs 65 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/remove-duplicates-from-a-list/.
using Xunit;
public sealed class UniqueTests
{
public static TheoryData<string, string[], string[]> Cases => new()
{
{ "repeats", ["apple", "pear", "apple", "fig", "pear"], ["apple", "pear", "fig"] },
{ "words", ["to", "be", "or", "not", "to", "be"], ["to", "be", "or", "not"] },
{ "empty", [], [] },
{ "single", ["a"], ["a"] },
{ "all-same", ["x", "x", "x"], ["x"] },
{ "no-duplicates", ["c", "a", "b"], ["c", "a", "b"] },
{ "not-adjacent", ["a", "b", "a", "b"], ["a", "b"] },
{ "adjacent", ["a", "a", "b", "b", "a"], ["a", "b"] },
{ "empty-string", ["", "a", "", "b"], ["", "a", "b"] },
{ "case", ["a", "A", "a"], ["a", "A"] },
{ "normalization", ["\u00e9", "e\u0301", "\u00e9"], ["\u00e9", "e\u0301"] },
{ "whitespace", [" a", "a", "a ", " a"], [" a", "a", "a "] },
{ "number-like", ["1", "01", "1.0", "1"], ["1", "01", "1.0"] },
{ "non-ascii", ["日本", "🙂", "日本", "🙂", "ü"], ["日本", "🙂", "ü"] },
};
[Theory]
[MemberData(nameof(Cases))]
public void KeepsTheFirstCopies(string name, string[] given, string[] want)
{
string[] input = [.. given];
Assert.True(want.SequenceEqual(Dedupe.Unique(input)), name);
Assert.Equal(given, input);
}
private static User[] U(params (string Name, string Email)[] rows) =>
rows.Select(r => new User(r.Name, r.Email)).ToArray();
// The cases of cases/by-key.jsonl.
public static TheoryData<string, User[], User[]> ByKey => new()
{
{ "case-insensitive",
U(("Ada", "ada@example.com"), ("Bob", "bob@example.com"), ("Ada L.", "ADA@Example.com")),
U(("Ada", "ada@example.com"), ("Bob", "bob@example.com")) },
{ "empty", U(), U() },
{ "same-name-other-email",
U(("Sam", "sam@a.example"), ("Sam", "sam@b.example")),
U(("Sam", "sam@a.example"), ("Sam", "sam@b.example")) },
{ "first-record-wins",
U(("Old", "x@example.com"), ("New", "X@EXAMPLE.COM")),
U(("Old", "x@example.com")) },
{ "dots-differ",
U(("Al", "a.b@example.com"), ("Bo", "ab@example.com")),
U(("Al", "a.b@example.com"), ("Bo", "ab@example.com")) },
{ "not-adjacent",
U(("A", "a@example.com"), ("B", "b@example.com"), ("C", "A@example.com"), ("D", "B@EXAMPLE.com")),
U(("A", "a@example.com"), ("B", "b@example.com")) },
};
[Theory]
[MemberData(nameof(ByKey))]
public void KeepsTheFirstUserForEachEmail(string name, User[] given, User[] want)
{
Assert.True(want.SequenceEqual(Dedupe.UniqueByEmail(given)), name);
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/remove-duplicates-from-a-list/.
/** @typedef {{ name: string, email: string }} User */
/**
* Returns a new array of the items without later copies. The first copies keep their order.
* @template T
* @param {Iterable<T>} items
* @returns {T[]}
*/
export function unique(items) {
// A Set visits its values in insertion order. It compares them with SameValueZero.
return [...new Set(items)];
}
/**
* Returns a new array of the first item for each key, in input order.
* @template T, K
* @param {Iterable<T>} items
* @param {(item: T) => K} key
* @returns {T[]}
*/
export function uniqueBy(items, key) {
const seen = new Set();
const out = [];
for (const item of items) {
const k = key(item);
if (!seen.has(k)) {
seen.add(k);
out.push(item);
}
}
return out;
}
/**
* Returns the first user for each email. Case does not matter in the emails.
* @param {Iterable<User>} users
* @returns {User[]}
*/
export function uniqueByEmail(users) {
return uniqueBy(users, (u) => u.email.toLowerCase());
}
unique.test.js 63 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/remove-duplicates-from-a-list/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { unique, uniqueByEmail } from "./unique.js";
const cases = {
repeats: [["apple", "pear", "apple", "fig", "pear"], ["apple", "pear", "fig"]],
words: [["to", "be", "or", "not", "to", "be"], ["to", "be", "or", "not"]],
empty: [[], []],
single: [["a"], ["a"]],
"all-same": [["x", "x", "x"], ["x"]],
"no-duplicates": [["c", "a", "b"], ["c", "a", "b"]],
"not-adjacent": [["a", "b", "a", "b"], ["a", "b"]],
adjacent: [["a", "a", "b", "b", "a"], ["a", "b"]],
"empty-string": [["", "a", "", "b"], ["", "a", "b"]],
case: [["a", "A", "a"], ["a", "A"]],
normalization: [["\u00e9", "e\u0301", "\u00e9"], ["\u00e9", "e\u0301"]],
whitespace: [[" a", "a", "a ", " a"], [" a", "a", "a "]],
"number-like": [["1", "01", "1.0", "1"], ["1", "01", "1.0"]],
"non-ascii": [["日本", "🙂", "日本", "🙂", "ü"], ["日本", "🙂", "ü"]],
};
for (const [name, [given, want]] of Object.entries(cases)) {
test(name, () => {
const input = [...given];
assert.deepEqual(unique(input), want);
assert.deepEqual(input, given, "the input must not change");
});
}
/** Makes users from [name, email] rows. */
const users = (rows) => rows.map(([name, email]) => ({ name, email }));
// The cases of cases/by-key.jsonl.
const byKey = {
"case-insensitive": [
[["Ada", "ada@example.com"], ["Bob", "bob@example.com"], ["Ada L.", "ADA@Example.com"]],
[["Ada", "ada@example.com"], ["Bob", "bob@example.com"]],
],
empty: [[], []],
"same-name-other-email": [
[["Sam", "sam@a.example"], ["Sam", "sam@b.example"]],
[["Sam", "sam@a.example"], ["Sam", "sam@b.example"]],
],
"first-record-wins": [[["Old", "x@example.com"], ["New", "X@EXAMPLE.COM"]], [["Old", "x@example.com"]]],
"dots-differ": [
[["Al", "a.b@example.com"], ["Bo", "ab@example.com"]],
[["Al", "a.b@example.com"], ["Bo", "ab@example.com"]],
],
"not-adjacent": [
[["A", "a@example.com"], ["B", "b@example.com"], ["C", "A@example.com"], ["D", "B@EXAMPLE.com"]],
[["A", "a@example.com"], ["B", "b@example.com"]],
],
};
for (const [name, [given, want]] of Object.entries(byKey)) {
test(`by-key ${name}`, () => {
assert.deepEqual(uniqueByEmail(users(given)), users(want));
});
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/remove-duplicates-from-a-list/.
export interface User {
readonly name: string;
readonly email: string;
}
/** Returns a new array of the items without later copies. The first copies keep their order. */
export function unique<T>(items: Iterable<T>): T[] {
// A Set visits its values in insertion order. It compares them with SameValueZero.
return [...new Set(items)];
}
/** Returns a new array of the first item for each key, in input order. */
export function uniqueBy<T, K>(items: Iterable<T>, key: (item: T) => K): T[] {
const seen = new Set<K>();
const out: T[] = [];
for (const item of items) {
const k = key(item);
if (!seen.has(k)) {
seen.add(k);
out.push(item);
}
}
return out;
}
/** Returns the first user for each email. Case does not matter in the emails. */
export function uniqueByEmail(users: Iterable<User>): User[] {
return uniqueBy(users, (u) => u.email.toLowerCase());
}
unique.test.ts 65 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/remove-duplicates-from-a-list/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { type User, unique, uniqueByEmail } from "./unique.ts";
const cases: Record<string, [string[], string[]]> = {
repeats: [["apple", "pear", "apple", "fig", "pear"], ["apple", "pear", "fig"]],
words: [["to", "be", "or", "not", "to", "be"], ["to", "be", "or", "not"]],
empty: [[], []],
single: [["a"], ["a"]],
"all-same": [["x", "x", "x"], ["x"]],
"no-duplicates": [["c", "a", "b"], ["c", "a", "b"]],
"not-adjacent": [["a", "b", "a", "b"], ["a", "b"]],
adjacent: [["a", "a", "b", "b", "a"], ["a", "b"]],
"empty-string": [["", "a", "", "b"], ["", "a", "b"]],
case: [["a", "A", "a"], ["a", "A"]],
normalization: [["\u00e9", "e\u0301", "\u00e9"], ["\u00e9", "e\u0301"]],
whitespace: [[" a", "a", "a ", " a"], [" a", "a", "a "]],
"number-like": [["1", "01", "1.0", "1"], ["1", "01", "1.0"]],
"non-ascii": [["日本", "🙂", "日本", "🙂", "ü"], ["日本", "🙂", "ü"]],
};
for (const [name, [given, want]] of Object.entries(cases)) {
test(name, () => {
const input = [...given];
assert.deepEqual(unique(input), want);
assert.deepEqual(input, given, "the input must not change");
});
}
type Row = [string, string];
/** Makes users from [name, email] rows. */
const users = (rows: readonly Row[]): User[] => rows.map(([name, email]) => ({ name, email }));
// The cases of cases/by-key.jsonl.
const byKey: Record<string, [Row[], Row[]]> = {
"case-insensitive": [
[["Ada", "ada@example.com"], ["Bob", "bob@example.com"], ["Ada L.", "ADA@Example.com"]],
[["Ada", "ada@example.com"], ["Bob", "bob@example.com"]],
],
empty: [[], []],
"same-name-other-email": [
[["Sam", "sam@a.example"], ["Sam", "sam@b.example"]],
[["Sam", "sam@a.example"], ["Sam", "sam@b.example"]],
],
"first-record-wins": [[["Old", "x@example.com"], ["New", "X@EXAMPLE.COM"]], [["Old", "x@example.com"]]],
"dots-differ": [
[["Al", "a.b@example.com"], ["Bo", "ab@example.com"]],
[["Al", "a.b@example.com"], ["Bo", "ab@example.com"]],
],
"not-adjacent": [
[["A", "a@example.com"], ["B", "b@example.com"], ["C", "A@example.com"], ["D", "B@EXAMPLE.com"]],
[["A", "a@example.com"], ["B", "b@example.com"]],
],
};
for (const [name, [given, want]] of Object.entries(byKey)) {
test(`by-key ${name}`, () => {
assert.deepEqual(uniqueByEmail(users(given)), users(want));
});
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/remove-duplicates-from-a-list/.
// Package dedupe removes duplicates from slices and keeps the input order.
package dedupe
import "strings"
// User is a record of a user.
type User struct {
Name string
Email string
}
// Unique returns a new slice of the items without later copies.
// The first copies keep their order.
func Unique[T comparable](items []T) []T {
return UniqueBy(items, func(x T) T { return x })
}
// UniqueBy returns a new slice of the first item for each key, in input order.
func UniqueBy[T any, K comparable](items []T, key func(T) K) []T {
// The map only records the keys that we saw. The order comes from the
// slice, because the iteration order of a map is not specified.
seen := make(map[K]struct{}, len(items))
out := make([]T, 0, len(items))
for _, item := range items {
k := key(item)
if _, ok := seen[k]; ok {
continue
}
seen[k] = struct{}{}
out = append(out, item)
}
return out
}
// UniqueByEmail returns the first user for each email.
// Case does not matter in the emails, which are ASCII.
func UniqueByEmail(users []User) []User {
return UniqueBy(users, func(u User) string { return strings.ToLower(u.Email) })
}
dedupe_test.go 78 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/remove-duplicates-from-a-list/.
package dedupe
import (
"slices"
"testing"
)
type s = []string
func TestUnique(t *testing.T) {
cases := []struct {
name string
given, want []string
}{
{"repeats", s{"apple", "pear", "apple", "fig", "pear"}, s{"apple", "pear", "fig"}},
{"words", s{"to", "be", "or", "not", "to", "be"}, s{"to", "be", "or", "not"}},
{"empty", s{}, s{}},
{"single", s{"a"}, s{"a"}},
{"all-same", s{"x", "x", "x"}, s{"x"}},
{"no-duplicates", s{"c", "a", "b"}, s{"c", "a", "b"}},
{"not-adjacent", s{"a", "b", "a", "b"}, s{"a", "b"}},
{"adjacent", s{"a", "a", "b", "b", "a"}, s{"a", "b"}},
{"empty-string", s{"", "a", "", "b"}, s{"", "a", "b"}},
{"case", s{"a", "A", "a"}, s{"a", "A"}},
{"normalization", s{"\u00e9", "e\u0301", "\u00e9"}, s{"\u00e9", "e\u0301"}},
{"whitespace", s{" a", "a", "a ", " a"}, s{" a", "a", "a "}},
{"number-like", s{"1", "01", "1.0", "1"}, s{"1", "01", "1.0"}},
{"non-ascii", s{"日本", "🙂", "日本", "🙂", "ü"}, s{"日本", "🙂", "ü"}},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
input := slices.Clone(c.given)
if got := Unique(input); !slices.Equal(got, c.want) {
t.Errorf("got %q, want %q", got, c.want)
}
if !slices.Equal(input, c.given) {
t.Errorf("the input changed to %q", input)
}
})
}
}
type u = []User
// The cases of cases/by-key.jsonl.
func TestUniqueByEmail(t *testing.T) {
cases := []struct {
name string
given, want []User
}{
{"case-insensitive",
u{{"Ada", "ada@example.com"}, {"Bob", "bob@example.com"}, {"Ada L.", "ADA@Example.com"}},
u{{"Ada", "ada@example.com"}, {"Bob", "bob@example.com"}}},
{"empty", u{}, u{}},
{"same-name-other-email",
u{{"Sam", "sam@a.example"}, {"Sam", "sam@b.example"}},
u{{"Sam", "sam@a.example"}, {"Sam", "sam@b.example"}}},
{"first-record-wins",
u{{"Old", "x@example.com"}, {"New", "X@EXAMPLE.COM"}},
u{{"Old", "x@example.com"}}},
{"dots-differ",
u{{"Al", "a.b@example.com"}, {"Bo", "ab@example.com"}},
u{{"Al", "a.b@example.com"}, {"Bo", "ab@example.com"}}},
{"not-adjacent",
u{{"A", "a@example.com"}, {"B", "b@example.com"}, {"C", "A@example.com"}, {"D", "B@EXAMPLE.com"}},
u{{"A", "a@example.com"}, {"B", "b@example.com"}}},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
if got := UniqueByEmail(c.given); !slices.Equal(got, c.want) {
t.Errorf("got %v, want %v", got, c.want)
}
})
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/remove-duplicates-from-a-list/.
//! Removes duplicates from lists and keeps the input order.
use std::collections::HashSet;
use std::hash::Hash;
/// A record of a user.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct User {
pub name: String,
pub email: String,
}
/// Returns the items without later copies. The first copies keep their order.
pub fn unique<T: Eq + Hash + Clone>(items: &[T]) -> Vec<T> {
// The set holds references to the items, so it copies no item.
let mut seen = HashSet::with_capacity(items.len());
// insert returns true only if the set did not have the value.
items.iter().filter(|&x| seen.insert(x)).cloned().collect()
}
/// Returns the first item for each key, in input order.
pub fn unique_by<T: Clone, K: Eq + Hash>(items: &[T], mut key: impl FnMut(&T) -> K) -> Vec<T> {
let mut seen = HashSet::with_capacity(items.len());
items
.iter()
.filter(|&x| seen.insert(key(x)))
.cloned()
.collect()
}
/// Returns the first user for each email. Case does not matter in the emails.
pub fn unique_by_email(users: &[User]) -> Vec<User> {
unique_by(users, |u| u.email.to_ascii_lowercase())
}
tests/unique_test.rs 100 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/remove-duplicates-from-a-list/.
use algo_remove_duplicates_from_a_list::{User, unique, unique_by_email};
#[test]
fn cases() {
let cases: &[(&str, &[&str], &[&str])] = &[
(
"repeats",
&["apple", "pear", "apple", "fig", "pear"],
&["apple", "pear", "fig"],
),
(
"words",
&["to", "be", "or", "not", "to", "be"],
&["to", "be", "or", "not"],
),
("empty", &[], &[]),
("single", &["a"], &["a"]),
("all-same", &["x", "x", "x"], &["x"]),
("no-duplicates", &["c", "a", "b"], &["c", "a", "b"]),
("not-adjacent", &["a", "b", "a", "b"], &["a", "b"]),
("adjacent", &["a", "a", "b", "b", "a"], &["a", "b"]),
("empty-string", &["", "a", "", "b"], &["", "a", "b"]),
("case", &["a", "A", "a"], &["a", "A"]),
(
"normalization",
&["\u{e9}", "e\u{301}", "\u{e9}"],
&["\u{e9}", "e\u{301}"],
),
("whitespace", &[" a", "a", "a ", " a"], &[" a", "a", "a "]),
("number-like", &["1", "01", "1.0", "1"], &["1", "01", "1.0"]),
(
"non-ascii",
&["日本", "🙂", "日本", "🙂", "ü"],
&["日本", "🙂", "ü"],
),
];
for &(name, given, want) in cases {
let given: Vec<String> = given.iter().map(|s| s.to_string()).collect();
assert_eq!(unique(&given), want, "case {name}");
}
}
type Row = (&'static str, &'static str);
fn users(rows: &[Row]) -> Vec<User> {
rows.iter()
.map(|&(name, email)| User {
name: name.to_string(),
email: email.to_string(),
})
.collect()
}
/// The cases of cases/by-key.jsonl.
#[test]
fn by_key() {
let cases: &[(&str, &[Row], &[Row])] = &[
(
"case-insensitive",
&[
("Ada", "ada@example.com"),
("Bob", "bob@example.com"),
("Ada L.", "ADA@Example.com"),
],
&[("Ada", "ada@example.com"), ("Bob", "bob@example.com")],
),
("empty", &[], &[]),
(
"same-name-other-email",
&[("Sam", "sam@a.example"), ("Sam", "sam@b.example")],
&[("Sam", "sam@a.example"), ("Sam", "sam@b.example")],
),
(
"first-record-wins",
&[("Old", "x@example.com"), ("New", "X@EXAMPLE.COM")],
&[("Old", "x@example.com")],
),
(
"dots-differ",
&[("Al", "a.b@example.com"), ("Bo", "ab@example.com")],
&[("Al", "a.b@example.com"), ("Bo", "ab@example.com")],
),
(
"not-adjacent",
&[
("A", "a@example.com"),
("B", "b@example.com"),
("C", "A@example.com"),
("D", "B@EXAMPLE.com"),
],
&[("A", "a@example.com"), ("B", "b@example.com")],
),
];
for &(name, given, want) in cases {
assert_eq!(unique_by_email(&users(given)), users(want), "case {name}");
}
}
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/remove-duplicates-from-a-list/.
# unique
# Reads items from stdin, one per line. Prints each item the first time it
# comes, so the first copies keep their order. No item can hold a newline.
unique() {
# seen[$0] is 0 the first time, so !seen[$0]++ is true only then.
# A pattern with no action prints the line.
awk '!seen[$0]++'
}
# unique_by_email
# Reads users from stdin, one per line: NAME and EMAIL with a tab between them.
# Prints the first user for each email. Case does not matter in the emails.
unique_by_email() {
# LC_ALL=C: tolower changes only A to Z, on every machine.
LC_ALL=C awk -F '\t' '!seen[tolower($2)]++'
}
test_unique.bats 64 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/remove-duplicates-from-a-list/.
bats_require_minimum_version 1.5.0
setup() {
source "$BATS_TEST_DIRNAME/unique.sh"
}
lines() { # lines ITEM...: prints each item on a line, and nothing for no items
if (($# > 0)); then printf '%s\n' "$@"; fi
}
check() { # check FUNCTION GIVEN... -- WANT...
local fn=$1 got want
shift
local -a given=()
while [ "$1" != -- ]; do given+=("$1"); shift; done
shift
# The x keeps the trailing newlines, which $(...) removes.
got=$(lines "${given[@]}" | "$fn"; printf x)
want=$(lines "$@"; printf x)
[ "$got" = "$want" ] || { printf 'got: %q\nwant: %q\n' "$got" "$want"; return 1; }
}
E=$(printf '\303\251') # U+00E9, one code point
D=$(printf 'e\314\201') # e and U+0301, two code points
TAB=$(printf '\t')
@test "repeats" { check unique apple pear apple fig pear -- apple pear fig; }
@test "words" { check unique to be or not to be -- to be or not; }
@test "empty" { check unique --; }
@test "single" { check unique a -- a; }
@test "all-same" { check unique x x x -- x; }
@test "no-duplicates" { check unique c a b -- c a b; }
@test "not-adjacent" { check unique a b a b -- a b; }
@test "adjacent" { check unique a a b b a -- a b; }
@test "empty-string" { check unique "" a "" b -- "" a b; }
@test "case" { check unique a A a -- a A; }
@test "normalization" { check unique "$E" "$D" "$E" -- "$E" "$D"; }
@test "whitespace" { check unique " a" a "a " " a" -- " a" a "a "; }
@test "number-like" { check unique 1 01 1.0 1 -- 1 01 1.0; }
@test "non-ascii" { check unique 日本 🙂 日本 🙂 ü -- 日本 🙂 ü; }
# The cases of cases/by-key.jsonl. Each user is NAME, a tab and EMAIL.
@test "by-key case-insensitive" {
check unique_by_email "Ada${TAB}ada@example.com" "Bob${TAB}bob@example.com" "Ada L.${TAB}ADA@Example.com" -- \
"Ada${TAB}ada@example.com" "Bob${TAB}bob@example.com"
}
@test "by-key empty" { check unique_by_email --; }
@test "by-key same-name-other-email" {
check unique_by_email "Sam${TAB}sam@a.example" "Sam${TAB}sam@b.example" -- "Sam${TAB}sam@a.example" "Sam${TAB}sam@b.example"
}
@test "by-key first-record-wins" {
check unique_by_email "Old${TAB}x@example.com" "New${TAB}X@EXAMPLE.COM" -- "Old${TAB}x@example.com"
}
@test "by-key dots-differ" {
check unique_by_email "Al${TAB}a.b@example.com" "Bo${TAB}ab@example.com" -- "Al${TAB}a.b@example.com" "Bo${TAB}ab@example.com"
}
@test "by-key not-adjacent" {
check unique_by_email "A${TAB}a@example.com" "B${TAB}b@example.com" "C${TAB}A@example.com" "D${TAB}B@EXAMPLE.com" -- \
"A${TAB}a@example.com" "B${TAB}b@example.com"
}
References
- The Python Standard Library, Built-in Types, Mapping types, dict (fromkeys; dictionaries preserve insertion order)
- The Python Standard Library, Built-in Types, Set Types, set, frozenset
- The Python Language Reference, Expressions, 6.10.1 Value comparisons (not-a-number values; built-in containers and identical objects)
- The Python documentation, Command line and environment, PYTHONHASHSEED
- MDN Web Docs, Set, Description (Value equality); Iterating sets
- MDN Web Docs, Array.prototype.indexOf(), Description
- Java SE 25 API, java.util.stream.Stream, distinct()
- Java SE 25 API, java.util.HashSet, class description (iteration order); add(E)
- Java SE 25 API, java.lang.Object, equals(Object), hashCode()
- Java SE 25 API, java.lang.Record, equals(Object), hashCode()
- Java SE 25 API, java.lang.String, toLowerCase(Locale), toLowerCase()
- .NET API reference, Enumerable.Distinct, Remarks
- .NET API reference, Enumerable.DistinctBy, Remarks
- .NET API reference, HashSet<T>.Add, Returns
- .NET API reference, String.ToLowerInvariant, Remarks
- The Go Programming Language Specification, For statements with range clause; Map types
- Go standard library, package slices, Compact, CompactFunc
- The Rust Standard Library, struct HashSet, insert; the type documentation (Eq and Hash)
- The Rust Standard Library, primitive type str, to_ascii_lowercase
- cppreference.com, std::unordered_set::insert, Return value
- cppreference.com, std::tolower, Description; Notes
- The Open Group, POSIX.1-2024, strcmp, Description
- The Open Group, POSIX.1-2024, strcasecmp, Description
- The Open Group, POSIX.1-2024, awk, Variables and Special Variables; Overall Program Structure; String Functions (tolower)
- The Open Group, POSIX.1-2024, uniq, Description; Application Usage
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Code (bash) | I0 not checked yet |
|
| Code (c) | I0 not checked yet |
|
| Code (cpp) | I0 not checked yet |
|
| Code (csharp) | I0 not checked yet |
|
| Code (go) | I0 not checked yet |
|
| Code (java) | I0 not checked yet |
|
| Code (javascript) | I0 not checked yet |
|
| Code (python) | I0 not checked yet |
|
| Code (rust) | I0 not checked yet |
|
| Code (typescript) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W3 standard |
|
The native tests pass in 9 of 10 languages in this build.
Tag 9RGPB9 Edit this page History Report an error Markdown