diff --git a/benchmark/enum_benchmark.dart b/benchmark/enum_benchmark.dart new file mode 100644 index 0000000..fc19312 --- /dev/null +++ b/benchmark/enum_benchmark.dart @@ -0,0 +1,44 @@ +import 'package:dartobjectutils/dartobjectutils.dart'; +import 'dart:core'; + +class MyEnum { + final String name; + const MyEnum(this.name); + @override + String toString() => "MyEnum.$name"; +} + +void main() { + // Setup + // Make these large enough to show a difference. + // 1000 enum values + // 10000 input elements + final int enumSize = 1000; + final int inputSize = 10000; + + final values = List.generate(enumSize, (i) => MyEnum('val$i')); + // Create inputs that are scattered across the enum values + final inputList = List.generate(inputSize, (i) => 'val${i % enumSize}'); + + final map = {'data': inputList}; + + print('Running benchmark with enumSize=$enumSize, inputSize=$inputSize'); + + // Warmup + print('Warming up...'); + for (int i = 0; i < 5; i++) { + getEnumArrayPropOrThrow(map, 'data', values); + } + + // Measure + print('Measuring...'); + final stopwatch = Stopwatch()..start(); + final iterations = 20; + for (int i = 0; i < iterations; i++) { + getEnumArrayPropOrThrow(map, 'data', values); + } + stopwatch.stop(); + + print('Total time: ${stopwatch.elapsedMilliseconds} ms'); + print('Average time: ${stopwatch.elapsedMilliseconds / iterations} ms'); +} 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..093ed2e 100644 --- a/lib/src/dartobjectutils_base.dart +++ b/lib/src/dartobjectutils_base.dart @@ -594,29 +594,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 +780,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 +792,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 +804,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 +815,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 +824,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 +843,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 +855,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 +876,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 +895,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 +907,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 +923,8 @@ List getBooleanArrayPropOrThrow( } } throw ArgumentError( - message ?? '$prop not found as boolean[] in ${props.runtimeType}'); + message ?? '$prop not found as boolean[] in ${props.runtimeType}', + ); } // --- Enum --- @@ -968,14 +993,21 @@ List getEnumArrayPropOrThrow( if (v is List) { final extractor = keyExtractor ?? (val) => val.toString().split('.').last; + final valueMap = {}; + for (final val in values) { + final key = extractor(val); + if (!valueMap.containsKey(key)) { + valueMap[key] = val; + } + } return v.map((e) { - try { - return values.firstWhere((val) => extractor(val) == e); - } catch (_) { - throw ElementConversionException( - 'Unknown type for enum $e ${e.runtimeType}', - ); + final val = valueMap[e]; + if (val != null) { + return val; } + throw ElementConversionException( + 'Unknown type for enum $e ${e.runtimeType}', + ); }).toList(); } } @@ -993,8 +1025,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 +1043,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'], ); });