Currying, Category Totals, and Fetch Retries
Medium · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
This three-part engineering exercise covers functional composition, resilient data aggregation, and asynchronous HTTP retries.
1. Fixed-Arity Currying (curry)
In ES6+ JavaScript, write curry(fn) to convert a function fn expecting N positional parameters (fn.length === N) into a chain of functions that accumulate arguments across calls and invoke fn as soon as at least N arguments have been supplied (for instance, currying calcVolume = (w, h, d) => w * h * d so curry(calcVolume)(2)(3)(5) returns 30).
2. Category Aggregation (group_by_category / groupByCategory)
Implement group_by_category(items) (the automated judge entry point in Python, corresponding to groupByCategory(items) in ES6+ JavaScript) to aggregate numeric amounts per category from a sequence of record dictionaries:
def group_by_category(items: List[Dict[str, object]]) -> Dict[str, int | float]:
Each dictionary in items may contain 'category' and 'value' entries. Apply these exact rules:
- If items is empty, return {}.
- Skip any record where 'category' is missing or None.
- Every non-None category encountered must appear as a key in the returned dictionary (initialized to 0), even if none of its records carry a valid numeric 'value'.
- Add item['value'] to that category's total only when it is a finite real number (int excluding bool, or float excluding NaN, +inf, and -inf). Missing 'value' keys, None, booleans (True / False), strings, NaN, and infinities contribute 0.
- Preserve exact case in category names, and do not mutate items or its element dictionaries.
3. Retrying HTTP Client (fetchData)
In ES6+ JavaScript, implement async function fetchData(url, retries) using the built-in fetch API to send an HTTP GET request to url. Whenever the request rejects with a network error or resolves with an HTTP status code other than 200, pause briefly (for example, using exponential backoff) and retry up to retries additional times before throwing an error.
Examples
Example 1
Input:
items = [
{"category": "cloud", "value": 120},
{"category": "storage", "value": 45},
{"category": "cloud", "value": 80},
{"category": "network", "value": 15}
]
Output: {"cloud": 200, "storage": 45, "network": 15}
Walk-through:
- The two "cloud" entries sum to 120 + 80 = 200.
- "storage" and "network" each have one numeric entry (45 and 15).
Example 2
Input:
items = [
{"category": "meals", "value": 12.5},
{"category": "meals", "value": 7.25},
{"category": "lodging", "value": "pending"},
{"category": "meals", "value": True}
]
Output: {"meals": 19.75, "lodging": 0}
Walk-through:
- "meals" adds 12.5 + 7.25 = 19.75 and ignores True because booleans are not treated as numeric amounts.
- "lodging" is initialized to 0, and "pending" is non-numeric so "lodging" stays at 0 in the returned dictionary.
Constraints
0 <= len(items) <= 10^5- Non-
None'category'values are case-sensitive strings;'value'may be omitted or hold any value (int,float,bool,str,None,NaN, or+-inf). - JavaScript utilities (
curry,groupByCategory,fetchData) use standard ES6+ withfetchavailable in the runtime environment andretries >= 0.
Step-by-step walkthrough
Understand all three parts and what the judge runs
This technical screen bundles three everyday software-engineering tasks:
- Part 1 (
curry): Turn a multi-argument function likecalcVolume(w, h, d)into a chain of calls likecurriedVolume(2)(3)(5). - Part 2 (
group_by_category/groupByCategory): Given a list of records, group them by category and sum their numeric values while handling empty inputs and non-numeric values safely. - Part 3 (
fetchData): Fetch JSON from a URL and retry failed or non-200HTTP responses up toretriestimes with a short backoff delay.
In a live JavaScript interview you write all three functions in ES6+. Here, the automated judge tests Part 2 in Python via
group_by_category(items), where each item dictionary uses the keys'category'and'value'. We will build Part 2 in Python first (alongside its JavaScript equivalent), then walk through Parts 1 and 3 in JavaScript so you are prepared for the full screen.- Part 1 (
Pin down the rules for missing and non-numeric data
Look closely at how Example 2 handles mixed and non-numeric data:
- Input:
[{'category': 'meals', 'value': 12.5}, {'category': 'meals', 'value': 7.25}, {'category': 'lodging', 'value': 'pending'}, {'category': 'meals', 'value': True}] - Output:
{'meals': 19.75, 'lodging': 0}
Notice that
'lodging'still appears in the output with a total of0even though'pending'is not a number, andTrueis ignored! That gives us four clear rules:- Empty input (
[]) returns an empty dictionary{}. - Every valid category appears in the output: the first time we see a category, we initialize its running sum to
0before checking whether its value is numeric. - Only finite real numbers count: integers and finite floating-point numbers are added.
None, missing'value'keys, strings like'pending'or'12', booleans (True/False),NaN("Not a Number"), and positive/negative infinity contribute0. - Missing category: if a record has no
'category'key (or'category'isNone), there is no bucket to place it in, so we skip that record.
- Input:
Why one dictionary pass beats scanning per category
A beginner's first instinct is often a two-phase loop: first collect every unique category name into a list, then loop over the entire
itemslist once for each category to add up its numbers. If there arenitems andkdistinct categories, scanning allnitemsktimes doesn * kchecks — which slows ton^2steps (10 billion checks for 100,000 unique items) when most categories are distinct.Instead, we can keep a single dictionary called
totals(an accumulator, meaning a running result we update one item at a time) and walk throughitemsjust once:Start: totals = {} Item 1: {'category': 'meals', 'value': 12.5} 'meals' is new -> totals['meals'] = 0 12.5 is finite -> totals['meals'] += 12.5 --> {'meals': 12.5} Item 2: {'category': 'meals', 'value': 7.25} 'meals' exists -> keep current total 7.25 is finite -> totals['meals'] += 7.25 --> {'meals': 19.75} Item 3: {'category': 'lodging', 'value': 'pending'} 'lodging' new -> totals['lodging'] = 0 'pending' skip -> add nothing --> {'meals': 19.75, 'lodging': 0} Item 4: {'category': 'meals', 'value': True} 'meals' exists -> True is bool, skip --> {'meals': 19.75, 'lodging': 0}Each item does one fast
O(1)dictionary check and at most one addition, bringing the total work down toO(n).Helper: filter for finite real numbers
Writing a small helper
is_valid_number(value)keeps our main loop clean and isolates two classic Python traps:boolis a subclass ofintin Python:isinstance(True, int)evaluates toTrue, andTrue + 5silently equals6! We must rejectboolbefore checkingint.NaNand infinity arefloatvalues:isinstance(float('nan'), float)isTrue, and adding oneNaNturns an entire category's sum intoNaN. Callingmath.isfinite(value)rejectsNaN,+inf, and-infin one step. Checkingintseparately first also avoidsOverflowErrorif a Python integer is too huge to fit in a 64-bit float.
import math def is_valid_number(value: object) -> bool: """Return True only for real ints and finite floats (excluding bools, NaN, and infinities).""" # Check bool BEFORE int: in Python, bool is a subclass of int, so isinstance(True, int) is True. if isinstance(value, bool): return False # Plain Python ints have arbitrary precision and are always finite; checking them before float # avoids OverflowError when math.isfinite tries to convert a huge int into a float. if isinstance(value, int): return True # Reject NaN, +inf, and -inf so a single bad float cannot corrupt an entire category sum. if isinstance(value, float): return math.isfinite(value) # Strings (like "pending" or "12"), None, lists, and dicts are not numeric amounts. return FalseGroup and sum in one pass (Python and JavaScript)
Now
group_by_categoryreads like plain English. Usingitem.get("category")anditem.get("value")instead of square bracketsitem["value"]safely returnsNoneinstead of crashing withKeyErrorwhen a key is missing:from typing import Dict, List def group_by_category(items: List[Dict[str, object]]) -> Dict[str, int | float]: # totals: maps each category name to its running numeric sum, e.g. {"cloud": 200, "lodging": 0}. totals: Dict[str, int | float] = {} for item in items: # Phase 1: Read the category safely; skip records that have no category key or None. category = item.get("category") if category is None: continue # Phase 2: Register every seen category at 0 before checking its value, so categories # whose values are all non-numeric still appear in the output (like "lodging": 0 in Example 2). if category not in totals: totals[category] = 0 # Phase 3: Add the value only when it is a finite real number; otherwise add nothing. raw_value = item.get("value") if is_valid_number(raw_value): totals[category] += raw_value return totalsIn JavaScript,
Array.prototype.reduceexpresses the exact same single-pass accumulator loop, andNumber.isFinite(value)returnstrueonly for finite primitive numbers (automatically rejecting strings, booleans,null,undefined,NaN, andInfinitywithout type coercion):function groupByCategory(items) { // Object.create(null) creates a clean dictionary with no inherited keys like "toString". return items.reduce((totals, item) => { if (!item || item.category === undefined || item.category === null) { return totals; } const { category, value } = item; if (!(category in totals)) { totals[category] = 0; } if (Number.isFinite(value)) { totals[category] += value; } return totals; }, Object.create(null)); }Why use
Object.create(null)instead of{}in JavaScript? A plain{}inherits methods liketoStringfromObject.prototype, so'toString' in {}is alreadytrue! WithoutObject.create(null), a category named"toString"would skip initialization to0and concatenate numbers onto the inherited function.Part 1 in JavaScript: currying a fixed-arity function
Currying transforms a function that expects
Narguments at once (calcVolume(2, 3, 5)) into a chain of functions that collect arguments piece by piece (curriedVolume(2)(3)(5)). In JavaScript,fn.lengthtells us how many fixed parametersfndeclares (its arity).Whenever the curried wrapper is called: - If we have collected at least
fn.lengtharguments, we have everythingfnneeds, so we callfnimmediately. - Otherwise, we return a brand-new function that waits for more arguments and combines the old array with the new ones ([...collectedArgs, ...nextArgs]).const curriedVolume = curry((w, h, d) => w * h * d); // fn.length === 3 curriedVolume(2) -> collected [2] (1 < 3) -> returns wrapper waiting for more |--- (3) -> collected [2, 3] (2 < 3) -> returns wrapper waiting for more |--- (5) -> collected [2, 3, 5] (3 >= 3) -> calls fn(2, 3, 5) -> 30Building a new array
[...collectedArgs, ...nextArgs]on every call (instead of mutating one shared array with.push()) ensures partial calls are safely reusable: if you saveconst doubleWidth = curriedVolume(2), callingdoubleWidth(3)(5)(30) will not pollute a later call todoubleWidth(4)(10)(80).function curry(fn) { return function curried(...collectedArgs) { // Once enough arguments have been gathered, invoke the original function. if (collectedArgs.length >= fn.length) { return fn.apply(this, collectedArgs); } // Otherwise return a regular function (preserving dynamic `this`) for the remaining arguments. return function (...nextArgs) { return curried.apply(this, [...collectedArgs, ...nextArgs]); }; }; }Part 3 in JavaScript: retrying fetch with exponential backoff
Two rules about the browser/Node
fetchAPI catch many candidates off guard:fetchdoes not throw on HTTP 404 or 500:await fetch(url)rejects only when no HTTP response was received at all (for example, DNS failure, dropped Wi-Fi, or refused connection). When the server replies with status500or404,fetchresolves normally! We must checkresponse.status === 200ourselves.- "Retry up to
retriestimes" meansretries + 1total attempts: 1 initial request plus up toretriesfollow-up attempts.
Between failed attempts, waiting with exponential backoff (doubling the wait time each retry:
100 ms,200 ms,400 ms, ...) gives an overloaded server breathing room to recover instead of hammering it immediately:retries = 2, baseDelayMs = 100: Attempt 0 (initial) --fails--> wait 100 ms --> Attempt 1 (retry 1) --fails--> wait 200 ms --> Attempt 2 (retry 2)const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); async function fetchData(url, retries = 3, baseDelayMs = 100) { const maxRetries = Math.max(0, retries); let lastError = null; for (let attempt = 0; attempt <= maxRetries; attempt++) { // Wait before each retry (attempt 1 waits baseDelayMs, attempt 2 waits 2 * baseDelayMs, etc.). if (attempt > 0) { const backoffMs = baseDelayMs * (2 ** (attempt - 1)); await delay(backoffMs); } let response; try { response = await fetch(url); // GET is the default HTTP method } catch (networkError) { // Network-level failure (offline, DNS failure, connection reset): record and retry. lastError = networkError; continue; } if (response.status === 200) { // Parse JSON outside the retry try/catch: if a 200 body isn't valid JSON, retrying won't fix it. return await response.json(); } lastError = new Error(`Unexpected HTTP status ${response.status}`); } throw new Error( `GET ${url} failed after ${maxRetries + 1} attempts`, { cause: lastError } ); }Complete Python solution
Here is the complete Python implementation tested by the automated judge for Part 2:
from typing import Any, Dict, List, Optional, Set, Tuple import math def is_valid_number(value: object) -> bool: """Return True only for real ints and finite floats (excluding bools, NaN, and infinities).""" # Check bool BEFORE int: in Python, bool is a subclass of int, so isinstance(True, int) is True. if isinstance(value, bool): return False # Plain Python ints have arbitrary precision and are always finite; checking them before float # avoids OverflowError when math.isfinite tries to convert a huge int into a float. if isinstance(value, int): return True # Reject NaN, +inf, and -inf so a single bad float cannot corrupt an entire category sum. if isinstance(value, float): return math.isfinite(value) # Strings (like "pending" or "12"), None, lists, and dicts are not numeric amounts. return False def group_by_category(items: List[Dict[str, object]]) -> Dict[str, int | float]: # totals: maps each category name to its running numeric sum, e.g. {"cloud": 200, "lodging": 0}. totals: Dict[str, int | float] = {} for item in items: # Phase 1: Read the category safely; skip records that have no category key or None. category = item.get("category") if category is None: continue # Phase 2: Register every seen category at 0 before checking its value, so categories # whose values are all non-numeric still appear in the output (like "lodging": 0 in Example 2). if category not in totals: totals[category] = 0 # Phase 3: Add the value only when it is a finite real number; otherwise add nothing. raw_value = item.get("value") if is_valid_number(raw_value): totals[category] += raw_value return totals✅ Submit now — all tests should pass.
Intuition & how it works
Think of group_by_category like sorting a stack of expense receipts into labeled envelopes: the first time you see a receipt labeled "lodging", you grab a fresh "lodging" envelope and write 0 on the front, and then if the receipt has a real numeric amount on it, you add that amount to the number on the envelope. That single dictionary of running sums is an accumulator (a data structure that builds up the final answer one item at a time during a single pass). The other two parts of the exercise follow similarly clean mental models: currying (converting a multi-argument function into a chain of functions that remember arguments collected so far) works like filling out a 3-box stamp card that triggers the reward as soon as the third box is stamped, and fetchData works like redialing a busy phone line up to retries extra times while doubling your pause between calls (exponential backoff, a retry strategy that waits 1x, 2x, 4x, ... longer after each failure so an overloaded server has time to recover).
Why do naive approaches get into trouble? For grouping, collecting unique categories first and rescanning the entire list once per category takes n * k steps for n items and k categories, which degrades to quadratic O(n^2) time when most categories are unique. Even in a single pass, blindly adding totals[cat] += value crashes in Python on strings/missing keys, turns an entire sum into NaN ("Not a Number", a special floating-point value where NaN + 10 is still NaN) on bad floats, or concatenates strings like "0pending" in JavaScript. Checking types carefully after registering each category at 0 handles messy inputs cleanly in one pass.
Here is how group_by_category processes the 4 mixed records from Example 2 step by step:
Input items:
1. {'category': 'meals', 'value': 12.5}
2. {'category': 'meals', 'value': 7.25}
3. {'category': 'lodging', 'value': 'pending'}
4. {'category': 'meals', 'value': True}
Step-by-step trace:
Item 1 ('meals', 12.5) -> 'meals' is new: totals['meals'] = 0; +12.5 -> {'meals': 12.5}
Item 2 ('meals', 7.25) -> 'meals' exists; 12.5 + 7.25 = 19.75 -> {'meals': 19.75}
Item 3 ('lodging', 'pending') -> 'lodging' is new: 0; 'pending' skipped -> {'meals': 19.75, 'lodging': 0}
Item 4 ('meals', True) -> 'meals' exists; True is bool, skipped -> {'meals': 19.75, 'lodging': 0}
Complexity
group_by_categorytime —O(n): We loop through theninput dictionaries once, performing anO(1)average-time hash-table lookup, a constant-time type check, and at most one addition per item.group_by_categoryspace —O(k): Thetotalsdictionary stores one entry for each of thekdistinct categories (k <= n), and we never copy or mutate the input list.currytime and space —O(N^2)acrossNsingle-argument calls: For a function of arityN(meaningNdeclared parameters), each partial call copies the arguments gathered so far into a new array (1 + 2 + ... + N), which is tiny becauseNis just a function's parameter count.fetchDataattempts and wait time — at mostretries + 1requests: Total sleep time before giving up sums tobaseDelayMs * (1 + 2 + ... + 2^(retries - 1)) = baseDelayMs * (2^retries - 1)(for example,100 + 200 + 400 = 700 mswhenretries = 3andbaseDelayMs = 100).
Edge cases
- Empty input (
[]): Loops zero times and returns{}. - Category with only non-numeric values: Initializing
totals[category] = 0before checkingraw_valueensures categories like'lodging'in Example 2 still appear with total0. Noneor missing'value'key:item.get("value")returnsNone, whichis_valid_numberrejects cleanly without raisingKeyError.- Booleans (
TrueandFalse): Explicitly rejected first becauseboolsubclassesintin Python (isinstance(True, int)isTrue), matching JavaScript wheretypeof true === "boolean". NaN,inf, and-inf: Rejected bymath.isfinite(andNumber.isFinitein JavaScript) so a single corrupted float cannot poison a category's entire sum.- Missing or
Nonecategory: Skipped safely because there is no category key to group the record under. - Case sensitivity and negative values:
'A'and'a'remain distinct keys, and negative numbers subtract from the running total naturally. fetchDatawithretries = 0: Runsattempt = 0once and throws immediately if that single request fails.
Common mistakes
- Using
isinstance(value, (int, float))alone in Python: CountsTrueas1and allowsfloat('nan')orfloat('inf')into the sum. - Initializing the category only inside
if is_valid_number(value): Silently drops categories whose values are all invalid instead of reporting0as Example 2 requires. - Mutating a shared array inside
curry: Pushing arguments into one outerargs = []array breaks partial reuse (const w2 = curriedVolume(2); w2(3)(5); w2(4)(10)would still contain3and5). Always build a fresh array[...collectedArgs, ...nextArgs]. - Using an arrow function for the inner curried wrapper when forwarding
this: An arrow function locksthisto the outer call rather than the caller of the next step; usingreturn function (...nextArgs) { ... }preserves dynamicthisat every step. - JavaScript prototype collisions on
{}: Using{}withcategory in totalstreats inheritedObject.prototypenames like"toString"or"constructor"as already initialized. UseObject.create(null)or aMap. - Assuming
fetchthrows on HTTP 404 or 500:fetchonly rejects on network failures; forgetting to checkresponse.status === 200treats server error pages as successful responses. - Off-by-one retry count: Looping
attempt < retriesinstead ofattempt <= retriesperformsretriestotal attempts instead of 1 initial request plusretriesretries.
Alternative approaches
collections.defaultdict(int)in Python: Automatically starts unseen keys at0, though you must still touchtotals[category](for exampletotals[category] += 0) when a record's value is non-numeric so that zero-sum categories are not omitted.- JavaScript
Map:new Map()avoidsObject.prototypekey collisions completely and preserves insertion order; callObject.fromEntries(map)at the end if the caller expects a plain object.
Follow-up questions
- How could you design
currywhen the target function accepts a variable number of arguments rather than a fixed parameter count? A variadic function (a function accepting any number of arguments, such as(...nums) => ...) hasfn.length === 0, socurrycannot automatically know when the caller is done passing arguments. The cleanest solution is an explicit empty-call terminator()where passing one or more arguments returns a new curried function with[...collected, ...args], and calling()with zero arguments finally invokesfn(...collected)(for example,curriedMultiplyAll(2)(3)(5)()). Alternatively, if the caller knows the desired count at setup time, accept an explicit parametercurry(fn, expectedArity)instead of readingfn.length. - Why does cloning nested objects during large-scale list transformations hurt runtime and memory, and how do you avoid it? A deep copy duplicates an object and every nested object or array inside it, costing
O(total_size)time and doubling peak memory while both copies exist. Doing a copy on every step of a loop — such as writingitems.reduce((acc, item) => ({ ...acc, [item.category]: ... }), {})— copies allkkeys on every single item, turning anO(n)aggregation intoO(n * k)work and creating massive garbage-collection pauses. In addition,JSON.parse(JSON.stringify(obj))dropsundefinedfields, turnsDateinstances into strings, and throws on circular references, whilestructuredClone(obj)handles dates and cycles safely but still pays the full allocation cost; reading the input without mutating it and building one freshtotalsdictionary avoids copying altogether. - What strategy lets you unit-test retry logic and backoff timing in
fetchDatadeterministically without hitting the network? Replacefetchwith a mock (a controllable fake function used in tests that records how it was called and returns scripted responses) either by injectingfetchImpl = fetchas an optional parameter or by stubbingglobalThis.fetchin a test runner like Jest or Vitest. You can then test every branch deterministically: (1) immediate200returns parsed JSON after 1 call, (2) a network rejection followed by a500followed by a200succeeds after 3 calls, and (3) persistent500responses throw afterretries + 1calls. PassbaseDelayMs = 0or use fake timers (jest.useFakeTimers()) so backoff sleeps run in microseconds instead of slowing down your test suite.
Follow-up questions
- How could you design `curry` when the target function accepts a variable number of arguments rather than a fixed parameter count?
- Why does cloning nested objects during large-scale list transformations hurt runtime and memory, and how do you avoid it?
- What strategy lets you unit-test retry logic and backoff timing in `fetchData` deterministically without hitting the network?
Similar questions
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance
- Increment Fixed-Size Digit Array by One
- Increment Digit Array