Skip to content

armgit / zulip

Public Imported from GitHub
0

Zulip server and web application. Open-source team chat that helps teams stay productive and focused.

util: Add unique_array_insert.

Evy Kassirer5965ca682126
diff --git a/web/src/util.ts b/web/src/util.ts
index 6258e1c0ccc..8a3f337673b 100644
--- a/web/src/util.ts
+++ b/web/src/util.ts
@@ -629,3 +629,14 @@ export async function sha256_hash(text: string): Promise<string | undefined> {
const hashHex = hashArray.map((byte) => byte.toString(16).padStart(2, "0")).join("");
return hashHex;
}
+
+// This should only be used in loops with small collections, since it
+// runs in linear time.
+export function unique_array_insert<T>(array: T[], new_item: T): void {
+ for (const item of array) {
+ if (_.isEqual(item, new_item)) {
+ return;
+ }
+ }
+ array.push(new_item);
+}
diff --git a/web/tests/util.test.cjs b/web/tests/util.test.cjs
index 11e39f1b375..8c7c11ae6b2 100644
--- a/web/tests/util.test.cjs
+++ b/web/tests/util.test.cjs
@@ -605,3 +605,18 @@ run_test("sha256_hash", async ({override}) => {
hash = await util.sha256_hash(data);
assert.equal(hash, expected_hash);
});
+
+run_test("unique_array_insert", () => {
+ const array = [{a: "foo", b: "bar"}];
+ util.unique_array_insert(array, {c: "beep", d: "boop"});
+ assert.deepEqual(array, [
+ {a: "foo", b: "bar"},
+ {c: "beep", d: "boop"},
+ ]);
+ util.unique_array_insert(array, {c: "beep", d: "boop"});
+ util.unique_array_insert(array, {a: "foo", b: "bar"});
+ assert.deepEqual(array, [
+ {a: "foo", b: "bar"},
+ {c: "beep", d: "boop"},
+ ]);
+});