Skip to content

Feature request: add Ruby's each_cons and each_slice methods #252

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
utkarshkukreti opened this issue Apr 23, 2013 · 6 comments
Closed

Feature request: add Ruby's each_cons and each_slice methods #252

utkarshkukreti opened this issue Apr 23, 2013 · 6 comments

Comments

@utkarshkukreti
Copy link

It would be nice to have the equivalent of each_cons and each_slice methods Ruby's Enumerable module has.

Something like:

_.eachCons([1, 2, 3, 4], 2) => [[1, 2], [2, 3], [3, 4]]

_.eachCons([1, 2, 3, 4], 3) => [[1, 2, 3], [2, 3, 4]]

_.eachSlice([1, 2, 3, 4], 2) => [[1, 2], [3, 4]]

_.eachSlice([1, 2, 3, 4], 3) => [[1, 2, 3], [4]]

and probably also accept a callback as second param like many existing functions do.

Let me know if you'd like this to be in lodash, I would try to send in a pull request if I can.

@jdalton
Copy link
Member

jdalton commented Apr 23, 2013

@utkarshkukreti Thanks for the suggestion, but these special cased each methods feel like they should be in their own extension, _.mixin. I'll defer to Underscore's reason for not adopting it.

@jdalton jdalton closed this as completed Apr 23, 2013
@jdalton
Copy link
Member

jdalton commented Apr 23, 2013

Extensions like this will be easier to put together when we provide pre-sliced AMD/CommonJS/Node modules in the next major bump.

@hugoferreira
Copy link

I know this is an old request, but I would really like to understand the rationale behind these rejections. I mean, almost everything in this library is a fold (or reduce) special case. And chunk is nothing but this, with a stride equal to its length. How's this (and underscore's) request any different from having chunk?

@EverybodyKurts
Copy link

Just as an FYI to anybody else searching for functionality similar to Ruby's eachCons, Ramda has this functionality named as aperture.

@windmaomao
Copy link

in Kotlin, i believe this is called windowed(n). Maybe a quick way to do this without a new function is to drop one element first and use the rest to go through the index.

@vincerubinetti
Copy link

vincerubinetti commented Aug 23, 2024

https://stackoverflow.com/a/48541301/2180570

const zipAdjacent = function<T> (ts: T[]): [T, T][] {
  return zip(dropRight(ts, 1), tail(ts));
};

by Oliver Joseph Ash


https://stackoverflow.com/a/67602261/2180570

const pairWise = a => a.slice(1).map((k,i) => [a[i], k]);

by loop

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Development

No branches or pull requests

6 participants