javascript
47 lines · 8 steps
Diffing sets to sync group membership
Compute the minimal add/remove delta between two id lists, then apply only the changes inside a transaction.
Explained by
highlit
1export function diffIds(current, desired) {
2 const currentSet = new Set(current);
3 const desiredSet = new Set(desired);
4
5 const toAdd = [];
6 const toRemove = [];
7
8 for (const id of desiredSet) {
9 if (!currentSet.has(id)) toAdd.push(id);
10 }
11
12 for (const id of currentSet) {
13 if (!desiredSet.has(id)) toRemove.push(id);
14 }
15
16 const unchanged = current.filter((id) => desiredSet.has(id));
17
18 return {
19 toAdd,
20 toRemove,
21 unchanged,
22 hasChanges: toAdd.length > 0 || toRemove.length > 0,
23 };
24}
25
26export async function syncMembership(groupId, desiredUserIds) {
27 const existing = await db.groupMembers.findAll({ where: { groupId } });
28 const { toAdd, toRemove, hasChanges } = diffIds(
29 existing.map((m) => m.userId),
30 desiredUserIds,
31 );
32
33 if (!hasChanges) return { changed: false };
34
35 await db.transaction(async (tx) => {
36 if (toRemove.length) {
37 await tx.groupMembers.destroy({ where: { groupId, userId: toRemove } });
38 }
39 if (toAdd.length) {
40 await tx.groupMembers.bulkCreate(
41 toAdd.map((userId) => ({ groupId, userId })),
42 );
43 }
44 });
45
46 return { changed: true, added: toAdd, removed: toRemove };
47}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Wrapping id lists in Sets turns membership checks into O(1) lookups, keeping the diff linear.
- 2Computing a delta first lets you skip work entirely when nothing has changed.
- 3Applying removes and adds inside one transaction keeps the final state atomic and consistent.
Related explainers
php
<?php namespace App\Services\Checkout;
Validating coupons with Laravel's Pipeline
pipeline
chain of responsibility
transactions
Intermediate
7 steps
javascript
function evaluate(expression) { const tokens = tokenize(expression); let pos = 0;
Building a recursive descent calculator
parsing
recursion
operator-precedence
Intermediate
8 steps
javascript
import { useState, useEffect, useCallback, useRef } from 'react'; const cache = new Map(); const inflight = new Map();
Building a stale-while-revalidate hook in React
caching
request-deduplication
custom-hooks
Advanced
10 steps
javascript
import { useEffect, useRef, useState } from 'react'; export function useDelayedFlag(active, delay = 300) { const [visible, setVisible] = useState(false);
Delaying a loading spinner with a React hook
custom-hooks
debouncing
cleanup
Intermediate
8 steps
javascript
const SWIPE_THRESHOLD = 80; const MAX_TRANSLATE = 120; export function attachSwipeToDismiss(element, onDismiss) {
Building a swipe-to-dismiss gesture in JS
touch-events
gesture-detection
dom-manipulation
Intermediate
10 steps
javascript
const { pool } = require('./db'); function withTransaction() { return async (req, res, next) => {
A per-request transaction middleware in Express
middleware
database-transactions
connection-pooling
Advanced
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/diffing-sets-to-sync-group-membership-explained-javascript-3041/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.