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, & pebbles</p>'
// โ
Recommended approach
const p = (text: string) => `<p>${escape(text)}</p>`;
p('fred, barney, & pebbles');
// => '<p>fred, barney, & 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;
};