Aller au contenu principal

wrap()

wrap<Arg, Args, Result>(value, wrapper): (...args) => Result

Creates a function that provides value to wrapper as its first argument.

💎 Why is this a Hidden Gem?

Add behavior around any function — perfect for logging, validation, or middleware.

DEPRECATED

Use a closure or higher-order function directly instead.


Type Parameters

Arg: Arg

The type of the first argument.

Args: Args extends unknown[]

The types of additional arguments.

Result: Result

The return type.


Parameters

value: Arg

The value to wrap.

wrapper: (value, ...args) => Result

The wrapper function.


Returns

The new function.


Since

2.0.0


Also known as

wrap (Lodash, es-toolkit) · ❌ (Remeda, Radashi, Ramda, Effect, Modern Dash, Antfu)


Example

// ❌ Deprecated approach
const p = wrap(escape, (func, text) => `<p>${func(text)}</p>`);
p('fred, barney, & pebbles');
// => '<p>fred, barney, &amp; pebbles</p>'

// ✅ Recommended approach
const p = (text: string) => `<p>${escape(text)}</p>`;
p('fred, barney, & pebbles');
// => '<p>fred, barney, &amp; pebbles</p>'

How it works?

Creates a function that wraps value with wrapper function. Deprecated: Use an arrow function.

Native Equivalent

// ❌ wrap(value, wrapper)
// ✅ (...args) => wrapper(value, ...args)

Use Cases

Wrap function with logic 📌

Add behavior around a function.

const withLogging = (fn) => (...args) => {
console.log("Calling with:", args);
const result = fn(...args);
console.log("Result:", result);
return result;
};

const add = (a, b) => a + b;
const logged = withLogging(add);

Add error handling

Wrap with try-catch.

const safe = (fn) => (...args) => {
try { return fn(...args); }
catch (e) { console.error(e); }
};

Measure performance

Wrap to track execution time.

const timed = (fn) => (...args) => {
const start = Date.now();
const result = fn(...args);
console.log(`Took ${Date.now() - start}ms`);
return result;
};