Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
fix: optimise utils
Sidwebworks92ecf019c9f3
diff --git a/packages/utils/src/arrays.ts b/packages/utils/src/arrays.tsindex 0efa2f3674..14a9506a04 100644--- a/packages/utils/src/arrays.ts+++ b/packages/utils/src/arrays.ts@@ -5,25 +5,30 @@ export type ArrayElement<A> = A extends readonly (infer T)[] ? T : never;/*** A utility function to filter out null and undefined values from an array.+ *+ * Indexed loop instead of `.reduce` to avoid the per-call closure+ * allocation and keep the load IC at `arr[i]` monomorphic.*/export const filterEmpty = <T extends Array<any>,U = Exclude<ArrayElement<T>, null | undefined>>(arr: T-): U[] =>- arr.reduce<U[]>((acc, item) => {- if (item !== null && item !== undefined) {- acc.push(item);- }-- return acc;- }, []);+): U[] => {+ const out: U[] = [];+ const len = arr.length;+ for (let i = 0; i < len; i++) {+ const item = arr[i];+ if (item !== null && item !== undefined) out.push(item);+ }+ return out;+};// Chunkexport function chunkArray<T>(array: T[], chunkSize: number): T[][] {const chunks: T[][] = [];- for (let i = 0; i < array.length; i += chunkSize) {+ const len = array.length;+ for (let i = 0; i < len; i += chunkSize) {chunks.push(array.slice(i, i + chunkSize));}return chunks;diff --git a/packages/utils/src/date.ts b/packages/utils/src/date.tsindex b845bd8bad..ff3ab06e64 100644--- a/packages/utils/src/date.ts+++ b/packages/utils/src/date.ts@@ -22,6 +22,32 @@ const defaultFormatOptions: Intl.DateTimeFormatOptions = {timeZone: getLocalTimeZone()};+// `Intl.DateTimeFormat` / `Intl.RelativeTimeFormat` constructors are+// expensive (locale data lookup + ICU init). These caches reuse the+// formatter for the default-options call sites — `formatDate(d)` in tables+// and `formatTimeAgo(t)` in feeds run thousands of times per render.+// Custom-options calls fall through to a fresh formatter to avoid hashing+// the options bag.+const defaultDateFormatters = new Map<string, Intl.DateTimeFormat>();+function getDefaultDateFormatter(locale: string): Intl.DateTimeFormat {+ let f = defaultDateFormatters.get(locale);+ if (f === undefined) {+ f = new Intl.DateTimeFormat(locale, defaultFormatOptions);+ defaultDateFormatters.set(locale, f);+ }+ return f;+}++const relativeFormatters = new Map<string, Intl.RelativeTimeFormat>();+function getRelativeFormatter(locale: string): Intl.RelativeTimeFormat {+ let f = relativeFormatters.get(locale);+ if (f === undefined) {+ f = new Intl.RelativeTimeFormat(locale, { numeric: "auto" });+ relativeFormatters.set(locale, f);+ }+ return f;+}+export function convertDateStringToIsoString(dateString: string) {return new Date(dateString).toISOString();}@@ -33,6 +59,9 @@ export function formatDate() {if (!dateString) return "";const _locale = locale || DEFAULT_LOCALE;+ const formatter = options+ ? new Intl.DateTimeFormat(_locale, options)+ : getDefaultDateFormatter(_locale);try {const _dateString = toZoned(parseDate(dateString),@@ -42,17 +71,11 @@ export function formatDate(// @ts-expect-errorconst date = parseAbsolute(_dateString);- return new Intl.DateTimeFormat(- _locale,- options || defaultFormatOptions- ).format(date.toDate());+ return formatter.format(date.toDate());} catch {try {const date = new Date(dateString);- return new Intl.DateTimeFormat(- _locale,- options || defaultFormatOptions- ).format(date);+ return formatter.format(date);} catch {return dateString;}@@ -76,15 +99,12 @@ export function formatRelativeTime(isoString: string, locale?: string) {}export function formatTimeAgo(isoString: string, locale?: string) {- const relativeFormatter = new Intl.RelativeTimeFormat(- locale || DEFAULT_LOCALE,- { numeric: "auto" }- );- let duration = (new Date(isoString).getTime() - new Date().getTime()) / 1000;+ const relativeFormatter = getRelativeFormatter(locale || DEFAULT_LOCALE);+ let duration = (new Date(isoString).getTime() - Date.now()) / 1000;- for (let i = 0; i <= DIVISIONS.length; i++) {+ const len = DIVISIONS.length;+ for (let i = 0; i < len; i++) {const division = DIVISIONS[i];- if (!division) return "";if (Math.abs(duration) < division.amount) {return relativeFormatter.format(Math.round(duration), division.name);}@@ -94,20 +114,18 @@ export function formatTimeAgo(isoString: string, locale?: string) {}export function formatTimeFromNow(isoString: string, locale?: string) {- const relativeFormatter = new Intl.RelativeTimeFormat(- locale || DEFAULT_LOCALE,- { numeric: "auto" }- );- let duration = (new Date().getTime() - new Date(isoString).getTime()) / 1000;+ const relativeFormatter = getRelativeFormatter(locale || DEFAULT_LOCALE);+ let duration = (Date.now() - new Date(isoString).getTime()) / 1000;- for (let i = 0; i <= DIVISIONS.length; i++) {+ const len = DIVISIONS.length;+ for (let i = 0; i < len; i++) {const division = DIVISIONS[i];- if (!division) return "";if (Math.abs(duration) < division.amount) {return relativeFormatter.format(Math.round(-1 * duration), division.name);}- duration /= division!.amount;+ duration /= division.amount;}+ return "";}export function getDateNYearsAgo(n: number) {diff --git a/packages/utils/src/duration.ts b/packages/utils/src/duration.tsindex 82853ed272..db034dcf82 100644--- a/packages/utils/src/duration.ts+++ b/packages/utils/src/duration.ts@@ -28,6 +28,31 @@ export function formatDuration(const aboveOneSecondUnits = ["d", "h", "m", "s"] as Unit[];const belowOneSecondUnits = ["ms"] as Unit[];+// Single regex pass replaces the 14-step `.replace` chain in the "short"+// style branch — each prior `.replace` allocated a new intermediate+// string. Unit ordering: longer suffix first so plurals don't get+// truncated to the singular form.+const SHORT_UNIT_PATTERN =+ / (milliseconds?|seconds?|minutes?|hours?|days?|weeks?|months?|years?)/g;+const SHORT_UNIT_MAP: Record<string, string> = {+ millisecond: "ms",+ milliseconds: "ms",+ second: "s",+ seconds: "s",+ minute: "m",+ minutes: "m",+ hour: "h",+ hours: "h",+ day: "d",+ days: "d",+ week: "w",+ weeks: "w",+ month: "mo",+ months: "mo",+ year: "y",+ years: "y"+};+export function formatDurationHours(hours: number,options?: DurationOptions@@ -62,24 +87,11 @@ export function formatDurationMilliseconds(return duration;}- switch (options.style) {- case "short":- duration = duration.replace(" milliseconds", "ms");- duration = duration.replace(" millisecond", "ms");- duration = duration.replace(" seconds", "s");- duration = duration.replace(" second", "s");- duration = duration.replace(" minutes", "m");- duration = duration.replace(" minute", "m");- duration = duration.replace(" hours", "h");- duration = duration.replace(" hour", "h");- duration = duration.replace(" days", "d");- duration = duration.replace(" day", "d");- duration = duration.replace(" weeks", "w");- duration = duration.replace(" week", "w");- duration = duration.replace(" months", "mo");- duration = duration.replace(" month", "mo");- duration = duration.replace(" years", "y");- duration = duration.replace(" year", "y");+ if (options.style === "short") {+ duration = duration.replace(+ SHORT_UNIT_PATTERN,+ (_match: string, unit: string) => SHORT_UNIT_MAP[unit]+ );}return duration;diff --git a/packages/utils/src/items.ts b/packages/utils/src/items.tsindex e60e979903..b51a62a3b1 100644--- a/packages/utils/src/items.ts+++ b/packages/utils/src/items.ts@@ -14,8 +14,14 @@ export function getItemReadableId(itemId?: string | null): string | undefined {if (!itemId) return undefined;- const item = items.find((item) => item.id === itemId);- return item?.readableIdWithRevision;+ // Indexed loop — `.find` allocates a closure per call. Hot path: list+ // rendering looks up readable ids per row.+ const len = items.length;+ for (let i = 0; i < len; i++) {+ const item = items[i];+ if (item.id === itemId) return item.readableIdWithRevision;+ }+ return undefined;}/**@@ -25,7 +31,27 @@ export function getItemReadableId(* @returns The item, or undefined if not found*/export function getItemById(items: Item[], itemId: string): Item | undefined {- return items.find((item) => item.id === itemId);+ const len = items.length;+ for (let i = 0; i < len; i++) {+ const item = items[i];+ if (item.id === itemId) return item;+ }+ return undefined;+}++// Build a separator-joined string from a fixed-arity record without+// allocating an intermediate `[…].filter().join()` array — saves two array+// allocations and a closure per call. Falsy parts (undefined, "") are+// dropped to match the prior `.filter((p) => !!p)` behaviour.+function joinTruthy(parts: (string | undefined)[], sep: string): string {+ let out = "";+ const len = parts.length;+ for (let i = 0; i < len; i++) {+ const part = parts[i];+ if (!part) continue;+ out = out.length === 0 ? part : out + sep + part;+ }+ return out;}export function getMaterialDescription(material: {@@ -36,16 +62,17 @@ export function getMaterialDescription(material: {dimensions?: string;finish?: string;}) {- return [- material.grade,- material.substance,- material.materialType,- material.shape,- material.dimensions,- material.finish- ]- .filter((p) => !!p)- .join(" ");+ return joinTruthy(+ [+ material.grade,+ material.substance,+ material.materialType,+ material.shape,+ material.dimensions,+ material.finish+ ],+ " "+ );}export function getMaterialId(material: {@@ -56,14 +83,15 @@ export function getMaterialId(material: {dimensions?: string;finish?: string;}) {- return [- material.grade,- material.substanceCode,- material.materialTypeCode,- material.shapeCode,- material.dimensions,- material.finish- ]- .filter((p) => !!p)- .join("-");+ return joinTruthy(+ [+ material.grade,+ material.substanceCode,+ material.materialTypeCode,+ material.shapeCode,+ material.dimensions,+ material.finish+ ],+ "-"+ );}diff --git a/packages/utils/src/object.ts b/packages/utils/src/object.tsindex b65d36f242..e0bf12b1e0 100644--- a/packages/utils/src/object.ts+++ b/packages/utils/src/object.ts@@ -1,18 +1,27 @@+/**+ * Group an array by a key derived from each item. Indexed loop and a+ * `result[key] === undefined` check keep the hot path off `.reduce`'s+ * closure allocation and avoid the implicit `in` lookup of `!result[key]`+ * (which also misbehaves on items that happen to map to the falsy keys+ * `""` / `0`).+ */export const groupBy = <T, K extends keyof any>(array: T[],getKey: (item: T) => K): Record<K, T[]> => {- return array.reduce(- (result, item) => {- const key = getKey(item);- if (!result[key]) {- result[key] = [];- }- result[key].push(item);- return result;- },- {} as Record<K, T[]>- );+ const result = {} as Record<K, T[]>;+ const len = array.length;+ for (let i = 0; i < len; i++) {+ const item = array[i];+ const key = getKey(item);+ const bucket = result[key];+ if (bucket === undefined) {+ result[key] = [item];+ } else {+ bucket.push(item);+ }+ }+ return result;};export const pick = <T extends Record<string, any>, K extends keyof T>(@@ -20,7 +29,9 @@ export const pick = <T extends Record<string, any>, K extends keyof T>(keys: K[]): Pick<T, K> => {const result = {} as Pick<T, K>;- for (const key of keys) {+ const len = keys.length;+ for (let i = 0; i < len; i++) {+ const key = keys[i];if (key in obj) {result[key] = obj[key];}@@ -33,8 +44,6 @@ export const get = <T extends Record<string, any>, K extends keyof T>(key: K,defaultValue: T[K]): T[K] => {- if (obj[key] === undefined) {- return defaultValue;- }- return obj[key];+ const value = obj[key];+ return value === undefined ? defaultValue : value;};diff --git a/packages/utils/src/string.ts b/packages/utils/src/string.tsindex a820e34aae..824ae088ce 100644--- a/packages/utils/src/string.ts+++ b/packages/utils/src/string.ts@@ -10,6 +10,12 @@ export function parseBoolean<T>(if (!value) return defaultValue;if (typeof value === "boolean") return value;++ // Fast-path the canonical lowercased forms before allocating+ // `trim().toLowerCase()` strings.+ if (value === "true" || value === "1") return true;+ if (value === "false" || value === "0") return false;+const normalized = value.trim().toLowerCase();if (normalized === "true" || normalized === "1") return true;if (normalized === "false" || normalized === "0") return false;