Björn
Björn

Reputation: 13207

shortest expression to return false for negative number and the number itself for positive number (or zero)

What is the shortest expression I can use to return false for all numbers < 0 and the number itself for all numbers >= 0?

Left is what I have, right is want I want to be returned.

-3: false
-1: false
 0:  0
 1:  1
23: 23

Something really short like:

(!!number)   <-- (doenst work)

Upvotes: 2

Views: 1474

Answers (4)

jak.b
jak.b

Reputation: 283

A very short one:

0>number?!1:number

Minified: 0>n?!1:n

Hint: !1 === false


Demo:

var numbers = [
  -5, // > false
  0,  // > 0
  5   // > 5
];

numbers.forEach(function(n) {
  console.log(
    0>n?!1:n
  );
});

Upvotes: 0

pimvdb
pimvdb

Reputation: 154838

If you want something shorter, you could do:

return number >= 0 && number;

If number >= 0 is false, then && will evaluate to the left operand (i.e. false). Otheriwse, it evaluates to the right operand (i.e. the number).

Upvotes: 2

Travesty3
Travesty3

Reputation: 14469

return number < 0 ? false : number;

Upvotes: 1

Sirko
Sirko

Reputation: 74046

without any checking whether number is actually a number:

return number < 0 ? false : number;

Upvotes: 2

Related Questions