-2

How could I write a function that takes a value and produce a list of values?

Ex: value = 2, function would increment by 1 until a condition is reached (or infinite and I would just take/drop from it), and expected result should look like: [3,4,5,6,7,8...]

right now I'm doing this ugly thing:

let min = ...;
const max = ....;
const acc = [min];

while (min.plus(1). < max) {
  min = min.plus(1);
  acc.push(min);
}

bonus question .... how could I represent this in type notation? Would it be: (a -> [a]) -> a -> [a]?

Thanks!

Stphane
  • 3,368
  • 5
  • 32
  • 47
damianrr
  • 1
  • 1

4 Answers4

1
function recursivePlus(min, max, collection) {
    if (!collection) {
        collection = [];
        collection.push(min);
        return recursivePlus(++min, max, collection);
    } else {
        if (min <= max) {
            collection.push(min);
            return recursivePlus(++min, max, collection);
        } else {
            return collection;
        }   
    }
}
recursivePlus(0, 3);
0

Maybe use lodash range https://lodash.com/docs/4.17.11#range

_.range(2, 9);
// => [2, 3, 4, 5, 6, 7, 8]

or use Array.apply (dense array) way:

How to generate sequence of numbers/chars in javascript?

https://2ality.com/2012/06/dense-arrays.html

SinunHenkka
  • 445
  • 6
  • 14
  • That's the type of utilities I'm looking for ... yet, what I've in my hand aren't numbers but dates .... basically I need to create the range by applying a function that adds a day to the last item processed. Range only processes numbers. – damianrr Oct 17 '19 at 21:34
0

I think range of dates as timestamps could be created with

const startDate = new Date("2019-10-16");
const endDate = new Date("2019-10-18");
const dayInMillis = 24 * 60 * 60 * 1000;
_.range(startDate.getTime(), endDate.getTime() + 1, dayInMillis);
// => [1571184000000, 1571270400000, 1571356800000]
SinunHenkka
  • 445
  • 6
  • 14
0

I found the solution I was looking for! Namely: unfold, it does the reverse of fold/reduce it would be something like this (Mind that I'm using Ramda.js a js functional library similar to underscore and lodash):

const f = n => n.toMillis() > maxDate.toMillis() ? false : [n, n.plus({ days: 1 })] unfold(f, minDate);

Thanks for trying to help me out guys, appreciated.

PS: I'll leave this article just in case someone is interested: https://kseo.github.io/posts/2016-12-12-unfold-and-fold.html

damianrr
  • 1
  • 1