Typorithm · medium

Implement partial & once

partial-onceinterview-questionspartialonceclosures
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn Implement partial & once

0%

Implement It

partial(fn, ...preset) returns a function that calls fn with the preset args followed by the new args. once(fn) returns a function that runs fn only on the first call, caches its result, and returns that cached value on every later call.

partial pre-binds leading arguments. It captures preset via rest, then returns a function that spreads preset first and the later arguments after, so partial(fn, a)(b, c) calls fn(a, b, c).

once enforces single execution. It keeps two closure variables: a boolean called flag and a result cache. The returned function checks if (!called); on the first call it flips the flag, runs fn(...args), and stores the return value.

On every subsequent call, the guard is skipped and the function simply returns the cached result without invoking fn again. This makes once ideal for one-time initialization where repeated calls must be no-ops that still return the original value.

01

partial spreads preset args before the later ones: fn(...preset, ...later).

02

once uses a called flag plus a cached result.

03

After the first call, once returns the cache without re-running fn.

function partial(fn, ...preset) {
  return (...later) => fn(...preset, ...later);
}

function once(fn) {
  let called = false;
  let result;
  return (...args) => {
    if (!called) {
      called = true;
      result = fn(...args);
    }
    return result;
  };
}

Read the implementation

Connect each part of the code to the concept before you type.

1. partial spreads preset first

partial calls fn with the preset args spread first, then the later args supplied at call time.

return (...later) => fn(...preset, ...later);

2. once's run flag

A closure variable tracks whether fn has already run so later calls can skip it.

let called = false;

3. Run only the first time

The guard ensures fn executes on the first call and is skipped on every later one.

if (!called) {

4. Cache the result

The first call's return value is stored so it can be returned on all subsequent calls.

result = fn(...args);

5. Return cached value

Every call returns the cached result; only the first call actually invokes fn.

return result;

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

Implement partial & once: Lesson & Practice · Typorithm | ApplyDjinn