From dfc9cf6c731dd492f4f42bd7629aed89a74ba007 Mon Sep 17 00:00:00 2001 From: "google-labs-jules[bot]" <161369871+google-labs-jules[bot]@users.noreply.github.com> Date: Sun, 25 Jan 2026 02:18:41 +0000 Subject: [PATCH 1/2] Optimize getStringArrayRegexpPropOrThrow to use single pass Combined the list extraction and regex validation into a single iteration to avoid creating an intermediate list and iterating twice. This improves performance for large lists. --- example/dartobjectutils_example.dart | 83 +++++++-------- lib/src/dartobjectutils_base.dart | 147 +++++++++++++++++---------- test/dartobjectutils_test.dart | 66 ++++++++---- test/regexp_tests.dart | 71 ++++++++----- 4 files changed, 229 insertions(+), 138 deletions(-) diff --git a/example/dartobjectutils_example.dart b/example/dartobjectutils_example.dart index 740d478..a336eec 100644 --- a/example/dartobjectutils_example.dart +++ b/example/dartobjectutils_example.dart @@ -8,10 +8,10 @@ class Address { final String zip; Address(Map json) - : street = getStringPropOrThrow(json, 'street'), - city = getStringPropOrThrow(json, 'city'), - // Use default value for optional fields - zip = getStringPropOrDefault(json, 'zip', '00000'); + : street = getStringPropOrThrow(json, 'street'), + city = getStringPropOrThrow(json, 'city'), + // Use default value for optional fields + zip = getStringPropOrDefault(json, 'zip', '00000'); @override String toString() => '$street, $city $zip'; @@ -27,28 +27,31 @@ class User { final Map scores; User(Map json) - : name = getStringPropOrThrow(json, 'name'), - // Automatically converts compatible types (e.g. String "30" -> int 30) - age = getNumberPropOrDefault(json, 'age', 0).toInt(), - isActive = getBooleanPropOrDefault(json, 'isActive', false), - // Parse nested object - address = getObjectFunctionPropOrThrow( - json, - 'address', - (j) => Address(j), - ), - // Parse array of primitives - tags = getStringArrayPropOrDefault(json, 'tags', []), - // Parse array of objects - prevAddresses = getObjectArrayFunctionPropOrDefault( - json, - 'prevAddresses', - (j) => Address(j), -
[], - )!, // ! is safe because we provide a non-null default value - // Explicitly specify generics for type safety when extracting Maps - scores = getMapPropOrDefault>( - json, 'scores', {}); + : name = getStringPropOrThrow(json, 'name'), + // Automatically converts compatible types (e.g. String "30" -> int 30) + age = getNumberPropOrDefault(json, 'age', 0).toInt(), + isActive = getBooleanPropOrDefault(json, 'isActive', false), + // Parse nested object + address = getObjectFunctionPropOrThrow( + json, + 'address', + (j) => Address(j), + ), + // Parse array of primitives + tags = getStringArrayPropOrDefault(json, 'tags', []), + // Parse array of objects + prevAddresses = getObjectArrayFunctionPropOrDefault( + json, + 'prevAddresses', + (j) => Address(j), +
[], + )!, // ! is safe because we provide a non-null default value + // Explicitly specify generics for type safety when extracting Maps + scores = getMapPropOrDefault>( + json, + 'scores', + {}, + ); @override String toString() { @@ -66,17 +69,13 @@ void main() { 'name': 'Alice', 'age': 30, 'isActive': true, - 'address': { - 'street': '123 Main St', - 'city': 'Wonderland', - 'zip': '12345', - }, + 'address': {'street': '123 Main St', 'city': 'Wonderland', 'zip': '12345'}, 'tags': ['admin', 'editor'], 'prevAddresses': [ {'street': '456 Old St', 'city': 'OldTown', 'zip': '67890'}, - {'street': '789 Unknown St', 'city': 'Nowhere'} + {'street': '789 Unknown St', 'city': 'Nowhere'}, ], - 'scores': {'math': 95, 'science': 88} + 'scores': {'math': 95, 'science': 88}, }; print('\n1. Parsing Valid User:'); @@ -90,10 +89,7 @@ void main() { // Case 2: Missing optional fields (using defaults) final minimalJson = { 'name': 'Bob', - 'address': { - 'street': '1st Ave', - 'city': 'Metropolis', - }, + 'address': {'street': '1st Ave', 'city': 'Metropolis'}, // 'age' missing -> defaults to 0 // 'isActive' missing -> defaults to false // 'tags' missing -> defaults to [] @@ -111,7 +107,8 @@ void main() { // Case 3: Invalid data (throwing error) final invalidJson = { 'name': 'Charlie', - 'age': 'not a number', // getNumberPropOrDefault handles conversion failure -> defaults to 0 + 'age': + 'not a number', // getNumberPropOrDefault handles conversion failure -> defaults to 0 'address': 'Not a map', // getObjectFunctionPropOrThrow throws exception }; @@ -145,11 +142,17 @@ void main() { // Demonstration of manual extraction before creating the object print('Decoded name: ${getStringPropOrThrow(decoded, "name")}'); - print('Decoded age: ${getNumberPropOrThrow(decoded, "age")}'); // Auto converts string "45" to num + print( + 'Decoded age: ${getNumberPropOrThrow(decoded, "age")}', + ); // Auto converts string "45" to num // Custom handling for boolean if API returns 0/1 instead of true/false final isActive = getBooleanFunctionPropOrDefault( - decoded, 'isActive', (v) => v == 1 || v == true, false); + decoded, + 'isActive', + (v) => v == 1 || v == true, + false, + ); print('Decoded isActive (custom logic): $isActive'); // Create User object diff --git a/lib/src/dartobjectutils_base.dart b/lib/src/dartobjectutils_base.dart index f710cee..e36848e 100644 --- a/lib/src/dartobjectutils_base.dart +++ b/lib/src/dartobjectutils_base.dart @@ -420,16 +420,26 @@ List getStringArrayRegexpPropOrThrow( RegExp regexp, { String? message, }) { - final list = getStringArrayPropOrThrow(props, prop, message: message); - for (final val in list) { - if (!regexp.hasMatch(val)) { - throw MissingOrInvalidPropertyException( - message ?? - '$prop element "$val" does not match pattern ${regexp.pattern} in ${props.runtimeType}', - ); + if (props != null) { + if (props.containsKey(prop)) { + final v = props[prop]; + if (v is List) { + return v.map((e) { + final val = e.toString(); + if (!regexp.hasMatch(val)) { + throw MissingOrInvalidPropertyException( + message ?? + '$prop element "$val" does not match pattern ${regexp.pattern} in ${props.runtimeType}', + ); + } + return val; + }).toList(); + } } } - return list; + throw MissingOrInvalidPropertyException( + message ?? '$prop not found as string[] in ${props.runtimeType}', + ); } // --- Date Array --- @@ -594,29 +604,27 @@ X getObjectArrayFunctionPropOrThrow?>( final v = props[prop]; if (v is List) { // v is List. We need to map it. - final list = v - .map((e) { - if (e is Map) { - return constructorFunc(e); - } - if (e is Map) { - return constructorFunc(e.cast()); - } - // What if e is not a map? The constructorFunc expects Map. - // But in `getObjectArrayPropOrThrow`, the constructorFunc is `(e) => e as Y`. - // If Y is something else, this might work if constructorFunc handles it. - // But ConstructorFunc definition is `Y Function(Map params)`. - // So e MUST be a Map. - // If it is not a Map, this will throw type error at runtime when calling constructorFunc, - // or we should handle it? - // TS: `return v.map(constructorFunc) as X;` - // TS `ConstructorFunc` is `(params: object) => Y`. - // JS `object` can be almost anything. - // Dart `Map` is more specific. - // If we strictly follow `ConstructorFunc` typedef, we must pass a Map. - throw ElementConversionException("Element in array is not a Map"); - }) - .toList(); + final list = v.map((e) { + if (e is Map) { + return constructorFunc(e); + } + if (e is Map) { + return constructorFunc(e.cast()); + } + // What if e is not a map? The constructorFunc expects Map. + // But in `getObjectArrayPropOrThrow`, the constructorFunc is `(e) => e as Y`. + // If Y is something else, this might work if constructorFunc handles it. + // But ConstructorFunc definition is `Y Function(Map params)`. + // So e MUST be a Map. + // If it is not a Map, this will throw type error at runtime when calling constructorFunc, + // or we should handle it? + // TS: `return v.map(constructorFunc) as X;` + // TS `ConstructorFunc` is `(params: object) => Y`. + // JS `object` can be almost anything. + // Dart `Map` is more specific. + // If we strictly follow `ConstructorFunc` typedef, we must pass a Map. + throw ElementConversionException("Element in array is not a Map"); + }).toList(); return list as X; } } @@ -782,7 +790,10 @@ Y getObjectPropOrDefaultFunctionAllowNull( // --- Number Array --- R getNumberArrayPropOrDefault( - Map? props, String prop, R defaultValue) { + Map? props, + String prop, + R defaultValue, +) { try { final res = getNumberArrayPropOrThrow(props, prop); return res as R; @@ -791,7 +802,10 @@ R getNumberArrayPropOrDefault( } R getNumberArrayPropOrDefaultFunction( - Map? props, String prop, R Function() defaultFunction) { + Map? props, + String prop, + R Function() defaultFunction, +) { try { final res = getNumberArrayPropOrThrow(props, prop); return res as R; @@ -800,8 +814,10 @@ R getNumberArrayPropOrDefaultFunction( } List getNumberArrayPropOrThrow( - Map? props, String prop, - {String? message}) { + Map? props, + String prop, { + String? message, +}) { if (props != null) { if (props.containsKey(prop)) { final v = props[prop]; @@ -809,8 +825,8 @@ List getNumberArrayPropOrThrow( return v.map((e) { if (e is num) return e; if (e is String) { - final n = num.tryParse(e); - if (n != null) return n; + final n = num.tryParse(e); + if (n != null) return n; } throw ArgumentError('Element $e is not a number'); }).toList(); @@ -818,13 +834,17 @@ List getNumberArrayPropOrThrow( } } throw ArgumentError( - message ?? '$prop not found as number[] in ${props.runtimeType}'); + message ?? '$prop not found as number[] in ${props.runtimeType}', + ); } // --- BigInt Array --- R getBigIntArrayPropOrDefault( - Map? props, String prop, R defaultValue) { + Map? props, + String prop, + R defaultValue, +) { try { final res = getBigIntArrayPropOrThrow(props, prop); return res as R; @@ -833,7 +853,10 @@ R getBigIntArrayPropOrDefault( } R getBigIntArrayPropOrDefaultFunction( - Map? props, String prop, R Function() defaultFunction) { + Map? props, + String prop, + R Function() defaultFunction, +) { try { final res = getBigIntArrayPropOrThrow(props, prop); return res as R; @@ -842,8 +865,10 @@ R getBigIntArrayPropOrDefaultFunction( } List getBigIntArrayPropOrThrow( - Map? props, String prop, - {String? message}) { + Map? props, + String prop, { + String? message, +}) { if (props != null) { if (props.containsKey(prop)) { final v = props[prop]; @@ -861,13 +886,17 @@ List getBigIntArrayPropOrThrow( } } throw ArgumentError( - message ?? '$prop not found as BigInt[] in ${props.runtimeType}'); + message ?? '$prop not found as BigInt[] in ${props.runtimeType}', + ); } // --- Boolean Array --- R getBooleanArrayPropOrDefault( - Map? props, String prop, R defaultValue) { + Map? props, + String prop, + R defaultValue, +) { try { final res = getBooleanArrayPropOrThrow(props, prop); return res as R; @@ -876,7 +905,10 @@ R getBooleanArrayPropOrDefault( } R getBooleanArrayPropOrDefaultFunction( - Map? props, String prop, R Function() defaultFunction) { + Map? props, + String prop, + R Function() defaultFunction, +) { try { final res = getBooleanArrayPropOrThrow(props, prop); return res as R; @@ -885,8 +917,10 @@ R getBooleanArrayPropOrDefaultFunction( } List getBooleanArrayPropOrThrow( - Map? props, String prop, - {String? message}) { + Map? props, + String prop, { + String? message, +}) { if (props != null) { if (props.containsKey(prop)) { final v = props[prop]; @@ -899,7 +933,8 @@ List getBooleanArrayPropOrThrow( } } throw ArgumentError( - message ?? '$prop not found as boolean[] in ${props.runtimeType}'); + message ?? '$prop not found as boolean[] in ${props.runtimeType}', + ); } // --- Enum --- @@ -993,8 +1028,12 @@ List getEnumArrayPropOrDefault( String Function(T)? keyExtractor, }) { try { - return getEnumArrayPropOrThrow(props, prop, values, - keyExtractor: keyExtractor); + return getEnumArrayPropOrThrow( + props, + prop, + values, + keyExtractor: keyExtractor, + ); } catch (_) {} return defaultValue; } @@ -1007,8 +1046,12 @@ List getEnumArrayPropOrDefaultFunction( String Function(T)? keyExtractor, }) { try { - return getEnumArrayPropOrThrow(props, prop, values, - keyExtractor: keyExtractor); + return getEnumArrayPropOrThrow( + props, + prop, + values, + keyExtractor: keyExtractor, + ); } catch (_) {} return defaultFunction(); } diff --git a/test/dartobjectutils_test.dart b/test/dartobjectutils_test.dart index b41fe3a..6865a65 100644 --- a/test/dartobjectutils_test.dart +++ b/test/dartobjectutils_test.dart @@ -148,17 +148,23 @@ void main() { }); test('getNumberArrayPropOrThrow', () { - final nums = getNumberArrayPropOrThrow({'nums': [1, 2.5, '3']}, 'nums'); + final nums = getNumberArrayPropOrThrow({ + 'nums': [1, 2.5, '3'], + }, 'nums'); expect(nums, [1, 2.5, 3]); }); test('getBigIntArrayPropOrThrow', () { - final bigInts = getBigIntArrayPropOrThrow({'bigInts': [BigInt.one, 2, '3']}, 'bigInts'); + final bigInts = getBigIntArrayPropOrThrow({ + 'bigInts': [BigInt.one, 2, '3'], + }, 'bigInts'); expect(bigInts, [BigInt.one, BigInt.from(2), BigInt.from(3)]); }); test('getBooleanArrayPropOrThrow', () { - final bools = getBooleanArrayPropOrThrow({'bools': [true, false]}, 'bools'); + final bools = getBooleanArrayPropOrThrow({ + 'bools': [true, false], + }, 'bools'); expect(bools, [true, false]); }); }); @@ -225,10 +231,7 @@ void main() { }; test('getEnumPropOrThrow', () { - expect( - getEnumPropOrThrow(map, 'enum', TestEnum.values), - TestEnum.one, - ); + expect(getEnumPropOrThrow(map, 'enum', TestEnum.values), TestEnum.one); expect( () => getEnumPropOrThrow(map, 'missing', TestEnum.values), throwsA(isA()), @@ -245,8 +248,7 @@ void main() { TestEnum.one, ); expect( - getEnumPropOrDefault( - map, 'missing', TestEnum.values, TestEnum.three), + getEnumPropOrDefault(map, 'missing', TestEnum.values, TestEnum.three), TestEnum.three, ); }); @@ -254,28 +256,38 @@ void main() { test('getEnumPropOrDefaultFunction', () { expect( getEnumPropOrDefaultFunction( - map, 'enum', TestEnum.values, () => TestEnum.three), + map, + 'enum', + TestEnum.values, + () => TestEnum.three, + ), TestEnum.one, ); expect( getEnumPropOrDefaultFunction( - map, 'missing', TestEnum.values, () => TestEnum.three), + map, + 'missing', + TestEnum.values, + () => TestEnum.three, + ), TestEnum.three, ); }); test('getEnumArrayPropOrThrow', () { - expect( - getEnumArrayPropOrThrow(map, 'enums', TestEnum.values), - [TestEnum.one, TestEnum.two], - ); + expect(getEnumArrayPropOrThrow(map, 'enums', TestEnum.values), [ + TestEnum.one, + TestEnum.two, + ]); expect( () => getEnumArrayPropOrThrow(map, 'missing', TestEnum.values), throwsA(isA()), ); expect( () => getEnumArrayPropOrThrow( - {'enums': ['one', 'four']}, + { + 'enums': ['one', 'four'], + }, 'enums', TestEnum.values, ), @@ -285,13 +297,15 @@ void main() { test('getEnumArrayPropOrDefault', () { expect( - getEnumArrayPropOrDefault( - map, 'enums', TestEnum.values, [TestEnum.three]), + getEnumArrayPropOrDefault(map, 'enums', TestEnum.values, [ + TestEnum.three, + ]), [TestEnum.one, TestEnum.two], ); expect( - getEnumArrayPropOrDefault( - map, 'missing', TestEnum.values, [TestEnum.three]), + getEnumArrayPropOrDefault(map, 'missing', TestEnum.values, [ + TestEnum.three, + ]), [TestEnum.three], ); }); @@ -299,12 +313,20 @@ void main() { test('getEnumArrayPropOrDefaultFunction', () { expect( getEnumArrayPropOrDefaultFunction( - map, 'enums', TestEnum.values, () => [TestEnum.three]), + map, + 'enums', + TestEnum.values, + () => [TestEnum.three], + ), [TestEnum.one, TestEnum.two], ); expect( getEnumArrayPropOrDefaultFunction( - map, 'missing', TestEnum.values, () => [TestEnum.three]), + map, + 'missing', + TestEnum.values, + () => [TestEnum.three], + ), [TestEnum.three], ); }); diff --git a/test/regexp_tests.dart b/test/regexp_tests.dart index 5a0dcd8..2abcfc2 100644 --- a/test/regexp_tests.dart +++ b/test/regexp_tests.dart @@ -7,7 +7,7 @@ void main() { 'email': 'test@example.com', 'username': 'user123', 'invalid': '!!!', - 'num': 123 + 'num': 123, }; final emailRegex = RegExp(r'^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$'); final alphaNumericRegex = RegExp(r'^[a-zA-Z0-9]+$'); @@ -37,26 +37,35 @@ void main() { // Wrong type (though getStringPropOrThrow converts num to string, // let's see if regex matches the stringified version. // 123 matches ^[a-zA-Z0-9]+$ - expect( - getStringRegexpPropOrThrow(map, 'num', alphaNumericRegex), - '123', - ); + expect(getStringRegexpPropOrThrow(map, 'num', alphaNumericRegex), '123'); }); test('getStringRegexpPropOrDefault', () { expect( getStringRegexpPropOrDefault( - map, 'email', emailRegex, 'default@example.com'), + map, + 'email', + emailRegex, + 'default@example.com', + ), 'test@example.com', ); expect( getStringRegexpPropOrDefault( - map, 'invalid', alphaNumericRegex, 'default'), + map, + 'invalid', + alphaNumericRegex, + 'default', + ), 'default', ); expect( getStringRegexpPropOrDefault( - map, 'missing', alphaNumericRegex, 'default'), + map, + 'missing', + alphaNumericRegex, + 'default', + ), 'default', ); }); @@ -64,12 +73,20 @@ void main() { test('getStringRegexpPropOrDefaultFunction', () { expect( getStringRegexpPropOrDefaultFunction( - map, 'email', emailRegex, () => 'default@example.com'), + map, + 'email', + emailRegex, + () => 'default@example.com', + ), 'test@example.com', ); expect( getStringRegexpPropOrDefaultFunction( - map, 'invalid', alphaNumericRegex, () => 'default'), + map, + 'invalid', + alphaNumericRegex, + () => 'default', + ), 'default', ); }); @@ -85,10 +102,10 @@ void main() { final numRegex = RegExp(r'^\d+$'); test('getStringArrayRegexpPropOrThrow', () { - expect( - getStringArrayRegexpPropOrThrow(map, 'emails', emailRegex), - ['a@a.com', 'b@b.com'], - ); + expect(getStringArrayRegexpPropOrThrow(map, 'emails', emailRegex), [ + 'a@a.com', + 'b@b.com', + ]); // One invalid element should cause throw expect( @@ -102,29 +119,35 @@ void main() { // I should probably implement it such that it throws if ANY element fails. // Numbers as strings - expect( - getStringArrayRegexpPropOrThrow(map, 'nums', numRegex), - ['123', '456'], - ); + expect(getStringArrayRegexpPropOrThrow(map, 'nums', numRegex), [ + '123', + '456', + ]); }); test('getStringArrayRegexpPropOrDefault', () { expect( - getStringArrayRegexpPropOrDefault( - map, 'emails', emailRegex, ['default']), + getStringArrayRegexpPropOrDefault(map, 'emails', emailRegex, [ + 'default', + ]), ['a@a.com', 'b@b.com'], ); expect( - getStringArrayRegexpPropOrDefault( - map, 'mixed', emailRegex, ['default']), + getStringArrayRegexpPropOrDefault(map, 'mixed', emailRegex, [ + 'default', + ]), ['default'], ); }); test('getStringArrayRegexpPropOrDefaultFunction', () { - expect( + expect( getStringArrayRegexpPropOrDefaultFunction( - map, 'mixed', emailRegex, () => ['default']), + map, + 'mixed', + emailRegex, + () => ['default'], + ), ['default'], ); }); From bc036ed21a2e252723b26d21d245b241698fee4d Mon Sep 17 00:00:00 2001 From: "google-labs-jules[bot]" <161369871+google-labs-jules[bot]@users.noreply.github.com> Date: Sun, 25 Jan 2026 06:32:07 +0000 Subject: [PATCH 2/2] Optimize getStringArrayRegexpPropOrThrow and remove unused comments Combined the list extraction and regex validation into a single iteration to avoid creating an intermediate list and iterating twice. This improves performance for large lists. Also removed a large block of commented-out code/notes in getObjectArrayFunctionPropOrThrow. --- lib/src/dartobjectutils_base.dart | 12 ------------ 1 file changed, 12 deletions(-) diff --git a/lib/src/dartobjectutils_base.dart b/lib/src/dartobjectutils_base.dart index e36848e..700b7fe 100644 --- a/lib/src/dartobjectutils_base.dart +++ b/lib/src/dartobjectutils_base.dart @@ -611,18 +611,6 @@ X getObjectArrayFunctionPropOrThrow?>( if (e is Map) { return constructorFunc(e.cast()); } - // What if e is not a map? The constructorFunc expects Map. - // But in `getObjectArrayPropOrThrow`, the constructorFunc is `(e) => e as Y`. - // If Y is something else, this might work if constructorFunc handles it. - // But ConstructorFunc definition is `Y Function(Map params)`. - // So e MUST be a Map. - // If it is not a Map, this will throw type error at runtime when calling constructorFunc, - // or we should handle it? - // TS: `return v.map(constructorFunc) as X;` - // TS `ConstructorFunc` is `(params: object) => Y`. - // JS `object` can be almost anything. - // Dart `Map` is more specific. - // If we strictly follow `ConstructorFunc` typedef, we must pass a Map. throw ElementConversionException("Element in array is not a Map"); }).toList(); return list as X;