Reputation: 39
I am trying to write a code(function) that takes in two parameters a and b, and returns all the even number between a and b if a is greater than b else it should return the odd numbers between a and b.
this is my code.
function number_ranges (a, b) {
let numbers = [];
if (a > b){
for (let i = b; i < a; i++){
if (i > b){
numbers.push(i);
}
}
}else{
for (let i = a; i < b; i++){
if (i > a){
numbers.push(i);
}
}
}
const result = numbers.filter(function(num){
return a > b ? num % 2 === 0: num % 2 === 1;
});
return result;
}
I would like to see a different approach because i cant seem to be able to pass all the test cases
Upvotes: 0
Views: 992
Reputation: 7923
I used this function f=(a,b)=>[...ArrayMath.max(a,b))].map((q,i)=>i).filter(z=>(a<b?!(z%2):z%2)&&z>=Math.min(a,b))
I first create a range from 1 to b
as follow [...Array(Math.max(a,b))].map((q,i)=>i)
Then I filter with a<b?!(z%2):z%2
. If a greater than b then a keep the even numbers, else the odds.
Also I keep only those number greater or equal to the first parameter using &&z>=Math.min(a,b)
f=(a,b)=>[...Array(Math.max(a,b))].map((q,i)=>i).filter(z=>(a<b?!(z%2):z%2)&&z>=Math.min(a,b))
console.log(f(10, 5))
console.log(f(5, 10))
Upvotes: 1
Reputation: 386654
You could take a sningle loop and a check if the value is even or or in combination with a check for the order.
function getEvenOdd(a, b) {
var inc = +(a < b) || -1,
i,
result = [];
for (i = a; i !== b + inc; i += inc) {
if (+(inc === 1) !== i % 2) {
result.push(i);
}
}
return result;
}
// even
console.log(getEvenOdd(3, 10).join(' ')); // [4, 6, 8, 10]
console.log(getEvenOdd(4, 10).join(' ')); // [4, 6, 8, 10]
console.log(getEvenOdd(3, 9).join(' ')); // [4, 6, 8]
console.log(getEvenOdd(4, 9).join(' ')); // [4, 6, 8]
// odd
console.log(getEvenOdd(10, 3).join(' ')); // [9, 7, 5, 3]
console.log(getEvenOdd(10, 4).join(' ')); // [9, 7, 5]
console.log(getEvenOdd(9, 3).join(' ')); // [9, 7, 5, 3]
console.log(getEvenOdd(9, 4).join(' ')); // [9, 7, 5]
Upvotes: 1