All files / core/src array.ts

100% Statements 177/177
100% Branches 71/71
100% Functions 13/13
100% Lines 177/177

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290                            1x 1x 1x 1x 1x 1x   1x 1x 6x 6x 1x 4x 4x 1x 12x 12x 1x 3x 3x 1x 2x 2x 1x 1x 1x 1x 1x 1x 1x 3x 3x 1x                                   1x 114x   114x 1x 1x   113x 113x 113x   113x 113x 113x   114x 114x   114x 1017x 1017x   130x     130x     130x 130x   130x 18x   18x 17x 17x     18x 129x   5x 112x   72x 107x 12x 34x 12x 12x   130x 130x     130x 13x     13x 2x 2x 2x   2x 2x 2x 2x 13x 11x 11x 11x 11x 11x   11x 11x 11x 11x 11x 11x 11x 11x 11x 11x   11x 5x 11x 1x 1x   1x 1x 13x     119x   130x 17x 16x 17x 17x   16x 17x 1x 1x 1x 1x 126x 102x 102x   119x 126x 24x 24x     126x 40x 51x 51x 1x 1x 51x 40x   119x 119x 119x 119x 119x 119x       119x 119x   126x   130x 15x 15x   104x 130x   1017x 1017x 1017x   114x 20x 180x 180x 22x 22x 22x   180x 180x 20x   113x 113x   1x                                 1x 17x 17x                                   1x 17x 17x   17x 32x 32x   32x 17x 32x 15x 15x 32x   17x 17x  
import type {
  ArrayMutation,
  ArrayMutator,
  Broadcaster,
  Linkable,
  MethodLike,
  ModelArray,
  ModelError,
  ObjLike,
  StateChange,
  StateMetadata,
  StateRelation,
  TrapOverrides,
} from './types.js';
import { BROADCASTER_REGISTRY, INIT_REGISTRY, META_REGISTRY, RELATION_REGISTRY, SORTER_REGISTRY } from './registry.js';
import { ARRAY_MUTATIONS, HEURISTIC_THRESHOLD } from './constant.js';
import { captureStack } from './exception.js';
import { getDevTool } from './dev.js';
import { isFunction } from '@beerush/utils';
import { anchor } from './anchor.js';
 
const mockReturn = {
  shift(items: unknown[]) {
    return items[0];
  },
  unshift(items: unknown[]) {
    return items.length;
  },
  push(items: unknown[]) {
    return items.length;
  },
  pop(items: unknown[]) {
    return items[items.length - 1];
  },
  splice() {
    return [];
  },
  fill(items: unknown[]) {
    return items;
  },
  sort(items: unknown[]) {
    return items;
  },
  reverse(items: unknown[]) {
    return items;
  },
};
 
/**
 * Creates a mutator for an array that handles state changes and validation.
 *
 * This function creates a WeakMap of method proxies for array mutation methods.
 * It handles both mutable and immutable array operations, including:
 * - Validation of new items against a schema
 * - Broadcasting of state changes to subscribers
 * - Proper linking/unlinking of array elements
 * - Handling of immutable arrays by returning mock values
 *
 * @template T - The type of the array
 * @param init - The initial array state
 * @param options - Optional state references containing schema, configs, and subscribers
 * @returns A WeakMap mapping original array methods to their proxied implementations
 * @throws Error if called on a non-reactive state (when no references are found)
 */
export function createArrayMutator<T extends unknown[]>(init: T, options?: TrapOverrides) {
  const meta = META_REGISTRY.get(init) as StateMetadata;
 
  if (!meta) {
    throw new Error(`Array trap factory called on non-reactive state.`);
  }
 
  const devTool = getDevTool();
  const compare = SORTER_REGISTRY.get(init);
  const broadcaster = BROADCASTER_REGISTRY.get(init) as Broadcaster;
 
  const { schema, subscriptions } = meta;
  const { unlink } = RELATION_REGISTRY.get(init) as StateRelation;
  const { configs } = options ?? meta;
 
  const mutator: ArrayMutator<T[number]> = {} as never;
  const mutatorMap = new WeakMap<WeakKey, MethodLike>();
 
  for (const method of ARRAY_MUTATIONS) {
    const originFn = (init as Array<unknown>)[method] as (...args: unknown[]) => unknown;
    const targetFn = (...args: unknown[]) => {
      // Make sure to always work with the underlying object (if exist).
      args = args.map((arg) => (anchor.has(arg as Linkable) ? anchor.get(arg as Linkable) : arg));
 
      // Capture the current items to track the removed items.
      const currentItems = [...(init as ObjLike[])];
 
      // Create a list of the added items.
      let addedItems: Linkable[] = [];
      let deletedItems: Linkable[] = [];
 
      if (method === 'splice') {
        const [start, delCount] = args as [number, number];
 
        if (delCount) {
          deletedItems = currentItems.slice(start, start + delCount);
        }
 
        // For splice, new items start from index 2 (after start and deleteCount)
        addedItems = args.slice(2) as Linkable[];
      } else if (method === 'fill') {
        // For fill, the same value is used for all elements
        addedItems = [args[0] as Linkable];
      } else if (method === 'push' || method === 'unshift') {
        // For push and unshift, all arguments are new items
        addedItems = args as Linkable[];
      } else if (method === 'shift') {
        deletedItems = [currentItems[0]];
      } else if (method === 'pop') {
        deletedItems = [currentItems[currentItems.length - 1]];
      }
 
      const addedItemsLength = addedItems.length;
      const deletedItemsLength = deletedItems.length;
 
      // Validate the added items.
      if (schema && addedItemsLength) {
        const validation = (schema as ModelArray).safeParse(addedItems);
 
        // If validation is successful, update the arguments with validated data.
        if (validation.success) {
          for (let i = 0; i < addedItemsLength; i++) {
            const value = addedItems[i];
            const index = args.indexOf(value);
 
            if (index > -1) {
              args[index] = (validation.data as unknown[])?.[i];
            }
          }
        } else {
          broadcaster.catch(validation.error as never as ModelError, {
            type: method,
            keys: [],
            value: args,
          });
 
          broadcaster.broadcast(
            init,
            {
              type: method,
              keys: [],
              error: validation.error as never as ModelError,
              value: args,
            },
            meta.id
          );
 
          if (method === 'push' || method === 'unshift') {
            return currentItems.length;
          } else if (method === 'splice') {
            return [];
          }
 
          return INIT_REGISTRY.get(init);
        }
      }
 
      // Call the original method to perform the operation.
      let result: unknown;
 
      if (method === 'push' && configs.ordered && isFunction(compare)) {
        if (addedItems.length <= HEURISTIC_THRESHOLD) {
          for (const item of addedItems) {
            orderedPush(init, item, compare);
          }
 
          result = init.length;
        } else {
          originFn.apply(init, args);
          init.sort(compare);
          result = init.length;
        }
      } else {
        result = originFn.apply(init, args);
      }
 
      let current = currentItems;
      if (['shift', 'pop'].includes(method)) {
        current = result as never;
      }
 
      // Unlink the deleted items.
      if (deletedItemsLength) {
        for (const item of deletedItems) {
          const childState = INIT_REGISTRY.get(item) as Linkable;
          if (subscriptions.has(childState)) {
            unlink(childState);
          }
        }
      }
 
      const event: StateChange = {
        type: method as ArrayMutation,
        prev: current,
        keys: [],
        value: args,
      };
 
      // Broadcast the array mutation event to all subscribers
      // Make sure to broadcast to subscribers first because observers might depend on a derived state.
      broadcaster.broadcast(init, event, meta.id);
      broadcaster.emit(event);
 
      devTool?.onCall?.(meta, method, args);
 
      if (result === init) {
        return INIT_REGISTRY.get(init);
      }
 
      return result;
    };
 
    mutator[method] = targetFn as never;
    mutatorMap.set(originFn, targetFn);
  }
 
  if (configs.immutable) {
    for (const method of ARRAY_MUTATIONS) {
      const originFn = (init as Array<unknown>)[method] as (...args: unknown[]) => unknown;
      const targetFn: MethodLike = (...args) => {
        captureStack.violation.methodCall(method, targetFn);
        return (mockReturn[method as never] as typeof targetFn)?.(INIT_REGISTRY.get(init), ...args);
      };
 
      mutatorMap.set(originFn, targetFn);
    }
  }
 
  return { mutator, mutatorMap };
}
 
createArrayMutator.mock = mockReturn;
 
/**
 * Inserts an item into an array at the correct position to maintain sorted order.
 *
 * This function uses binary search to find the correct insertion point for the item
 * based on the provided comparison function. The array must already be sorted
 * according to the same comparison function for the result to be correctly sorted.
 *
 * @template T - The type of elements in the array
 * @param target - The sorted array to insert the item into
 * @param item - The item to insert
 * @param compare - A function that defines the sort order. It should return:
 *   - A negative value if the first argument is less than the second
 *   - Zero if the first argument is equal to the second
 *   - A positive value if the first argument is greater than the second
 */
export function orderedPush<T>(target: T[], item: T, compare: (a: T, b: T) => number): void {
  target.splice(orderedIndexOf(target, item, compare), 0, item);
}
 
/**
 * Finds the index at which an item should be inserted into a sorted array to maintain sort order.
 *
 * This function uses binary search to efficiently determine the correct insertion point
 * for the item based on the provided comparison function. The array must already be sorted
 * according to the same comparison function for the result to be correct.
 *
 * @template T - The type of elements in the array
 * @param target - The sorted array to search
 * @param item - The item to find the insertion index for
 * @param compare - A function that defines the sort order. It should return:
 *   - A negative value if the first argument is less than the second
 *   - Zero if the first argument is equal to the second
 *   - A positive value if the first argument is greater than the second
 * @returns The index at which the item should be inserted to maintain sorted order
 */
export function orderedIndexOf<T>(target: T[], item: T, compare: (a: T, b: T) => number): number {
  let low = 0;
  let high = target.length;
 
  while (low < high) {
    const mid = Math.floor((low + high) / 2);
    const result = compare(target[mid], item);
 
    if (result <= 0) {
      low = mid + 1;
    } else {
      high = mid;
    }
  }
 
  return low;
}