Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Short-circuit in starts_with #6146

Open
ozanmuyes opened this issue Oct 24, 2024 · 3 comments
Open

Short-circuit in starts_with #6146

ozanmuyes opened this issue Oct 24, 2024 · 3 comments

Comments

@ozanmuyes
Copy link

if (prefix.length > source.length) {

this can be written as

         if (prefix.length != source.length) {

since prefix can't be longer than the source.

@babiabeo
Copy link
Contributor

It will return false if prefix is shorter than source, which is not the expected behavior.

@ozanmuyes
Copy link
Author

Why it is not the expected behaviour? So "foobar" starts with "foobarbaz"?

@0f-0b
Copy link
Contributor

0f-0b commented Oct 27, 2024

This is what happens if you run the example from the documentation after applying this change.

$ deno run example.ts
error: Uncaught (in promise) AssertionError: Values are not equal.


    [Diff] Actual / Expected


-   false
+   true

  throw new AssertionError(message);
        ^
    at assertEquals (file://…/deno_std/assert/equals.ts:51:9)
    at file://…/example.ts:7:1

If you remove the check altogether it would work, but much slower than the original in case prefix is sometimes longer than source, because V8 deoptimizes the function when source[i] indexes out of bounds.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants