This skill helps you transform arrays and objects with functional patterns, enabling safer access, grouping, and normalization for real-world data.
npx playbooks add skill whatiskadudoing/fp-ts-skills --skill fp-data-transforms
This 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.
---
---
Array operations are the bread and butter of data transformation. Let's replace verbose loops with expressive, chainable operations.
The Task: Convert an array of prices from cents to dollars.
const pricesInCents = [999, 1499, 2999, 4999];
function convertToDollars(prices: number[]): number[] {
const result: number[] = [];
for (let i = 0; i < prices.length; i++) {
result.push(prices[i] / 100);
}
return result;
}
const dollars = convertToDollars(pricesInCents);
// [9.99, 14.99, 29.99, 49.99]
const pricesInCents = [999, 1499, 2999, 4999];
const toDollars = (cents: number): number => cents / 100;
const dollars = pricesInCents.map(toDollars);
// [9.99, 14.99, 29.99, 49.99]
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.
The Task: Get all active users from a list.
interface User {
id: string;
name: string;
isActive: boolean;
}
function getActiveUsers(users: User[]): User[] {
const result: User[] = [];
for (const user of users) {
if (user.isActive) {
result.push(user);
}
}
return result;
}
const isActive = (user: User): boolean => user.isActive;
const activeUsers = users.filter(isActive);
// Or inline for simple predicates
const activeUsers = users.filter(user => user.isActive);
Why functional is better here: The predicate (isActive) is separated from the iteration logic. You can reuse, test, and compose predicates independently.
The Task: Calculate the total price of items in a cart.
interface CartItem {
name: string;
price: number;
quantity: number;
}
function calculateTotal(items: CartItem[]): number {
let total = 0;
for (const item of items) {
total += item.price * item.quantity;
}
return total;
}
const calculateTotal = (items: CartItem[]): number =>
items.reduce(
(total, item) => total + item.price * item.quantity,
0
);
// Or break out the line total calculation
const lineTotal = (item: CartItem): number => item.price * item.quantity;
const calculateTotal = (items: CartItem[]): number =>
items.map(lineTotal).reduce((a, b) => a + b, 0);
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.
The Task: Get the names of all active premium users, sorted alphabetically.
interface User {
id: string;
name: string;
isActive: boolean;
tier: 'free' | 'premium';
}
function getActivePremiumNames(users: User[]): string[] {
const result: string[] = [];
for (const user of users) {
if (user.isActive && user.tier === 'premium') {
result.push(user.name);
}
}
result.sort((a, b) => a.localeCompare(b));
return result;
}
const getActivePremiumNames = (users: User[]): string[] =>
users
.filter(user => user.isActive)
.filter(user => user.tier === 'premium')
.map(user => user.name)
.sort((a, b) => a.localeCompare(b));
// Or with named predicates for reuse
const isActive = (user: User): boolean => user.isActive;
const isPremium = (user: User): boolean => user.tier === 'premium';
const getName = (user: User): string => user.name;
const alphabetically = (a: string, b: string): number => a.localeCompare(b);
const getActivePremiumNames = (users: User[]): string[] =>
users
.filter(isActive)
.filter(isPremium)
.map(getName)
.sort(alphabetically);
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.
fp-ts provides additional array utilities with better composition support:
import * as A from 'fp-ts/Array';
import * as O from 'fp-ts/Option';
import { pipe } from 'fp-ts/function';
// Safe head (first element)
const first = pipe(
[1, 2, 3],
A.head
); // Some(1)
const firstOfEmpty = pipe(
[] as number[],
A.head
); // None
// Safe lookup by index
const third = pipe(
['a', 'b', 'c', 'd'],
A.lookup(2)
); // Some('c')
// Find with predicate
const found = pipe(
users,
A.findFirst(user => user.id === 'abc123')
); // Option<User>
// Partition into two groups
const [inactive, active] = pipe(
users,
A.partition(user => user.isActive)
);
// Take first N elements
const topThree = pipe(
sortedScores,
A.takeLeft(3)
);
// Unique values
const uniqueTags = pipe(
allTags,
A.uniq({ equals: (a, b) => a === b })
);
---
Objects need reshaping constantly: picking fields, omitting sensitive data, merging settings, and updating nested values.
The Task: Extract only the public fields from a user object.
interface User {
id: string;
name: string;
email: string;
passwordHash: string;
internalNotes: string;
}
function getPublicUser(user: User): { id: string; name: string; email: string } {
return {
id: user.id,
name: user.name,
email: user.email,
};
}
// Generic pick utility
const pick = <T extends object, K extends keyof T>(
keys: K[]
) => (obj: T): Pick<T, K> =>
keys.reduce(
(result, key) => {
result[key] = obj[key];
return result;
},
{} as Pick<T, K>
);
const getPublicUser = pick<User, 'id' | 'name' | 'email'>(['id', 'name', 'email']);
const publicUser = getPublicUser(user);
Why functional is better here: The pick utility is reusable across your codebase. Type safety ensures you can only pick keys that exist.
The Task: Remove sensitive fields before logging.
function sanitizeForLogging(user: User): Omit<User, 'passwordHash' | 'internalNotes'> {
const { passwordHash, internalNotes, ...safe } = user;
return safe;
}
// Generic omit utility
const omit = <T extends object, K extends keyof T>(
keys: K[]
) => (obj: T): Omit<T, K> => {
const result = { ...obj };
for (const key of keys) {
delete result[key];
}
return result as Omit<T, K>;
};
const sanitizeForLogging = omit<User, 'passwordHash' | 'internalNotes'>([
'passwordHash',
'internalNotes',
]);
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.
The Task: Merge user settings with defaults.
interface Settings {
theme: 'light' | 'dark';
fontSize: number;
notifications: boolean;
language: string;
}
function mergeSettings(
defaults: Settings,
userSettings: Partial<Settings>
): Settings {
return {
theme: userSettings.theme !== undefined ? userSettings.theme : defaults.theme,
fontSize: userSettings.fontSize !== undefined ? userSettings.fontSize : defaults.fontSize,
notifications: userSettings.notifications !== undefined
? userSettings.notifications
: defaults.notifications,
language: userSettings.language !== undefined ? userSettings.language : defaults.language,
};
}
const mergeSettings = (
defaults: Settings,
userSettings: Partial<Settings>
): Settings => ({
...defaults,
...userSettings,
});
// Usage
const defaults: Settings = {
theme: 'light',
fontSize: 14,
notifications: true,
language: 'en',
};
const userPrefs: Partial<Settings> = {
theme: 'dark',
fontSize: 16,
};
const finalSettings = mergeSettings(defaults, userPrefs);
// { theme: 'dark', fontSize: 16, notifications: true, language: 'en' }
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.
The Task: Merge nested configuration objects.
interface Config {
api: {
baseUrl: string;
timeout: number;
retries: number;
};
ui: {
theme: string;
animations: boolean;
};
}
function deepMerge(
target: Config,
source: Partial<Config>
): Config {
const result = { ...target };
if (source.api) {
result.api = { ...target.api, ...source.api };
}
if (source.ui) {
result.ui = { ...target.ui, ...source.ui };
}
return result;
}
// Generic deep merge for one level of nesting
const deepMerge = <T extends Record<string, object>>(
target: T,
source: { [K in keyof T]?: Partial<T[K]> }
): T => {
const result = { ...target };
for (const key of Object.keys(source) as Array<keyof T>) {
if (source[key] !== undefined) {
result[key] = { ...target[key], ...source[key] };
}
}
return result;
};
// Usage
const defaultConfig: Config = {
api: { baseUrl: 'https://api.example.com', timeout: 5000, retries: 3 },
ui: { theme: 'light', animations: true },
};
const customConfig = deepMerge(defaultConfig, {
api: { timeout: 10000 },
ui: { theme: 'dark' },
});
// api.baseUrl preserved, api.timeout overridden
// ui.theme overridden, ui.animations preserved
The Task: Update a deeply nested value without mutation.
interface State {
user: {
profile: {
settings: {
theme: string;
};
};
};
}
function updateTheme(state: State, newTheme: string): void {
state.user.profile.settings.theme = newTheme; // Mutation!
}
// Manual spread nesting
const updateTheme = (state: State, newTheme: string): State => ({
...state,
user: {
...state.user,
profile: {
...state.user.profile,
settings: {
...state.user.profile.settings,
theme: newTheme,
},
},
},
});
// With a lens-like helper
const updatePath = <T, V>(
obj: T,
path: string[],
value: V
): T => {
if (path.length === 0) return value as unknown as T;
const [head, ...rest] = path;
return {
...obj,
[head]: updatePath((obj as Record<string, unknown>)[head], rest, value),
} as T;
};
const newState = updatePath(state, ['user', 'profile', 'settings', 'theme'], 'dark');
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.
---
API responses rarely match the shape your app needs. Normalization transforms nested, denormalized data into flat, indexed structures.
The Task: Transform a nested API response into a normalized state.
interface ApiResponse {
orders: Array<{
id: string;
customerId: string;
customerName: string;
customerEmail: string;
items: Array<{
productId: string;
productName: string;
quantity: number;
price: number;
}>;
total: number;
status: string;
}>;
}
interface NormalizedState {
orders: {
byId: Record<string, Order>;
allIds: string[];
};
customers: {
byId: Record<string, Customer>;
allIds: string[];
};
products: {
byId: Record<string, Product>;
allIds: string[];
};
}
interface Order {
id: string;
customerId: string;
itemIds: string[];
total: number;
status: string;
}
interface Customer {
id: string;
name: string;
email: string;
}
interface Product {
id: string;
name: string;
price: number;
}
function normalizeApiResponse(response: ApiResponse): NormalizedState {
const state: NormalizedState = {
orders: { byId: {}, allIds: [] },
customers: { byId: {}, allIds: [] },
products: { byId: {}, allIds: [] },
};
for (const order of response.orders) {
// Extract customer
if (!state.customers.byId[order.customerId]) {
state.customers.byId[order.customerId] = {
id: order.customerId,
name: order.customerName,
email: order.customerEmail,
};
state.customers.allIds.push(order.customerId);
}
// Extract products and build item IDs
const itemIds: string[] = [];
for (const item of order.items) {
if (!state.products.byId[item.productId]) {
state.products.byId[item.productId] = {
id: item.productId,
name: item.productName,
price: item.price,
};
state.products.allIds.push(item.productId);
}
itemIds.push(item.productId);
}
// Add normalized order
state.orders.byId[order.id] = {
id: order.id,
customerId: order.customerId,
itemIds,
total: order.total,
status: order.status,
};
state.orders.allIds.push(order.id);
}
return state;
}
import { pipe } from 'fp-ts/function';
import * as A from 'fp-ts/Array';
import * as R from 'fp-ts/Record';
// Helper to create normalized collection
interface NormalizedCollection<T extends { id: string }> {
byId: Record<string, T>;
allIds: string[];
}
const createNormalizedCollection = <T extends { id: string }>(
items: T[]
): NormalizedCollection<T> => ({
byId: pipe(
items,
A.reduce({} as Record<string, T>, (acc, item) => ({
...acc,
[item.id]: item,
}))
),
allIds: items.map(item => item.id),
});
// Extract entities
const extractCustomers = (orders: ApiResponse['orders']): Customer[] =>
pipe(
orders,
A.map(order => ({
id: order.customerId,
name: order.customerName,
email: order.customerEmail,
})),
A.uniq({ equals: (a, b) => a.id === b.id })
);
const extractProducts = (orders: ApiResponse['orders']): Product[] =>
pipe(
orders,
A.flatMap(order => order.items),
A.map(item => ({
id: item.productId,
name: item.productName,
price: item.price,
})),
A.uniq({ equals: (a, b) => a.id === b.id })
);
const extractOrders = (orders: ApiResponse['orders']): Order[] =>
orders.map(order => ({
id: order.id,
customerId: order.customerId,
itemIds: order.items.map(item => item.productId),
total: order.total,
status: order.status,
}));
// Compose into final normalization
const normalizeApiResponse = (response: ApiResponse): NormalizedState => ({
orders: createNormalizedCollection(extractOrders(response.orders)),
customers: createNormalizedCollection(extractCustomers(response.orders)),
products: createNormalizedCollection(extractProducts(response.orders)),
});
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.
The Task: Convert API data to what your components need.
// API gives you this
interface ApiUser {
user_id: string;
first_name: string;
last_name: string;
email_address: string;
created_at: string; // ISO string
avatar_url: string | null;
}
// Components need this
interface DisplayUser {
id: string;
fullName: string;
email: string;
memberSince: string; // "Jan 2024"
avatarUrl: string; // With fallback
}
const formatDate = (isoString: string): string => {
const date = new Date(isoString);
return date.toLocaleDateString('en-US', { month: 'short', year: 'numeric' });
};
const DEFAULT_AVATAR = 'https://example.com/default-avatar.png';
const toDisplayUser = (apiUser: ApiUser): DisplayUser => ({
id: apiUser.user_id,
fullName: `${apiUser.first_name} ${apiUser.last_name}`,
email: apiUser.email_address,
memberSince: formatDate(apiUser.created_at),
avatarUrl: apiUser.avatar_url ?? DEFAULT_AVATAR,
});
// Transform array of users
const toDisplayUsers = (apiUsers: ApiUser[]): DisplayUser[] =>
apiUsers.map(toDisplayUser);
---
Grouping and aggregating data is essential for reports, dashboards, and analytics.
The Task: Group orders by customer.
interface Order {
id: string;
customerId: string;
total: number;
date: string;
}
function groupByCustomer(orders: Order[]): Record<string, Order[]> {
const result: Record<string, Order[]> = {};
for (const order of orders) {
if (!result[order.customerId]) {
result[order.customerId] = [];
}
result[order.customerId].push(order);
}
return result;
}
// Generic groupBy utility
const groupBy = <T, K extends string | number>(
getKey: (item: T) => K
) => (items: T[]): Record<K, T[]> =>
items.reduce(
(groups, item) => {
const key = getKey(item);
return {
...groups,
[key]: [...(groups[key] || []), item],
};
},
{} as Record<K, T[]>
);
// Usage
const groupByCustomer = groupBy<Order, string>(order => order.customerId);
const ordersByCustomer = groupByCustomer(orders);
// Or inline
const ordersByStatus = groupBy((order: Order) => order.status)(orders);
Using fp-ts NonEmptyArray.groupBy:
import * as NEA from 'fp-ts/NonEmptyArray';
import { pipe } from 'fp-ts/function';
// NEA.groupBy guarantees non-empty arrays in result
const ordersByCustomer = pipe(
orders as NEA.NonEmptyArray<Order>, // Must be non-empty
NEA.groupBy(order => order.customerId)
); // Record<string, NonEmptyArray<Order>>
The Task: Count orders by status.
function countByStatus(orders: Order[]): Record<string, number> {
const counts: Record<string, number> = {};
for (const order of orders) {
counts[order.status] = (counts[order.status] || 0) + 1;
}
return counts;
}
// Generic countBy utility
const countBy = <T, K extends string>(
getKey: (item: T) => K
) => (items: T[]): Record<K, number> =>
items.reduce(
(counts, item) => {
const key = getWeekly roundup of top Claude Code skills, MCP servers, and AI coding tips.