[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill-2dd42e06-74cb-46cd-bb4d-fe0a11a7680c":3,"$f3bc2fZBN_VZAW-6f8ThlfgQcTH3j26QHxcexdKvGqeY":43},{"id":4,"title":5,"description":6,"categoryId":7,"moduleId":8,"tags":9,"prompt":10,"icon":11,"source":12,"sourceUrl":13,"authorId":14,"authorName":15,"isPublic":16,"stars":17,"runs":18,"createdAt":19,"updatedAt":19,"module":20,"category":27,"packages":34},"2dd42e06-74cb-46cd-bb4d-fe0a11a7680c","fp-data-transforms","使用函数模式进行日常数据转换 - 数组、对象、分组、聚合和空安全访问","cat_life_career","mod_other","sickn33,other","---\nname: fp-data-transforms\ndescription: Everyday data transformations using functional patterns - arrays, objects, grouping, aggregation, and null-safe access\nrisk: unknown\nsource: community\nversion: 1.0.0\nauthor: Claude\ntags:\n  - functional-programming\n  - typescript\n  - data-transformation\n  - fp-ts\n  - arrays\n  - objects\n  - grouping\n  - aggregation\n  - null-safety\n---\n\n# Practical Data Transformations\n\nThis skill covers the data transformations you do every day: working with arrays, reshaping objects, normalizing API responses, grouping data, and safely accessing nested values. Each section shows the imperative approach first, then the functional equivalent, with honest assessments of when each approach shines.\n\n## When to Use\n- You need to transform arrays, objects, grouped data, or nested values in TypeScript.\n- The task involves reshaping API responses, null-safe access, aggregation, or normalization.\n- You want practical functional patterns for everyday data work instead of low-level loops.\n\n---\n\n## Table of Contents\n\n1. [Array Operations](#1-array-operations)\n2. [Object Transformations](#2-object-transformations)\n3. [Data Normalization](#3-data-normalization)\n4. [Grouping and Aggregation](#4-grouping-and-aggregation)\n5. [Null-Safe Access](#5-null-safe-access)\n6. [Real-World Examples](#6-real-world-examples)\n7. [When to Use What](#7-when-to-use-what)\n\n---\n\n## 1. Array Operations\n\nArray operations are the bread and butter of data transformation. Let's replace verbose loops with expressive, chainable operations.\n\n### Map: Transform Every Element\n\n**The Task**: Convert an array of prices from cents to dollars.\n\n#### Imperative Approach\n\n```typescript\nconst pricesInCents = [999, 1499, 2999, 4999];\n\nfunction convertToDollars(prices: number[]): number[] {\n  const result: number[] = [];\n  for (let i = 0; i \u003C prices.length; i++) {\n    result.push(prices[i] \u002F 100);\n  }\n  return result;\n}\n\nconst dollars = convertToDollars(pricesInCents);\n\u002F\u002F [9.99, 14.99, 29.99, 49.99]\n```\n\n#### Functional Approach\n\n```typescript\nconst pricesInCents = [999, 1499, 2999, 4999];\n\nconst toDollars = (cents: number): number => cents \u002F 100;\n\nconst dollars = pricesInCents.map(toDollars);\n\u002F\u002F [9.99, 14.99, 29.99, 49.99]\n```\n\n**Why functional is better here**: The intent is immediately clear. `map` says \"transform each element.\" The transformation logic (`toDollars`) is named and reusable. No index management, no manual array building.\n\n### Filter: Keep What Matches\n\n**The Task**: Get all active users from a list.\n\n#### Imperative Approach\n\n```typescript\ninterface User {\n  id: string;\n  name: string;\n  isActive: boolean;\n}\n\nfunction getActiveUsers(users: User[]): User[] {\n  const result: User[] = [];\n  for (const user of users) {\n    if (user.isActive) {\n      result.push(user);\n    }\n  }\n  return result;\n}\n```\n\n#### Functional Approach\n\n```typescript\nconst isActive = (user: User): boolean => user.isActive;\n\nconst activeUsers = users.filter(isActive);\n\n\u002F\u002F Or inline for simple predicates\nconst activeUsers = users.filter(user => user.isActive);\n```\n\n**Why functional is better here**: The predicate (`isActive`) is separated from the iteration logic. You can reuse, test, and compose predicates independently.\n\n### Reduce: Accumulate Into Something New\n\n**The Task**: Calculate the total price of items in a cart.\n\n#### Imperative Approach\n\n```typescript\ninterface CartItem {\n  name: string;\n  price: number;\n  quantity: number;\n}\n\nfunction calculateTotal(items: CartItem[]): number {\n  let total = 0;\n  for (const item of items) {\n    total += item.price * item.quantity;\n  }\n  return total;\n}\n```\n\n#### Functional Approach\n\n```typescript\nconst calculateTotal = (items: CartItem[]): number =>\n  items.reduce(\n    (total, item) => total + item.price * item.quantity,\n    0\n  );\n\n\u002F\u002F Or break out the line total calculation\nconst lineTotal = (item: CartItem): number => item.price * item.quantity;\n\nconst calculateTotal = (items: CartItem[]): number =>\n  items.map(lineTotal).reduce((a, b) => a + b, 0);\n```\n\n**Honest assessment**: For simple sums, the imperative loop is actually quite readable. The functional version shines when you need to compose the accumulation with other transformations, or when the reduction logic is complex enough to benefit from being named.\n\n### Chaining: Combine Operations\n\n**The Task**: Get the names of all active premium users, sorted alphabetically.\n\n#### Imperative Approach\n\n```typescript\ninterface User {\n  id: string;\n  name: string;\n  isActive: boolean;\n  tier: 'free' | 'premium';\n}\n\nfunction getActivePremiumNames(users: User[]): string[] {\n  const result: string[] = [];\n  for (const user of users) {\n    if (user.isActive && user.tier === 'premium') {\n      result.push(user.name);\n    }\n  }\n  result.sort((a, b) => a.localeCompare(b));\n  return result;\n}\n```\n\n#### Functional Approach\n\n```typescript\nconst getActivePremiumNames = (users: User[]): string[] =>\n  users\n    .filter(user => user.isActive)\n    .filter(user => user.tier === 'premium')\n    .map(user => user.name)\n    .sort((a, b) => a.localeCompare(b));\n\n\u002F\u002F Or with named predicates for reuse\nconst isActive = (user: User): boolean => user.isActive;\nconst isPremium = (user: User): boolean => user.tier === 'premium';\nconst getName = (user: User): string => user.name;\nconst alphabetically = (a: string, b: string): number => a.localeCompare(b);\n\nconst getActivePremiumNames = (users: User[]): string[] =>\n  users\n    .filter(isActive)\n    .filter(isPremium)\n    .map(getName)\n    .sort(alphabetically);\n```\n\n**Why functional is better here**: Each step in the chain has a single responsibility. You can read the transformation as a series of steps: \"filter active, filter premium, get names, sort.\" Adding or removing a step is trivial.\n\n### Using fp-ts Array Module\n\nfp-ts provides additional array utilities with better composition support:\n\n```typescript\nimport * as A from 'fp-ts\u002FArray';\nimport * as O from 'fp-ts\u002FOption';\nimport { pipe } from 'fp-ts\u002Ffunction';\n\n\u002F\u002F Safe head (first element)\nconst first = pipe(\n  [1, 2, 3],\n  A.head\n); \u002F\u002F Some(1)\n\nconst firstOfEmpty = pipe(\n  [] as number[],\n  A.head\n); \u002F\u002F None\n\n\u002F\u002F Safe lookup by index\nconst third = pipe(\n  ['a', 'b', 'c', 'd'],\n  A.lookup(2)\n); \u002F\u002F Some('c')\n\n\u002F\u002F Find with predicate\nconst found = pipe(\n  users,\n  A.findFirst(user => user.id === 'abc123')\n); \u002F\u002F Option\u003CUser>\n\n\u002F\u002F Partition into two groups\nconst [inactive, active] = pipe(\n  users,\n  A.partition(user => user.isActive)\n);\n\n\u002F\u002F Take first N elements\nconst topThree = pipe(\n  sortedScores,\n  A.takeLeft(3)\n);\n\n\u002F\u002F Unique values\nconst uniqueTags = pipe(\n  allTags,\n  A.uniq({ equals: (a, b) => a === b })\n);\n```\n\n---\n\n## 2. Object Transformations\n\nObjects need reshaping constantly: picking fields, omitting sensitive data, merging settings, and updating nested values.\n\n### Pick: Select Specific Fields\n\n**The Task**: Extract only the public fields from a user object.\n\n#### Imperative Approach\n\n```typescript\ninterface User {\n  id: string;\n  name: string;\n  email: string;\n  passwordHash: string;\n  internalNotes: string;\n}\n\nfunction getPublicUser(user: User): { id: string; name: string; email: string } {\n  return {\n    id: user.id,\n    name: user.name,\n    email: user.email,\n  };\n}\n```\n\n#### Functional Approach\n\n```typescript\n\u002F\u002F Generic pick utility\nconst pick = \u003CT extends object, K extends keyof T>(\n  keys: K[]\n) => (obj: T): Pick\u003CT, K> =>\n  keys.reduce(\n    (result, key) => {\n      result[key] = obj[key];\n      return result;\n    },\n    {} as Pick\u003CT, K>\n  );\n\nconst getPublicUser = pick\u003CUser, 'id' | 'name' | 'email'>(['id', 'name', 'email']);\n\nconst publicUser = getPublicUser(user);\n```\n\n**Why functional is better here**: The `pick` utility is reusable across your codebase. Type safety ensures you can only pick keys that exist.\n\n### Omit: Remove Specific Fields\n\n**The Task**: Remove sensitive fields before logging.\n\n#### Imperative Approach\n\n```typescript\nfunction sanitizeForLogging(user: User): Omit\u003CUser, 'passwordHash' | 'internalNotes'> {\n  const { passwordHash, internalNotes, ...safe } = user;\n  return safe;\n}\n```\n\n#### Functional Approach\n\n```typescript\n\u002F\u002F Generic omit utility\nconst omit = \u003CT extends object, K extends keyof T>(\n  keys: K[]\n) => (obj: T): Omit\u003CT, K> => {\n  const result = { ...obj };\n  for (const key of keys) {\n    delete result[key];\n  }\n  return result as Omit\u003CT, K>;\n};\n\nconst sanitizeForLogging = omit\u003CUser, 'passwordHash' | 'internalNotes'>([\n  'passwordHash',\n  'internalNotes',\n]);\n```\n\n**Honest assessment**: For one-off omits, destructuring (the imperative approach) is perfectly fine and very readable. The functional `omit` utility pays off when you have many such transformations or need to compose them.\n\n### Merge: Combine Objects\n\n**The Task**: Merge user settings with defaults.\n\n#### Imperative Approach\n\n```typescript\ninterface Settings {\n  theme: 'light' | 'dark';\n  fontSize: number;\n  notifications: boolean;\n  language: string;\n}\n\nfunction mergeSettings(\n  defaults: Settings,\n  userSettings: Partial\u003CSettings>\n): Settings {\n  return {\n    theme: userSettings.theme !== undefined ? userSettings.theme : defaults.theme,\n    fontSize: userSettings.fontSize !== undefined ? userSettings.fontSize : defaults.fontSize,\n    notifications: userSettings.notifications !== undefined\n      ? userSettings.notifications\n      : defaults.notifications,\n    language: userSettings.language !== undefined ? userSettings.language : defaults.language,\n  };\n}\n```\n\n#### Functional Approach\n\n```typescript\nconst mergeSettings = (\n  defaults: Settings,\n  userSettings: Partial\u003CSettings>\n): Settings => ({\n  ...defaults,\n  ...userSettings,\n});\n\n\u002F\u002F Usage\nconst defaults: Settings = {\n  theme: 'light',\n  fontSize: 14,\n  notifications: true,\n  language: 'en',\n};\n\nconst userPrefs: Partial\u003CSettings> = {\n  theme: 'dark',\n  fontSize: 16,\n};\n\nconst finalSettings = mergeSettings(defaults, userPrefs);\n\u002F\u002F { theme: 'dark', fontSize: 16, notifications: true, language: 'en' }\n```\n\n**Why functional is better here**: Spread syntax is concise and handles any number of keys. Later spreads override earlier ones, giving you natural \"defaults with overrides\" behavior.\n\n### Deep Merge: Nested Object Combination\n\n**The Task**: Merge nested configuration objects.\n\n#### Imperative Approach\n\n```typescript\ninterface Config {\n  api: {\n    baseUrl: string;\n    timeout: number;\n    retries: number;\n  };\n  ui: {\n    theme: string;\n    animations: boolean;\n  };\n}\n\nfunction deepMerge(\n  target: Config,\n  source: Partial\u003CConfig>\n): Config {\n  const result = { ...target };\n\n  if (source.api) {\n    result.api = { ...target.api, ...source.api };\n  }\n  if (source.ui) {\n    result.ui = { ...target.ui, ...source.ui };\n  }\n\n  return result;\n}\n```\n\n#### Functional Approach\n\n```typescript\n\u002F\u002F Generic deep merge for one level of nesting\nconst deepMerge = \u003CT extends Record\u003Cstring, object>>(\n  target: T,\n  source: { [K in keyof T]?: Partial\u003CT[K]> }\n): T => {\n  const result = { ...target };\n\n  for (const key of Object.keys(source) as Array\u003Ckeyof T>) {\n    if (source[key] !== undefined) {\n      result[key] = { ...target[key], ...source[key] };\n    }\n  }\n\n  return result;\n};\n\n\u002F\u002F Usage\nconst defaultConfig: Config = {\n  api: { baseUrl: 'https:\u002F\u002Fapi.example.com', timeout: 5000, retries: 3 },\n  ui: { theme: 'light', animations: true },\n};\n\nconst customConfig = deepMerge(defaultConfig, {\n  api: { timeout: 10000 },\n  ui: { theme: 'dark' },\n});\n\u002F\u002F api.baseUrl preserved, api.timeout overridden\n\u002F\u002F ui.theme overridden, ui.animations preserved\n```\n\n### Immutable Updates: Change Nested Values\n\n**The Task**: Update a deeply nested value without mutation.\n\n#### Imperative (Mutating) Approach\n\n```typescript\ninterface State {\n  user: {\n    profile: {\n      settings: {\n        theme: string;\n      };\n    };\n  };\n}\n\nfunction updateTheme(state: State, newTheme: string): void {\n  state.user.profile.settings.theme = newTheme; \u002F\u002F Mutation!\n}\n```\n\n#### Functional (Immutable) Approach\n\n```typescript\n\u002F\u002F Manual spread nesting\nconst updateTheme = (state: State, newTheme: string): State => ({\n  ...state,\n  user: {\n    ...state.user,\n    profile: {\n      ...state.user.profile,\n      settings: {\n        ...state.user.profile.settings,\n        theme: newTheme,\n      },\n    },\n  },\n});\n\n\u002F\u002F With a lens-like helper\nconst updatePath = \u003CT, V>(\n  obj: T,\n  path: string[],\n  value: V\n): T => {\n  if (path.length === 0) return value as unknown as T;\n\n  const [head, ...rest] = path;\n  return {\n    ...obj,\n    [head]: updatePath((obj as Record\u003Cstring, unknown>)[head], rest, value),\n  } as T;\n};\n\nconst newState = updatePath(state, ['user', 'profile', 'settings', 'theme'], 'dark');\n```\n\n**Honest assessment**: The spread nesting is verbose but explicit. For deeply nested updates, consider using a library like `immer` or fp-ts lenses. The verbosity of the functional approach is the price of immutability.\n\n---\n\n## 3. Data Normalization\n\nAPI responses rarely match the shape your app needs. Normalization transforms nested, denormalized data into flat, indexed structures.\n\n### API Response to App State\n\n**The Task**: Transform a nested API response into a normalized state.\n\n#### API Response (What You Get)\n\n```typescript\ninterface ApiResponse {\n  orders: Array\u003C{\n    id: string;\n    customerId: string;\n    customerName: string;\n    customerEmail: string;\n    items: Array\u003C{\n      productId: string;\n      productName: string;\n      quantity: number;\n      price: number;\n    }>;\n    total: number;\n    status: string;\n  }>;\n}\n```\n\n#### App State (What You Need)\n\n```typescript\ninterface NormalizedState {\n  orders: {\n    byId: Record\u003Cstring, Order>;\n    allIds: string[];\n  };\n  customers: {\n    byId: Record\u003Cstring, Customer>;\n    allIds: string[];\n  };\n  products: {\n    byId: Record\u003Cstring, Product>;\n    allIds: string[];\n  };\n}\n\ninterface Order {\n  id: string;\n  customerId: string;\n  itemIds: string[];\n  total: number;\n  status: string;\n}\n\ninterface Customer {\n  id: string;\n  name: string;\n  email: string;\n}\n\ninterface Product {\n  id: string;\n  name: string;\n  price: number;\n}\n```\n\n#### Imperative Approach\n\n```typescript\nfunction normalizeApiResponse(response: ApiResponse): NormalizedState {\n  const state: NormalizedState = {\n    orders: { byId: {}, allIds: [] },\n    customers: { byId: {}, allIds: [] },\n    products: { byId: {}, allIds: [] },\n  };\n\n  for (const order of response.orders) {\n    \u002F\u002F Extract customer\n    if (!state.customers.byId[order.customerId]) {\n      state.customers.byId[order.customerId] = {\n        id: order.customerId,\n        name: order.customerName,\n        email: order.customerEmail,\n      };\n      state.customers.allIds.push(order.customerId);\n    }\n\n    \u002F\u002F Extract products and build item IDs\n    const itemIds: string[] = [];\n    for (const item of order.items) {\n      if (!state.products.byId[item.productId]) {\n        state.products.byId[item.productId] = {\n          id: item.productId,\n          name: item.productName,\n          price: item.price,\n        };\n        state.products.allIds.push(item.productId);\n      }\n      itemIds.push(item.productId);\n    }\n\n    \u002F\u002F Add normalized order\n    state.orders.byId[order.id] = {\n      id: order.id,\n      customerId: order.customerId,\n      itemIds,\n      total: order.total,\n      status: order.status,\n    };\n    state.orders.allIds.push(order.id);\n  }\n\n  return state;\n}\n```\n\n#### Functional Approach\n\n```typescript\nimport { pipe } from 'fp-ts\u002Ffunction';\nimport * as A from 'fp-ts\u002FArray';\nimport * as R from 'fp-ts\u002FRecord';\n\n\u002F\u002F Helper to create normalized collection\ninterface NormalizedCollection\u003CT extends { id: string }> {\n  byId: Record\u003Cstring, T>;\n  allIds: string[];\n}\n\nconst createNormalizedCollection = \u003CT extends { id: string }>(\n  items: T[]\n): NormalizedCollection\u003CT> => ({\n  byId: pipe(\n    items,\n    A.reduce({} as Record\u003Cstring, T>, (acc, item) => ({\n      ...acc,\n      [item.id]: item,\n    }))\n  ),\n  allIds: items.map(item => item.id),\n});\n\n\u002F\u002F Extract entities\nconst extractCustomers = (orders: ApiResponse['orders']): Customer[] =>\n  pipe(\n    orders,\n    A.map(order => ({\n      id: order.customerId,\n      name: order.customerName,\n      email: order.customerEmail,\n    })),\n    A.uniq({ equals: (a, b) => a.id === b.id })\n  );\n\nconst extractProducts = (orders: ApiResponse['orders']): Product[] =>\n  pipe(\n    orders,\n    A.flatMap(order => order.items),\n    A.map(item => ({\n      id: item.productId,\n      name: item.productName,\n      price: item.price,\n    })),\n    A.uniq({ equals: (a, b) => a.id === b.id })\n  );\n\nconst extractOrders = (orders: ApiResponse['orders']): Order[] =>\n  orders.map(order => ({\n    id: order.id,\n    customerId: order.customerId,\n    itemIds: order.items.map(item => item.productId),\n    total: order.total,\n    status: order.status,\n  }));\n\n\u002F\u002F Compose into final normalization\nconst normalizeApiResponse = (response: ApiResponse): NormalizedState => ({\n  orders: createNormalizedCollection(extractOrders(response.orders)),\n  customers: createNormalizedCollection(extractCustomers(response.orders)),\n  products: createNormalizedCollection(extractProducts(response.orders)),\n});\n```\n\n**Why functional is better here**: Each extraction is independent and testable. The `createNormalizedCollection` helper is reusable. Adding a new entity type means adding one new extraction function.\n\n### Transform API Response to UI-Ready Data\n\n**The Task**: Convert API data to what your components need.\n\n```typescript\n\u002F\u002F API gives you this\ninterface ApiUser {\n  user_id: string;\n  first_name: string;\n  last_name: string;\n  email_address: string;\n  created_at: string; \u002F\u002F ISO string\n  avatar_url: string | null;\n}\n\n\u002F\u002F Components need this\ninterface DisplayUser {\n  id: string;\n  fullName: string;\n  email: string;\n  memberSince: string; \u002F\u002F \"Jan 2024\"\n  avatarUrl: string; \u002F\u002F With fallback\n}\n```\n\n#### Functional Approach\n\n```typescript\nconst formatDate = (isoString: string): string => {\n  const date = new Date(isoString);\n  return date.toLocaleDateString('en-US', { month: 'short', year: 'numeric' });\n};\n\nconst DEFAULT_AVATAR = 'https:\u002F\u002Fexample.com\u002Fdefault-avatar.png';\n\nconst toDisplayUser = (apiUser: ApiUser): DisplayUser => ({\n  id: apiUser.user_id,\n  fullName: `${apiUser.first_name} ${apiUser.last_name}`,\n  email: apiUser.email_address,\n  memberSince: formatDate(apiUser.created_at),\n  avatarUrl: apiUser.avatar_url ?? DEFAULT_AVATAR,\n});\n\n\u002F\u002F Transform array of users\nconst toDisplayUsers = (apiUsers: ApiUser[]): DisplayUser[] =>\n  apiUsers.map(toDisplayUser);\n```\n\n---\n\n## 4. Grouping and Aggregation\n\nGrouping and aggregating data is essential for reports, dashboards, and analytics.\n\n### GroupBy: Organize by Key\n\n**The Task**: Group orders by customer.\n\n#### Imperative Approach\n\n```typescript\ninterface Order {\n  id: string;\n  customerId: string;\n  total: number;\n  date: string;\n}\n\nfunction groupByCustomer(orders: Order[]): Record\u003Cstring, Order[]> {\n  const result: Record\u003Cstring, Order[]> = {};\n\n  for (const order of orders) {\n    if (!result[order.customerId]) {\n      result[order.customerId] = [];\n    }\n    result[order.customerId].push(order);\n  }\n\n  return result;\n}\n```\n\n#### Functional Approach\n\n```typescript\n\u002F\u002F Generic groupBy utility\nconst groupBy = \u003CT, K extends string | number>(\n  getKey: (item: T) => K\n) => (items: T[]): Record\u003CK, T[]> =>\n  items.reduce(\n    (groups, item) => {\n      const key = getKey(item);\n      return {\n        ...groups,\n        [key]: [...(groups[key] || []), item],\n      };\n    },\n    {} as Record\u003CK, T[]>\n  );\n\n\u002F\u002F Usage\nconst groupByCustomer = groupBy\u003COrder, string>(order => order.customerId);\nconst ordersByCustomer = groupByCustomer(orders);\n\n\u002F\u002F Or inline\nconst ordersByStatus = groupBy((order: Order) => order.status)(orders);\n```\n\n**Using fp-ts NonEmptyArray.groupBy**:\n\n```typescript\nimport * as NEA from 'fp-ts\u002FNonEmptyArray';\nimport { pipe } from 'fp-ts\u002Ffunction';\n\n\u002F\u002F NEA.groupBy guarantees non-empty arrays in result\nconst ordersByCustomer = pipe(\n  orders as NEA.NonEmptyArray\u003COrder>, \u002F\u002F Must be non-empty\n  NEA.groupBy(order => order.customerId)\n); \u002F\u002F Record\u003Cstring, NonEmptyArray\u003COrder>>\n```\n\n### CountBy: Count Occurrences\n\n**The Task**: Count orders by status.\n\n#### Imperative Approach\n\n```typescript\nfunction countByStatus(orders: Order[]): Record\u003Cstring, number> {\n  const counts: Record\u003Cstring, number> = {};\n\n  for (const order of orders) {\n    counts[order.status] = (counts[order.status] || 0) + 1;\n  }\n\n  return counts;\n}\n```\n\n#### Functional Approach\n\n```typescript\n\u002F\u002F Generic countBy utility\nconst countBy = \u003CT, K extends string>(\n  getKey: (item: T) => K\n) => (items: T[]): Record\u003CK, number> =>\n  items.reduce(\n    (counts, item) => {\n      const key = getKey(item);\n      return {\n        ...counts,\n        [key]: (counts[key] || 0) + 1,\n      };\n    },\n    {} as Record\u003CK, number>\n  );\n\n\u002F\u002F Usage\nconst orderCountByStatus = countBy((order: Order) => order.status)(orders);\n\u002F\u002F { pending: 5, shipped: 12, delivered: 8 }\n```\n\n### SumBy: Aggregate Numeric Values\n\n**The Task**: Calculate total revenue per product category.\n\n#### Imperative Approach\n\n```typescript\ninterface Sale {\n  productId: string;\n  category: string;\n  amount: number;\n}\n\nfunction sumByCategory(sales: Sale[]): Record\u003Cstring, number> {\n  const totals: Record\u003Cstring, number> = {};\n\n  for (const sale of sales) {\n    totals[sale.category] = (totals[sale.category] || 0) + sale.amount;\n  }\n\n  return totals;\n}\n```\n\n#### Functional Approach\n\n```typescript\n\u002F\u002F Generic sumBy utility\nconst sumBy = \u003CT, K extends string>(\n  getKey: (item: T) => K,\n  getValue: (item: T) => number\n) => (items: T[]): Record\u003CK, number> =>\n  items.reduce(\n    (totals, item) => {\n      const key = getKey(item);\n      return {\n        ...totals,\n        [key]: (totals[key] || 0) + getValue(item),\n      };\n    },\n    {} as Record\u003CK, number>\n  );\n\n\u002F\u002F Usage\nconst revenueByCategory = sumBy(\n  (sale: Sale) => sale.category,\n  (sale: Sale) => sale.amount\n)(sales);\n\u002F\u002F { electronics: 15000, clothing: 8500, books: 3200 }\n```\n\n### Complex Aggregation Example\n\n**The Task**: Calculate totals from line items with quantity and unit price.\n\n```typescript\ninterface LineItem {\n  productId: string;\n  productName: string;\n  quantity: number;\n  unitPrice: number;\n}\n\ninterface Invoice {\n  id: string;\n  lineItems: LineItem[];\n  taxRate: number;\n}\n```\n\n#### Functional Approach\n\n```typescript\nconst lineTotal = (item: LineItem): number =>\n  item.quantity * item.unitPrice;\n\nconst subtotal = (items: LineItem[]): number =>\n  items.reduce((sum, item) => sum + lineTotal(item), 0);\n\nconst calculateTax = (amount: number, rate: number): number =>\n  amount * rate;\n\nconst calculateInvoiceTotal = (invoice: Invoice): {\n  subtotal: number;\n  tax: number;\n  total: number;\n} => {\n  const sub = subtotal(invoice.lineItems);\n  const tax = calculateTax(sub, invoice.taxRate);\n\n  return {\n    subtotal: sub,\n    tax,\n    total: sub + tax,\n  };\n};\n\n\u002F\u002F With fp-ts pipe for clarity\nimport { pipe } from 'fp-ts\u002Ffunction';\n\nconst calculateInvoiceTotal = (invoice: Invoice) => {\n  const sub = pipe(\n    invoice.lineItems,\n    A.map(lineTotal),\n    A.reduce(0, (a, b) => a + b)\n  );\n\n  return {\n    subtotal: sub,\n    tax: sub * invoice.taxRate,\n    total: sub * (1 + invoice.taxRate),\n  };\n};\n```\n\n---\n\n## 5. Null-Safe Access\n\nStop writing `if (x && x.y && x.y.z)`. Safely navigate nested structures without runtime errors.\n\n### The Problem\n\n```typescript\ninterface Config {\n  database?: {\n    connection?: {\n      host?: string;\n      port?: number;\n    };\n    pool?: {\n      max?: number;\n    };\n  };\n  features?: {\n    experimental?: {\n      enabled?: boolean;\n    };\n  };\n}\n```\n\n#### Imperative (Verbose) Approach\n\n```typescript\nfunction getDatabaseHost(config: Config): string {\n  if (\n    config.database &&\n    config.database.connection &&\n    config.database.connection.host\n  ) {\n    return config.database.connection.host;\n  }\n  return 'localhost';\n}\n```\n\n#### Optional Chaining (Modern TypeScript)\n\n```typescript\nconst getDatabaseHost = (config: Config): string =>\n  config.database?.connection?.host ?? 'localhost';\n```\n\n**Honest assessment**: For simple access patterns, optional chaining (`?.`) is perfect. It's built into the language and very readable. Use fp-ts Option when you need to compose operations on potentially missing values.\n\n### When to Use Option Instead\n\nUse fp-ts Option when:\n- You need to chain multiple operations on potentially missing values\n- You want to distinguish \"missing\" from other falsy values\n- You're building a pipeline of transformations\n\n```typescript\nimport * as O from 'fp-ts\u002FOption';\nimport { pipe } from 'fp-ts\u002Ffunction';\n\n\u002F\u002F Safe property access that returns Option\nconst prop = \u003CT, K extends keyof T>(key: K) =>\n  (obj: T | null | undefined): O.Option\u003CT[K]> =>\n    obj != null && key in obj\n      ? O.some(obj[key] as T[K])\n      : O.none;\n\n\u002F\u002F Chain accesses with flatMap\nconst getDatabaseHost = (config: Config): O.Option\u003Cstring> =>\n  pipe(\n    O.some(config),\n    O.flatMap(prop('database')),\n    O.flatMap(prop('connection')),\n    O.flatMap(prop('host'))\n  );\n\n\u002F\u002F Extract with default\nconst host = pipe(\n  getDatabaseHost(config),\n  O.getOrElse(() => 'localhost')\n);\n```\n\n### Safe Array Access\n\n```typescript\nimport * as A from 'fp-ts\u002FArray';\nimport * as O from 'fp-ts\u002FOption';\nimport { pipe } from 'fp-ts\u002Ffunction';\n\n\u002F\u002F Imperative: throws if array is empty\nconst first = items[0]; \u002F\u002F Could be undefined!\n\n\u002F\u002F Safe: returns Option\nconst first = A.head(items); \u002F\u002F Option\u003CItem>\n\n\u002F\u002F Get first item's name, or default\nconst firstName = pipe(\n  items,\n  A.head,\n  O.map(item => item.name),\n  O.getOrElse(() => 'No items')\n);\n\n\u002F\u002F Safe lookup by index\nconst third = pipe(\n  items,\n  A.lookup(2),\n  O.map(item => item.name),\n  O.getOrElse(() => 'Not found')\n);\n```\n\n### Safe Record\u002FDictionary Access\n\n```typescript\nimport * as R from 'fp-ts\u002FRecord';\nimport * as O from 'fp-ts\u002FOption';\nimport { pipe } from 'fp-ts\u002Ffunction';\n\nconst users: Record\u003Cstring, User> = {\n  'user-1': { name: 'Alice', email: 'alice@example.com' },\n  'user-2': { name: 'Bob', email: 'bob@example.com' },\n};\n\n\u002F\u002F Imperative: could be undefined\nconst user = users['user-3']; \u002F\u002F User | undefined\n\n\u002F\u002F Safe: returns Option\nconst user = R.lookup('user-3')(users); \u002F\u002F Option\u003CUser>\n\n\u002F\u002F Get user email or default\nconst email = pipe(\n  users,\n  R.lookup('user-3'),\n  O.map(u => u.email),\n  O.getOrElse(() => 'unknown@example.com')\n);\n```\n\n### Combining Multiple Optional Values\n\n**The Task**: Get a user's display name, which requires both first and last name.\n\n```typescript\ninterface Profile {\n  firstName?: string;\n  lastName?: string;\n  nickname?: string;\n}\n\n\u002F\u002F Imperative\nfunction getDisplayName(profile: Profile): string {\n  if (profile.firstName && profile.lastName) {\n    return `${profile.firstName} ${profile.lastName}`;\n  }\n  if (profile.nickname) {\n    return profile.nickname;\n  }\n  return 'Anonymous';\n}\n\n\u002F\u002F Functional with Option\nimport * as O from 'fp-ts\u002FOption';\nimport { pipe } from 'fp-ts\u002Ffunction';\n\nconst getDisplayName = (profile: Profile): string =>\n  pipe(\n    \u002F\u002F Try full name first\n    O.Do,\n    O.bind('first', () => O.fromNullable(profile.firstName)),\n    O.bind('last', () => O.fromNullable(profile.lastName)),\n    O.map(({ first, last }) => `${first} ${last}`),\n    \u002F\u002F Fall back to nickname\n    O.alt(() => O.fromNullable(profile.nickname)),\n    \u002F\u002F Finally, default to Anonymous\n    O.getOrElse(() => 'Anonymous')\n  );\n```\n\n---\n\n## 6. Real-World Examples\n\n### Example 1: Transform API Response to UI-Ready Data\n\n```typescript\n\u002F\u002F API response\ninterface ApiOrder {\n  order_id: string;\n  customer: {\n    id: string;\n    full_name: string;\n  };\n  line_items: Array\u003C{\n    product_id: string;\n    product_name: string;\n    qty: number;\n    unit_price: number;\n  }>;\n  order_date: string;\n  status: 'pending' | 'processing' | 'shipped' | 'delivered';\n}\n\n\u002F\u002F What the UI needs\ninterface OrderSummary {\n  id: string;\n  customerName: string;\n  itemCount: number;\n  total: number;\n  formattedTotal: string;\n  date: string;\n  statusLabel: string;\n  statusColor: string;\n}\n\n\u002F\u002F Transformation\nconst STATUS_CONFIG: Record\u003Cstring, { label: string; color: string }> = {\n  pending: { label: 'Pending', color: 'yellow' },\n  processing: { label: 'Processing', color: 'blue' },\n  shipped: { label: 'Shipped', color: 'purple' },\n  delivered: { label: 'Delivered', color: 'green' },\n};\n\nconst formatCurrency = (cents: number): string =>\n  `$${(cents \u002F 100).toFixed(2)}`;\n\nconst formatDate = (iso: string): string =>\n  new Date(iso).toLocaleDateString('en-US', {\n    month: 'short',\n    day: 'numeric',\n    year: 'numeric',\n  });\n\nconst toOrderSummary = (order: ApiOrder): OrderSummary => {\n  const total = order.line_items.reduce(\n    (sum, item) => sum + item.qty * item.unit_price,\n    0\n  );\n\n  const status = STATUS_CONFIG[order.status] ?? STATUS_CONFIG.pending;\n\n  return {\n    id: order.order_id,\n    customerName: order.customer.full_name,\n    itemCount: order.line_items.reduce((sum, item) => sum + item.qty, 0),\n    total,\n    formattedTotal: formatCurrency(total),\n    date: formatDate(order.order_date),\n    statusLabel: status.label,\n    statusColor: status.color,\n  };\n};\n\n\u002F\u002F Transform all orders\nconst toOrderSummaries = (orders: ApiOrder[]): OrderSummary[] =>\n  orders.map(toOrderSummary);\n```\n\n### Example 2: Merge User Settings with Defaults\n\n```typescript\ninterface AppSettings {\n  theme: {\n    mode: 'light' | 'dark' | 'system';\n    primaryColor: string;\n    fontSize: 'small' | 'medium' | 'large';\n  };\n  notifications: {\n    email: boolean;\n    push: boolean;\n    sms: boolean;\n    frequency: 'immediate' | 'daily' | 'weekly';\n  };\n  privacy: {\n    showProfile: boolean;\n    showActivity: boolean;\n    allowAnalytics: boolean;\n  };\n}\n\ntype DeepPartial\u003CT> = {\n  [P in keyof T]?: T[P] extends object ? DeepPartial\u003CT[P]> : T[P];\n};\n\nconst DEFAULT_SETTINGS: AppSettings = {\n  theme: {\n    mode: 'system',\n    primaryColor: '#007bff',\n    fontSize: 'medium',\n  },\n  notifications: {\n    email: true,\n    push: true,\n    sms: false,\n    frequency: 'immediate',\n  },\n  privacy: {\n    showProfile: true,\n    showActivity: true,\n    allowAnalytics: true,\n  },\n};\n\nconst deepMergeSettings = (\n  defaults: AppSettings,\n  user: DeepPartial\u003CAppSettings>\n): AppSettings => ({\n  theme: { ...defaults.theme, ...user.theme },\n  notifications: { ...defaults.notifications, ...user.notifications },\n  privacy: { ...defaults.privacy, ...user.privacy },\n});\n\n\u002F\u002F Usage\nconst userPreferences: DeepPartial\u003CAppSettings> = {\n  theme: { mode: 'dark' },\n  notifications: { sms: true, frequency: 'daily' },\n};\n\nconst finalSettings = deepMergeSettings(DEFAULT_SETTINGS, userPreferences);\n```\n\n### Example 3: Group Orders by Customer with Totals\n\n```typescript\ninterface Order {\n  id: string;\n  customerId: string;\n  customerName: string;\n  items: Array\u003C{ name: string; price: number; quantity: number }>;\n  date: string;\n}\n\ninterface CustomerOrderSummary {\n  customerId: string;\n  customerName: string;\n  orderCount: number;\n  totalSpent: number;\n  orders: Order[];\n}\n\nconst calculateOrderTotal = (order: Order): number =>\n  order.items.reduce((sum, item) => sum + item.price * item.quantity, 0);\n\nconst groupOrdersByCustomer = (orders: Order[]): CustomerOrderSummary[] => {\n  const grouped = groupBy((order: Order) => order.customerId)(orders);\n\n  return Object.entries(grouped).map(([customerId, customerOrders]) => ({\n    customerId,\n    customerName: customerOrders[0].customerName,\n    orderCount: customerOrders.length,\n    totalSpent: customerOrders.reduce(\n      (sum, order) => sum + calculateOrderTotal(order),\n      0\n    ),\n    orders: customerOrders,\n  }));\n};\n```\n\n### Example 4: Safely Access Deeply Nested Config\n\n```typescript\ninterface AppConfig {\n  services?: {\n    api?: {\n      endpoints?: {\n        users?: string;\n        orders?: string;\n        products?: string;\n      };\n      auth?: {\n        type?: 'bearer' | 'basic' | 'oauth';\n        token?: string;\n      };\n    };\n    database?: {\n      primary?: {\n        host?: string;\n        port?: number;\n        name?: string;\n      };\n    };\n  };\n}\n\nimport * as O from 'fp-ts\u002FOption';\nimport { pipe } from 'fp-ts\u002Ffunction';\n\n\u002F\u002F Create a type-safe config accessor\nconst getConfigValue = \u003CT>(\n  config: AppConfig,\n  path: (config: AppConfig) => T | undefined,\n  defaultValue: T\n): T => path(config) ?? defaultValue;\n\n\u002F\u002F Usage with optional chaining (simplest)\nconst apiUsersEndpoint = getConfigValue(\n  config,\n  c => c.services?.api?.endpoints?.users,\n  '\u002Fapi\u002Fusers'\n);\n\n\u002F\u002F For more complex scenarios, use Option\nconst getEndpoint = (config: AppConfig, name: 'users' | 'orders' | 'products'): string =>\n  pipe(\n    O.fromNullable(config.services),\n    O.flatMap(s => O.fromNullable(s.api)),\n    O.flatMap(a => O.fromNullable(a.endpoints)),\n    O.flatMap(e => O.fromNullable(e[name])),\n    O.getOrElse(() => `\u002Fapi\u002F${name}`)\n  );\n\n\u002F\u002F Reusable pattern for multiple values\nconst getDbConfig = (config: AppConfig) => ({\n  host: config.services?.database?.primary?.host ?? 'localhost',\n  port: config.services?.database?.primary?.port ?? 5432,\n  name: config.services?.database?.primary?.name ?? 'app',\n});\n```\n\n---\n\n## 7. When to Use What\n\n### Use Native Methods When:\n\n- **Simple transformations**: `.map()`, `.filter()`, `.reduce()` are perfectly good\n- **No composition needed**: You're doing a one-off transformation\n- **Team familiarity**: Everyone knows native methods\n- **Optional chaining suffices**: `obj?.prop?.value ?? default` handles your null-safety needs\n\n```typescript\n\u002F\u002F Native is fine here\nconst activeUserNames = users\n  .filter(u => u.isActive)\n  .map(u => u.name);\n```\n\n### Use fp-ts When:\n\n- **Chaining operations that might fail**: Multiple steps where each can return nothing\n- **Composing transformations**: Building reusable transformation pipelines\n- **Type-safe error handling**: You want the compiler to track potential failures\n- **Complex data pipelines**: Many steps that benefit from explicit composition\n\n```typescript\n\u002F\u002F fp-ts shines here\nconst result = pipe(\n  users,\n  A.findFirst(u => u.id === userId),\n  O.flatMap(u => O.fromNullable(u.profile)),\n  O.flatMap(p => O.fromNullable(p.settings)),\n  O.map(s => s.theme),\n  O.getOrElse(() => 'default')\n);\n```\n\n### Use Custom Utilities When:\n\n- **Domain-specific operations**: `groupBy`, `countBy`, `sumBy` for your data\n- **Repeated patterns**: You find yourself writing the same transformation many times\n- **Team conventions**: Establishing consistent patterns across the codebase\n\n```typescript\n\u002F\u002F Custom utility pays off when used repeatedly\nconst revenueByRegion = sumBy(\n  (sale: Sale) => sale.region,\n  (sale: Sale) => sale.amount\n)(sales);\n```\n\n### Performance Considerations\n\n- **Chaining creates intermediate arrays**: `arr.filter().map()` creates one array, then another\n- **For hot paths, consider `reduce`**: One pass through the data\n- **Measure before optimizing**: The readability cost of optimization is often not worth it\n\n```typescript\n\u002F\u002F If performance matters (and you've measured!)\nconst result = items.reduce((acc, item) => {\n  if (item.isActive) {\n    acc.push(item.name.toUpperCase());\n  }\n  return acc;\n}, [] as string[]);\n\n\u002F\u002F vs the more readable (but 2-pass) version\nconst result = items\n  .filter(item => item.isActive)\n  .map(item => item.name.toUpperCase());\n```\n\n---\n\n## Summary\n\n| Task | Imperative | Functional | Recommendation |\n|------|-----------|------------|----------------|\n| Transform array elements | for loop with push | `.map()` | Use map |\n| Filter array | for loop with condition | `.filter()` | Use filter |\n| Accumulate values | for loop with accumulator | `.reduce()` | Use reduce for complex, loop for simple |\n| Group by key | for loop with object | `groupBy` utility | Create reusable utility |\n| Pick object fields | manual property copy | `pick` utility | Use spread for one-off, utility for repeated |\n| Merge objects | property-by-property | spread syntax | Use spread |\n| Deep merge | nested conditionals | recursive utility | Use utility or library |\n| Null-safe access | `if (x && x.y)` | `?.` or Option | Use `?.` for simple, Option for composition |\n| Normalize API data | nested loops | extraction functions | Break into composable functions |\n\n**The functional approach is better when:**\n- You need to compose operations\n- You want reusable transformations\n- You value explicit data flow over implicit state\n- Type safety for missing values matters\n\n**The imperative approach is acceptable when:**\n- The transformation is a one-off\n- The logic is simple and linear\n- Performance is critical and you've measured\n- The team is more comfortable with it\n\n## Limitations\n- Use this skill only when the task clearly matches the scope described above.\n- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.\n- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.\n","","imported","https:\u002F\u002Fgithub.com\u002Fsickn33\u002Fantigravity-awesome-skills","user_system_seed","SkillOPIC",true,115,731,"2026-05-16 13:18:33",{"id":8,"name":21,"slug":22,"icon":23,"description":24,"sort":25,"createdAt":26},"其他","other","mdi-page-next-outline","其他类型Skill",5,"2026-05-16 12:53:40",{"id":7,"name":28,"slug":29,"icon":30,"description":31,"moduleId":8,"sort":32,"skillCount":33,"createdAt":26},"职场发展","career","mdi-briefcase-outline","面试准备、简历优化、职业规划",4,575,[35],{"id":36,"skillId":4,"version":37,"fileName":38,"fileSize":39,"filePath":40,"fileHash":41,"manifest":42,"createdAt":19},"3fd53d8c-669f-4ba0-8f7f-02903ad73b06","1.0.0","fp-data-transforms.zip",10791,"uploads\u002Fskills\u002F2dd42e06-74cb-46cd-bb4d-fe0a11a7680c\u002Ffp-data-transforms.zip","2860265a15dc6ce7778a4bdc36f0784635bf7a3f84d8c4d20a5b4db7693aa775","[{\"path\":\"SKILL.md\",\"isDirectory\":false,\"size\":36922}]",{"code":44,"message":45,"data":46},200,"success",{"items":47,"stats":48,"page":51},[],{"averageRating":49,"totalRatings":49,"ratingCounts":50},0,[49,49,49,49,49],{"limit":52,"offset":49,"hasMore":53,"nextOffset":52,"ratedOnly":16},15,false]