javascript - In String.prototype.slice(), should .slice(0,-0) and .slice(0,+0) output the same result? -


i came across quirk while trying optimise string pluralisation in game of code golf. had idea write strings plurals , use substr cut last character off, conditionally:

var counter = 1; var mytext = counter + " units".substr(0, 6-(counter===1)); 

it's fine - wanted. looking @ mdn docs string.prototype.slice(), thought had found way make even shorter, using passing negative 0 second argument function. docs:

endslice

optional. zero-based index @ end extraction. if omitted, slice() extracts end of string. if negative, treated sourcelength + endslice sourcelength length of string (for example, if endslice -3 treated sourcelength - 3).

var mytext = counter + " units".slice(0,-(counter===1)); 

this evaluates .slice(0,-1) when counter equal 1, chop last letter string, or otherwise evaluate .slice(0,-0), according docs should mean 0 characters subtracted length of string being operated upon.

as happens, -0 treated same +0 string.prototype.slice. wondered if convention, treat -0 being same +0 (i know, instance, -0 === +0 evaluates true). thought @ string.prototype.substr, +0 , -0 supposed handled same way in function.

does have greater insight this? there basic convention in language design states that, while signed 0 language feature, should ignored, except in scenarios (like 1/-0)?

tl;dr i'm salty can't make jokes winning code golf slicing.

from mathematical perspective there no negative zero. positive number greater zero, , negative number smaller zero. 0 neither of those. guess behaviour described correct.

a real number may either rational or irrational; either algebraic or transcendental; , either positive, negative, or zero.

https://en.wikipedia.org/wiki/real_number

although, because in programming work floating point numbers, approximation of real numbers, there concept of -0, representation of negative number close 0 represented otherwise - http://www.johndcook.com/blog/2010/06/15/why-computers-have-signed-zero/


regarding javascript, write as:

var counter = 1; var mytext = counter + " unit" + (counter > 1 ? "s" : ""); 

Comments

Popular posts from this blog

javascript - Thinglink image not visible until browser resize -

firebird - Error "invalid transaction handle (expecting explicit transaction start)" executing script from Delphi -

mongodb - How to keep track of users making Stripe Payments -