Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to use the method some inside the reduce method?

I generate an array without taking into account the number 1 and the number that is sent as a parameter.

I used the "some" method to return the result when the number is divisible by some index. But I would like to use the functionality of the "some" method in the reduction while the array values ​​are being processed and not at the end.

let validate = (x) => [...Array(x - 2).keys()].reduce(
    (prev, curr) => (prev[curr] = curr + 2, prev), [])
    .some(i => x % i === 0);

console.log(validate(7)); // returns false because 7 is not divisible by any index between 2 and 6
console.log(validate(35)); //returns true because 35 is divisible by index 5

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

.reduce isn’t quite the right tool here, I think. You want to check whether any values in a range match a certain condition, so the outermost iteration method should be .some. This way, the loop breaks immediately when a match is found. The array of values to check can be constructed with Array.from.

let validate = (x) => Array.from(
  { length: x - 2 },
  (_, i) => i + 2
)
  .some(i => x % i === 0);

console.log(validate(7)); // returns false because 7 is not divisible by any index between 2 and 6
console.log(validate(15)); //returns true because 35 is divisible by index 5
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading