Search code examples
javascriptarrayscron

Javascript: add a new value to a set of values (minutes), which is furthest away from any two existing cronjobs


Suppose I have an array of numbers (which indicate the minutes when cron jobs should run):

let arr = ['21', '23', '25', '59', '10']

I want to insert a new number into this array arr, but I want to make sure that it's furthest away from any two numbers that already exist in this spectrum.

Intuitively I can say that it should be somewhere around 44 but how do I program that into an algorithm?

I know the question is a bit general, but it is very useful for scheduling cronjobs automatically, so that they don't overlap, and I don't even know where to start.

Maybe you heard of a similar problem and a possible solution? Or a Node.Js module that does something similar?


Solution

  • If the values of the array are in order, you could check a value and the previous value, pic the greatest delta and calculate the time in the middle.

        let array = [35, 23, 25, 59, 10];
    
        array.sort((a, b) => a - b); // sorts numbers in ascending order
    
        let result = array
            .reduce((r, value, i, { length, [(i + length - 1) % length]: prev }) => {
                var delta = (value + 60 - prev) % 60;
                if (!r || delta > r.delta) return { delta, value: (prev + delta / 2) % 60 };
                return r;
            }, undefined)
            .value;
    
    console.log(result);
    console.log(parseInt(result)); // in case if used for cron