DEV Community

loading...

using reduce to calc longest range

thebronxsystem profile image thebronxsystem ・1 min read

Hey all I am trying to solve this.
I have an open that contains a nested array of ranges.

let test = {ranges: [[01, 10], [11, 100], [1000, 10001]]};

function characterCount(script) {
  return test.ranges.reduce((count, [from, to]) => {
    return count + (from - to);
  }, 0);
}

console.log(test.ranges.reduce((a, b) => {
  // console.log("a", a, "b", b);
  console.log("a", a, "b", b);
  return characterCount(a) < characterCount(b) ? b : a;
}));

Enter fullscreen mode Exit fullscreen mode

the result should be [1000, 10001];
Any help appreciated I finding this very tricky.

Discussion (1)

pic
Editor guide
Collapse
thebronxsystem profile image
thebronxsystem Author

I think I got it

// let test = {ranges: [[994, 1008], [11392, 11508], [11513, 11520]]};
let test = {ranges: [[01, 10], [11, 100], [1000, 10001]]};

function characterCount(script) {
  return script.reduce((a, b) => b - a);
}
// 11,100

console.log(test.ranges.reduce((a, b) => {
  return characterCount(a) < characterCount(b) ? b : a;
}));

console.log("complete.");


Enter fullscreen mode Exit fullscreen mode