Skip to content
This repository was archived by the owner on Oct 12, 2024. It is now read-only.

Commit f4f2679

Browse files
committed
Add setNestedValueOnMapExtension to collections
1 parent 4c26ae8 commit f4f2679

File tree

3 files changed

+36
-1
lines changed

3 files changed

+36
-1
lines changed

lib/src/_all_src.g.dart

+1
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ export 'collections/src/non_nulls_on_map_extension.dart';
2525
export 'collections/src/null_filtered.dart';
2626
export 'collections/src/null_if_empty_extensions.dart';
2727
export 'collections/src/second_to_ninth_element_on_iterable_extension.dart';
28+
export 'collections/src/set_nested_value_on_map_extension.dart';
2829
export 'collections/src/unique_entries.dart';
2930
export 'core/src/ansi_styled_string.dart';
3031
export 'core/src/callbacks.dart';
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
//.title
2+
// ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
3+
//
4+
// 🇽🇾🇿 & Dev
5+
//
6+
// Copyright Ⓒ Robert Mollentze, xyzand.dev
7+
//
8+
// Licensing details can be found in the LICENSE file in the root directory.
9+
//
10+
// ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
11+
//.title~
12+
13+
extension SetNestedValueOnMapExtension on Map {
14+
/// Sets a [value] in a nested map structure, creating intermediate maps as
15+
/// needed.
16+
///
17+
/// Traverses the [keyPath] in the map, creating empty maps for any missing
18+
/// intermediate keys, and sets the [value] at the final key in the path.
19+
///
20+
/// **Example:**
21+
///
22+
/// ```dart
23+
/// final map = <String, dynamic>{};
24+
/// map.setNestedValue(['hello', 'world'], 'oh hey there!');
25+
/// print(map); // {hello: {world: oh hey there!}}
26+
/// ```
27+
void setNestedValue(List<dynamic> keyPath, dynamic value) {
28+
var currentLevel = this;
29+
for (var n = 0; n < keyPath.length - 1; n++) {
30+
currentLevel = currentLevel.putIfAbsent(keyPath[n], () => {});
31+
}
32+
currentLevel[keyPath.last] = value;
33+
}
34+
}

pubspec.yaml

+1-1
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
name: xyz_utils
1414
description: This package provides a set of utilities that are commonly used in Dart apps. It is also the foundation for other packages in the XYZ ecosystem.
1515
repository: https://github.com/robmllze/xyz_utils
16-
version: 0.60.0
16+
version: 0.61.0
1717

1818
## -----------------------------------------------------------------------------
1919

0 commit comments

Comments
 (0)