Lodash prototype.plant: Clone Chain Sequences

This article provides a practical overview of the lodash.prototype.plant method, explaining how it enables the reuse and cloning of explicit Lodash chain sequences with new input data. You will learn the mechanics behind this method, observe a practical code demonstration, and understand the performance benefits of executing existing transformation pipelines without redefining them.

What is lodash.prototype.plant?

In Lodash, chaining allows developers to link multiple utility functions together into an explicit pipeline using the _() wrapper. Typically, a chain sequence is tied to the original data passed into the wrapper.

The lodash.prototype.plant(value) method clones an existing chain sequence and replaces the wrapped value with a new one. It creates an exact copy of the queued transformation pipeline, leaving the original chain sequence unaltered while preparing the new pipeline for execution with the provided value.

How It Works

Lodash supports lazy evaluation, meaning chained operations are queued rather than executed immediately until .value() is called.

When you call .plant(value) on a chain:

  1. Lodash copies the internal pipeline of queued actions from the source chain.
  2. It attaches the new input value as the target of these queued actions.
  3. It returns a new wrapped Lodash instance ready for evaluation.

Syntax

chain.plant(value)

Code Example

const _ = require('lodash');

// Define a transformation pipeline on an initial dataset
const initialArray = [1, 2, 3];
const doubleAndFilter = _(initialArray)
  .map(n => n * 2)
  .filter(n => n > 2);

// Evaluate the original chain
console.log(doubleAndFilter.value()); 
// Output: [4, 6]

// Plant a new dataset into the pipeline without re-declaring the chain
const newArray = [5, 10, 15];
const plantedChain = doubleAndFilter.plant(newArray);

// Evaluate the newly planted chain
console.log(plantedChain.value()); 
// Output: [10, 20, 30]

// The original chain remains functional and unchanged
console.log(doubleAndFilter.value()); 
// Output: [4, 6]

When to Use prototype.plant