samuelgoto / proposal-number-parse

3 stars 0 forks source link

start index #2

Open fuchsia opened 7 years ago

fuchsia commented 7 years ago

If you're doing any serious parsing, the number won't begin at the beginning of the string; whether it's currency ("£5000.00"), hex colours ("#ffffff"), SVG path data, ("M19.654,0c-1.344,4.445-1.964,9.865-1.582,16 l1.938,11.5" ), CSS ("width: 600px; height: 360px"), JSON ('{ "width": 500, "height": 600 }') or some bespoke config format, the numbers are going to be buried in the middle of the string.

At present, you have to extract the number with substring() or a regex capture group and parse it to Number() (decimals) or parseInt() (non decimal integers with non-standard prefixes). Having something like Number.parse(string,{start:1, radix: 16}) would avoid that. It doesn't remove the need to validate the number. But it makes Number.parse() a function I might be able to use for parsing.

Precedents: String.prototype.startsWith, String.prototype.endsWith, String.prototype.indexOf, etc...

ljharb commented 7 years ago

The start index avoids having to slice; I don't see much value there. As for the radix, the point is to extract any literal that Number() would coerce, and it returns a string, not a number - so I don't think either option makes sense.

fuchsia commented 7 years ago

So I can't user Number.parse() where the prefix is absent, e.g "#ff00ff".slice(1)?

rwaldron commented 7 years ago

@fuchsia "ff00ff" does not meet the criteria that @ljharb defined:

any literal that Number() would coerce

fuchsia commented 7 years ago

We're on so completely different pages that it: DID. NOT. COMPUTE. It's sounding like ljharb's function is only going to be useful for tokenising javascript source. However I've prototyped a version to see if it is any use in practice.

samuelgoto commented 7 years ago

Can you share that prototype here?

(sent from phone, apologies for the brevity)

On Jul 21, 2017 1:27 PM, "fuchsia" notifications@github.com wrote:

We're on so completely different pages that it: DID. NOT. COMPUTE. It's sounding like ljharb's function is only going to be useful for tokenising javascript source. However I've prototyped a version to see if it is any use in practice.

— You are receiving this because you are subscribed to this thread. Reply to this email directly, view it on GitHub https://github.com/samuelgoto/proposal-number-parse/issues/2#issuecomment-317104378, or mute the thread https://github.com/notifications/unsubscribe-auth/AAqV6mmFOGkh0TwXb6QJw0Vw0uZ0sloiks5sQQmhgaJpZM4OYJBS .

fuchsia commented 7 years ago

Back on topic, I don't know how expensive slicing a string is (do engines copy the bytes or do they create a pair of pointers and leave the garbage collector to tidy up?) But a startIndex is a free hit. Any parser has got to have a read pointer; it can start at 0 or it can start at n. It might as well be exposed. Indeed it has been added where it was missing (sticky regex.)