Skip to content

unorderedPairKey

Builds a canonical, order-independent key for an unordered pair of strings — the same result for (a, b) and (b, a). Useful for deduplicating unordered relationships (edges, matched pairs, …) using a Set/Map keyed by string.

Available since v3.1.1

import { unorderedPairKey } from '@helpers4/string';
// or, from the all-in-one package (same code, one install):
import { unorderedPairKey } from 'helpers4/string';
unorderedPairKey(a: string, b: string, separator: string): string
ParameterTypeDescription
astringThe first string
bstringThe second string
separatorstringJoins the two strings in the key. Defaults to `’|’` — pick a separator that cannot appear inside `a`/`b` themselves, or two distinct pairs could collide on the same key.

string — a and b joined by separator, in whichever of the two lexicographic orders sorts first

Deduplicate unordered relationships in a Set

Section titled “Deduplicate unordered relationships in a Set”

The same key is produced regardless of which side is passed first.

const seen = new Set<string>();
seen.add(unorderedPairKey('alice', 'bob'));
seen.has(unorderedPairKey('bob', 'alice'))
// => true

Pick a separator that cannot appear inside the inputs to avoid collisions.

unorderedPairKey('bob', 'alice', ':')
// => 'alice:bob'

View source on GitHub