简体   繁体   中英

Repeat value infinitely Ramda

For zipping, how can I zip a list with repetitions of a single value?

desired:

R.zip([1, 2, 3])(R.repeat(2)); // [[1, 2], [2, 2], [3, 2]]

You can use R.ap as a combinator of the R.zip function and a function that takes the length, and repeats and item:

 const { ap, zip, pipe, length, repeat } = R const fn = item => ap( zip, pipe(length, repeat(item)) ) const result = fn(2)([1, 2, 3]) console.log(result)
 <script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.28.0/ramda.min.js" integrity="sha512-t0vPcE8ynwIFovsylwUuLPIbdhDj6fav2prN9fEu/VYBupsmrmk9x43Hvnt+Mgn2h5YPSJOk7PMo9zIeGedD1A==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

This an overkill, but just for the sake of completeness - you can create Infinite lazy arrays in JS using a proxy. Create an array proxy with a get trap. For length return Infinity , and call a cb function to generate an item. In this case I use R.always to create always return 2 for an item:

 const { zip, __, always } = R const getInfiniteArray = getItem => new Proxy([], { get(target, prop, receive) { return prop === 'length'? Infinity: getItem(target, prop, receive) } }) const fn = zip(__, getInfiniteArray(always(2))) const result = fn()([1, 2, 3]) console.log(result)
 <script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.28.0/ramda.min.js" integrity="sha512-t0vPcE8ynwIFovsylwUuLPIbdhDj6fav2prN9fEu/VYBupsmrmk9x43Hvnt+Mgn2h5YPSJOk7PMo9zIeGedD1A==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

Try this:

R.zip([1, 2, 3], R.repeat(2, 3));

As someone pointed out, Ramda doesn't understand lazy lists, mainly because javascript does not provide support for lazy evaluation...

Probably this is the closest you could get, ramda would play a minimal role here though:

 function* infiniteZipWith(fn) { let number = 0; while (true) { yield [++number, fn()]; } }; const list = infiniteZipWith(R.always(2)); console.log(list.next().value); console.log(list.next().value); console.log(list.next().value);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.28.0/ramda.min.js" integrity="sha512-t0vPcE8ynwIFovsylwUuLPIbdhDj6fav2prN9fEu/VYBupsmrmk9x43Hvnt+Mgn2h5YPSJOk7PMo9zIeGedD1A==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM