owltide/shared/utils/functions.ts
Hornwitser fe06d0d6bd
All checks were successful
/ build (push) Successful in 2m5s
/ deploy (push) Successful in 16s
Refactor API types and sync logic
Rename and refactor the types passed over the API to be based on an
entity that's either living or a tombstone.  A living entity has a
deleted property that's either undefined or false, while a tombstone
has a deleted property set to true.  All entities have a numeric id
and an updatedAt timestamp.

To sync entities, an array of replacements are passed around. Living
entities are replaced with tombstones when they're deleted. And
tombstones are replaced with living entities when restored.
2025-06-11 21:05:17 +02:00

57 lines
1.4 KiB
TypeScript

/** Returns a tuple consisting of a running index starting from 0, and the item of the iterable */
export function* enumerate<T>(iterable: Iterable<T>) {
let index = 0;
for (const item of iterable) {
yield [index++, item] as [number, T];
}
}
/** Filters an iterable based on the passed predicate function */
export function* filter<T, S extends T>(it: Iterable<T>, predicate: (value: T) => value is S) {
for (const value of it) {
if (predicate(value)) {
yield value;
}
}
}
/** Converts a name to an id */
export function toId(name: string) {
return name.toLowerCase().replace(/[^a-z0-9]+/g, "-");
}
/** Returns adjacent pairs from iterable */
export function* pairs<T>(iterable: Iterable<T>) {
let first;
let second;
for (const [index, item] of enumerate(iterable)) {
[first, second] = [second, item];
if (index >= 1) {
yield [first, second] as [T, T];
}
}
}
/**
Returns true if all sets are equal
@param sets set to compare
@returns true if all sets are the same size and have the same elements
*/
export function setEquals<T>(...sets: Set<T>[]) {
if (sets.length < 2) {
throw TypeError("At least two sets must be passed to setEquals");
}
const ref = sets[0];
const rest = sets.slice(1);
if (rest.some(set => set.size !== ref.size)) {
return false;
}
for (const set of rest) {
for (const el of set) {
if (!ref.has(el)) {
return false;
}
}
}
return true;
}