Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Equivalent of Ruby's each cons in JavaScript
Ruby's each_cons() method iterates through consecutive N elements of an enumerable, creating subarrays of fixed size. JavaScript doesn't have this built-in, but we can implement it using Array prototype extension.
Understanding each_cons Behavior
The each_cons(n) function creates sliding windows of size n from an array. For each starting position, it takes n consecutive elements until there aren't enough remaining elements.
const arr = [1, 2, 3, 4, 5]; // With n=2: creates pairs starting from each position // Result: [[1,2], [2,3], [3,4], [4,5]] // With n=3: creates triplets starting from each position // Result: [[1,2,3], [2,3,4], [3,4,5]]
Implementation Using Sliding Window
We'll implement this using the sliding window algorithm, which efficiently creates consecutive subarrays:
const eachCons = function(num) {
let res = [], temp = [];
let start = 0, end = 0;
// Build initial window of size num
while(end < num) {
temp.push(this[end++]);
}
// Slide window through the array
for(; end <= this.length ;) {
if(temp.length === num) {
res.push(temp);
start++;
end = start;
temp = [];
}
temp[end-start] = this[end];
end++;
}
return res;
};
Array.prototype.eachCons = eachCons;
console.log([1, 2, 3, 4, 5].eachCons(1));
console.log([1, 2, 3, 4, 5].eachCons(2));
console.log([1, 2, 3, 4, 5].eachCons(3));
console.log([1, 2, 3, 4, 5].eachCons(4));
[ [ 1 ], [ 2 ], [ 3 ], [ 4 ], [ 5 ] ] [ [ 1, 2 ], [ 2, 3 ], [ 3, 4 ], [ 4, 5 ] ] [ [ 1, 2, 3 ], [ 2, 3, 4 ], [ 3, 4, 5 ] ] [ [ 1, 2, 3, 4 ], [ 2, 3, 4, 5 ] ]
Alternative ES6 Implementation
A more concise approach using modern JavaScript methods:
Array.prototype.eachConsES6 = function(n) {
return this.slice(0, -n + 1).map((_, i) => this.slice(i, i + n));
};
const arr = [1, 2, 3, 4, 5];
console.log(arr.eachConsES6(2));
console.log(arr.eachConsES6(3));
[ [ 1, 2 ], [ 2, 3 ], [ 3, 4 ], [ 4, 5 ] ] [ [ 1, 2, 3 ], [ 2, 3, 4 ], [ 3, 4, 5 ] ]
How It Works
The sliding window algorithm maintains a window of size n that moves through the array:
- Initialize window with first
nelements - Add current window to results
- Slide window one position right
- Repeat until insufficient elements remain
Conclusion
The sliding window approach efficiently implements Ruby's each_cons in JavaScript. While the ES6 version is more concise, the manual implementation offers better performance for large arrays.
