small array utilities
0

Configure Feed

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

feat: cluster function

+34
+34
lib/mod.ts
··· 78 78 }; 79 79 80 80 /** 81 + * groups subsequent elements from an array based on a predicate 82 + * @param array array to cluster 83 + * @param predicate function to test consecutive elements with 84 + * @returns an array of clusters, where each cluster is an array of consecutive elements that satisfy the predicate 85 + */ 86 + /*#__NO_SIDE_EFFECTS__*/ 87 + export const cluster = <T>(array: T[], predicate: (a: T, b: T) => unknown): T[][] => { 88 + const len = array.length; 89 + 90 + if (len === 0) { 91 + return []; 92 + } 93 + 94 + let prev = array[0]; 95 + let current = [prev]; 96 + 97 + const clusters: T[][] = [current]; 98 + 99 + for (let idx = 1; idx < len; idx++) { 100 + const item = array[idx]; 101 + 102 + if (predicate(prev, item)) { 103 + current.push(item); 104 + } else { 105 + clusters.push(current = [item]); 106 + } 107 + 108 + prev = item; 109 + } 110 + 111 + return clusters; 112 + }; 113 + 114 + /** 81 115 * returns elements present in the first array but not in the second 82 116 * @param a the source array 83 117 * @param b the array to compare against