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:
- Lodash copies the internal pipeline of queued actions from the source chain.
- It attaches the new input
valueas the target of these queued actions. - It returns a new wrapped Lodash instance ready for evaluation.
Syntax
chain.plant(value)chain: The existing Lodash chain sequence containing the queued operations.value: The new data source to inject into the cloned chain.- Returns: A new Lodash wrapper instance containing the cloned chain applied to the new 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
- Pipeline Reusability: When applying the exact same
sequence of transformations to multiple sets of data over time,
plantavoids the need to repeatedly wrap logic inside custom functions. - Performance Optimization: Creating a chain sequence
incurs small overhead as Lodash sets up internal execution queues. Using
plantcopies the existing sequence structure rather than constructing a new one from scratch, optimizing repeated executions over high-throughput data streams.