small array utilities
0

Configure Feed

Select the types of activity you want to include in your feed.

feat: differenceBy function

+24
+24
lib/mod.ts
··· 88 88 }; 89 89 90 90 /** 91 + * returns elements present in the first array but not in the second, based on a selector 92 + * @param a the source array 93 + * @param b the array to compare against 94 + * @param selector function to derive comparison keys 95 + * @returns an array of elements in a not present in b based on the selector 96 + */ 97 + /*#__NO_SIDE_EFFECTS__*/ 98 + export const differenceBy = <T, K>(a: T[], b: T[], selector: (value: T) => K): T[] => { 99 + const bSet = new Set(b.map(selector)); 100 + const aSet = new Set<K>(); 101 + 102 + return a.filter((value) => { 103 + const key = selector(value); 104 + 105 + if (!bSet.has(key) && !aSet.has(key)) { 106 + aSet.add(key); 107 + return true; 108 + } 109 + 110 + return false; 111 + }); 112 + }; 113 + 114 + /** 91 115 * returns elements common to both arrays 92 116 * @param a the first array 93 117 * @param b the second array