# wrap

Function • Returns a function that returns its argument.


Arguments

name type description
value Any Any JavaScript value.

Returns

name type description
function Function An anonymous function that returns value when invoked.

# Description

wrap returns an anonymous function that, when invoked, returns the argument value. Use it any time you need to convert a value into a function you want to invoke later.

# Examples

# Returns a function that returns its argument.

provide = _.wrap 1

assert.equal 1,
  provide()
let provide = _.wrap(1);

assert.equal(1,
  provide());

# Avoid mutating wrapped values.

provide = _.wrap x: 1
double = (object) ->
  object.x *= 2
  object

assert.deepEqual x: 2,
  double provide()

# With `value` mutated, provide returns the doubled value.
assert.deepEqual x: 2,
  provide()
let provide = _.wrap({ x: 1 });
let double = (object) => {
  object.x *= 2
  return object
};

assert.deepEqual({ x: 2 },
  double(provide()));

assert.deepEqual({ x: 2 },
  provide());

The above example defines:

  • provide, a function created by wrap that returns an object.
  • double, a function that mutates the object passed to it.

In the first assert, we can see that double successfully doubles the value returned from provide. However, because JavaScript applies pass by reference to regular objects, the value now returned by provide is also altered. We confirm that in the second assert.

Keep this in mind when using wrap and avoid mutating value.