8000 More efficient `isBlank` check (probably) · Issue #704 · google/quiver-dart · GitHub 8000
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content
More efficient isBlank check (probably) #704
Open
@niktekusho

Description

@niktekusho

Hi, thank you for the awesome library.

I noticed that isBlank is implemented as:

bool isBlank(String? s) => s == null || s.trim().isEmpty;

I am new to Dart (learning it for Flutter) and expect that trim will create a new String to check if it is blank.
Is my assumption correct? I cannot confirm this in code since String is abstract, and I could not find an implementation of it (I think it's implemented like a native method in Java, though 😄 ).

Would you accept a PR that avoids the new string creation by checking if each code point of the original string is whitespace?

The implementation I have locally is the following:

/// Set with whitespace character points.
/// ```plaintext
///     0009..000D    ; White_Space # Cc   <control-0009>..<control-000D>
///     0020          ; White_Space # Zs   SPACE
///     [cut for brevity...] 
///     FEFF          ; BOM                ZERO WIDTH NO_BREAK SPACE
/// ```
const whitespaces = <int>{
  0x0009,
  0x000A,
  0x000B,
  0x000C,
  0x000D,
  0x0020,
  0x0085,
  0x00A0,
  0x1680,
  0x2000,
  0x2001,
  0x2002,
  0x2003,
  0x2004,
  0x2005,
  0x2006,
  0x2007,
  0x2008,
  0x2009,
  0x200A,
  0x2028,
  0x2029,
  0x202F,
  0x205F,
  0x3000,
  0xFEFF,
};

bool isBlank(String? val) {
  if (val == null) return true;

  return val.codeUnits.every((element) => whitespaces.contains(element));
}

Here are some incomplete tests (imports are from Flutter; thus, they would need a replacement from the tests package):

void main() {
  test('Passing null to isBlank returns true', () {
    expect(isBlank(null), isTrue);
  });

  test('Passing non empty string to isBlank returns false', () {
    expect(isBlank('abc'), isFalse);
  });

  test('Passing empty string to isBlank returns true', () {
    expect(isBlank(''), isTrue);
  });

  test('Passing blank string to isBlank returns true', () {
    expect(isBlank(' '), isTrue);
  });
}

It's surely a bit long and verbose, but I don't think it's hard to understand.
What do you think about it?
One problem that might arise in the future will be if new codepoints in Unicode become whitespaces, which will require a code change in this library.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      0