I wrote a code but i met a some strange thing.
function countPositivesSumNegatives(input) {
let count = 0;
let positive = 0;
let negative = 0;
for (let i = 0; i < input.length; i++) {
if (input[i] < 0) {
negative += input[i];
}
if (input[i] > 0) {
count++;
positive = count;
}
if (input == 0) {
return [];
}
}
return [positive, negative];
}
console.log(countPositivesSumNegatives([0, 0]));
Why output is [0, 0] instead of [] ? I'm trying to get just empty array []
Output has to be:
countPositivesSumNegatives([1, 2, 3, -1, -3]) -> [3, -4]
countPositivesSumNegatives([0, 0]) -> []
(UPDATED)
Since the function should return [] only if all elements are == 0, you can check at the end of the loop if positive and negative are == 0, meaning no positive numbers have been counted and no negative numbers have been summed:
function countPositivesSumNegatives(input) {
let count = 0;
let positive = 0;
let negative = 0;
for (let i = 0; i < input.length; i++) {
if (input[i] < 0) {
negative += input[i];
}
if (input[i] > 0) {
count++;
positive = count;
}
}
if (positive === 0 && negative === 0) {
return [];
}
else {
return [positive, negative];
}
}
console.log(countPositivesSumNegatives([0, 0]));
The only time you return [] is when the condition (input[i] == 0) matches on any element.
However, given the name of the function you only want to skip such elements.
If and only if the argument contains no other elements but 0, return the empty array.
So the following modified code will work:
function countPositivesSumNegatives(input) {
let count = 0;
let positive = 0;
let negative = 0;
for (let i = 0; i < input.length; i++) {
if (input[i] < 0) {
negative += input[i];
}
if (input[i] > 0) {
count++;
}
}
positive = count; // Hoisted out of the loop. Unless your function contains more code, you do not need the 'count' variable at all.
let seen_nonzero = ((positive !== 0) || (negative !== 0));
// Flags whether a non-0 element is present in your input.
let a_r =
seen_nonzero
? [positive, negative]
: []
;
return a_r
}
console.log(countPositivesSumNegatives([0, 0]));
console.log(countPositivesSumNegatives([1, 2, 3, -1, -3]));
console.log(countPositivesSumNegatives([-1, -2, 0, 1, 2]));