Iterate an array as a pair (current, next) in JavaScript

前端 未结 13 999
情话喂你
情话喂你 2020-12-09 09:06

In the question Iterate a list as pair (current, next) in Python, the OP is interested in iterating a Python list as a series of current, next pairs. I have th

13条回答
  •  南笙
    南笙 (楼主)
    2020-12-09 09:48

    This answer is inspired by an answer I saw to a similar question but in Haskell: https://stackoverflow.com/a/4506000/5932012

    We can use helpers from Lodash to write the following:

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

    (Unlike the Haskell equivalent, we need dropRight because Lodash's zip behaves differently to Haskell's`: it will use the length of the longest array instead of the shortest.)

    The same in Ramda:

    const zipAdjacent = function (ts: T[]): [T, T][] {
      return R.zip(ts, R.tail(ts));
    };
    zipAdjacent([1,2,3,4]); // => [[1,2], [2,3], [3,4]]
    

    Although Ramda already has a function that covers this called aperture. This is slightly more generic because it allows you to define how many consecutive elements you want, instead of defaulting to 2:

    R.aperture(2, [1,2,3,4]); // => [[1,2], [2,3], [3,4]]
    R.aperture(3, [1,2,3,4]); // => [[1,2,3],[2,3,4]]
    

提交回复
热议问题