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+ with fetch available in the runtime environment and retries >= 0.

Step-by-step walkthrough

  1. Understand all three parts and what the judge runs

    This technical screen bundles three everyday software-engineering tasks:

    1. Part 1 (curry): Turn a multi-argument function like calcVolume(w, h, d) into a chain of calls like curriedVolume(2)(3)(5).
    2. 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.
    3. Part 3 (fetchData): Fetch JSON from a URL and retry failed or non-200 HTTP responses up to retries times 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.

  2. 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 of 0 even though 'pending' is not a number, and True is 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 0 before 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 contribute 0.
    • Missing category: if a record has no 'category' key (or 'category' is None), there is no bucket to place it in, so we skip that record.
  3. 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 items list once for each category to add up its numbers. If there are n items and k distinct categories, scanning all n items k times does n * k checks — which slows to n^2 steps (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 through items just 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 to O(n).

  4. 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:

    1. bool is a subclass of int in Python: isinstance(True, int) evaluates to True, and True + 5 silently equals 6! We must reject bool before checking int.
    2. NaN and infinity are float values: isinstance(float('nan'), float) is True, and adding one NaN turns an entire category's sum into NaN. Calling math.isfinite(value) rejects NaN, +inf, and -inf in one step. Checking int separately first also avoids OverflowError if 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 False
    
  5. Group and sum in one pass (Python and JavaScript)

    Now group_by_category reads like plain English. Using item.get("category") and item.get("value") instead of square brackets item["value"] safely returns None instead of crashing with KeyError when 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 totals
    

    In JavaScript, Array.prototype.reduce expresses the exact same single-pass accumulator loop, and Number.isFinite(value) returns true only for finite primitive numbers (automatically rejecting strings, booleans, null, undefined, NaN, and Infinity without 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 like toString from Object.prototype, so 'toString' in {} is already true! Without Object.create(null), a category named "toString" would skip initialization to 0 and concatenate numbers onto the inherited function.

  6. Part 1 in JavaScript: currying a fixed-arity function

    Currying transforms a function that expects N arguments at once (calcVolume(2, 3, 5)) into a chain of functions that collect arguments piece by piece (curriedVolume(2)(3)(5)). In JavaScript, fn.length tells us how many fixed parameters fn declares (its arity).

    Whenever the curried wrapper is called: - If we have collected at least fn.length arguments, we have everything fn needs, so we call fn immediately. - 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) -> 30
    

    Building a new array [...collectedArgs, ...nextArgs] on every call (instead of mutating one shared array with .push()) ensures partial calls are safely reusable: if you save const doubleWidth = curriedVolume(2), calling doubleWidth(3)(5) (30) will not pollute a later call to doubleWidth(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]);
        };
      };
    }
    
  7. Part 3 in JavaScript: retrying fetch with exponential backoff

    Two rules about the browser/Node fetch API catch many candidates off guard:

    1. fetch does 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 status 500 or 404, fetch resolves normally! We must check response.status === 200 ourselves.
    2. "Retry up to retries times" means retries + 1 total attempts: 1 initial request plus up to retries follow-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 }
      );
    }
    
  8. 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_category time — O(n): We loop through the n input dictionaries once, performing an O(1) average-time hash-table lookup, a constant-time type check, and at most one addition per item.
  • group_by_category space — O(k): The totals dictionary stores one entry for each of the k distinct categories (k <= n), and we never copy or mutate the input list.
  • curry time and space — O(N^2) across N single-argument calls: For a function of arity N (meaning N declared parameters), each partial call copies the arguments gathered so far into a new array (1 + 2 + ... + N), which is tiny because N is just a function's parameter count.
  • fetchData attempts and wait time — at most retries + 1 requests: Total sleep time before giving up sums to baseDelayMs * (1 + 2 + ... + 2^(retries - 1)) = baseDelayMs * (2^retries - 1) (for example, 100 + 200 + 400 = 700 ms when retries = 3 and baseDelayMs = 100).

Edge cases

  • Empty input ([]): Loops zero times and returns {}.
  • Category with only non-numeric values: Initializing totals[category] = 0 before checking raw_value ensures categories like 'lodging' in Example 2 still appear with total 0.
  • None or missing 'value' key: item.get("value") returns None, which is_valid_number rejects cleanly without raising KeyError.
  • Booleans (True and False): Explicitly rejected first because bool subclasses int in Python (isinstance(True, int) is True), matching JavaScript where typeof true === "boolean".
  • NaN, inf, and -inf: Rejected by math.isfinite (and Number.isFinite in JavaScript) so a single corrupted float cannot poison a category's entire sum.
  • Missing or None category: 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.
  • fetchData with retries = 0: Runs attempt = 0 once and throws immediately if that single request fails.

Common mistakes

  • Using isinstance(value, (int, float)) alone in Python: Counts True as 1 and allows float('nan') or float('inf') into the sum.
  • Initializing the category only inside if is_valid_number(value): Silently drops categories whose values are all invalid instead of reporting 0 as Example 2 requires.
  • Mutating a shared array inside curry: Pushing arguments into one outer args = [] array breaks partial reuse (const w2 = curriedVolume(2); w2(3)(5); w2(4)(10) would still contain 3 and 5). Always build a fresh array [...collectedArgs, ...nextArgs].
  • Using an arrow function for the inner curried wrapper when forwarding this: An arrow function locks this to the outer call rather than the caller of the next step; using return function (...nextArgs) { ... } preserves dynamic this at every step.
  • JavaScript prototype collisions on {}: Using {} with category in totals treats inherited Object.prototype names like "toString" or "constructor" as already initialized. Use Object.create(null) or a Map.
  • Assuming fetch throws on HTTP 404 or 500: fetch only rejects on network failures; forgetting to check response.status === 200 treats server error pages as successful responses.
  • Off-by-one retry count: Looping attempt < retries instead of attempt <= retries performs retries total attempts instead of 1 initial request plus retries retries.

Alternative approaches

  • collections.defaultdict(int) in Python: Automatically starts unseen keys at 0, though you must still touch totals[category] (for example totals[category] += 0) when a record's value is non-numeric so that zero-sum categories are not omitted.
  • JavaScript Map: new Map() avoids Object.prototype key collisions completely and preserves insertion order; call Object.fromEntries(map) at the end if the caller expects a plain object.

Follow-up questions

  • How could you design curry when 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) => ...) has fn.length === 0, so curry cannot 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 invokes fn(...collected) (for example, curriedMultiplyAll(2)(3)(5)()). Alternatively, if the caller knows the desired count at setup time, accept an explicit parameter curry(fn, expectedArity) instead of reading fn.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 writing items.reduce((acc, item) => ({ ...acc, [item.category]: ... }), {}) — copies all k keys on every single item, turning an O(n) aggregation into O(n * k) work and creating massive garbage-collection pauses. In addition, JSON.parse(JSON.stringify(obj)) drops undefined fields, turns Date instances into strings, and throws on circular references, while structuredClone(obj) handles dates and cycles safely but still pays the full allocation cost; reading the input without mutating it and building one fresh totals dictionary avoids copying altogether.
  • What strategy lets you unit-test retry logic and backoff timing in fetchData deterministically without hitting the network? Replace fetch with a mock (a controllable fake function used in tests that records how it was called and returns scripted responses) either by injecting fetchImpl = fetch as an optional parameter or by stubbing globalThis.fetch in a test runner like Jest or Vitest. You can then test every branch deterministically: (1) immediate 200 returns parsed JSON after 1 call, (2) a network rejection followed by a 500 followed by a 200 succeeds after 3 calls, and (3) persistent 500 responses throw after retries + 1 calls. Pass baseDelayMs = 0 or use fake timers (jest.useFakeTimers()) so backoff sleeps run in microseconds instead of slowing down your test suite.

Follow-up questions

Similar questions

More Sap interview questions

All 1 Sap questions →