Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(1303)

Side by Side Diff: pkg/analyzer/lib/src/util/yaml.dart

Issue 1425393002: Map merging. (Closed) Base URL: git@github.com:dart-lang/sdk.git@master
Patch Set: Created 5 years, 1 month ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
(Empty)
1 // Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file
2 // for details. All rights reserved. Use of this source code is governed by a
3 // BSD-style license that can be found in the LICENSE file.
4
5 library analyzer.src.util.yaml;
6
7 import 'dart:collection';
8
9 /// Merges two maps (of yaml) with simple override semantics, suitable for
10 /// merging two maps where one map defines default values that are added to
11 /// (and possibly overriden) by an overriding map.
12 class Merger {
13
14 /// Merges a default [o1] with an overriding object [o2].
15 ///
16 /// * lists are merged (without duplicates).
17 /// * lists of scalar values can be promoted to simple maps when merged with
18 /// maps of strings to booleans (e.g., ['opt1', 'opt2'] becomes
19 /// {'opt1': true, 'opt2': true}.
20 /// * maps are merged recursively.
21 /// * if map values cannot be merged, the overriding value is taken.
22 ///
23 Object merge(Object o1, Object o2) {
24 // Handle promotion first.
25 if (o1 is List && o2 is Map<Object, bool>) {
26 o1 = new Map.fromIterable(o1, key: (item) => item, value: (item) => true);
27 }
28 if (o1 is Map<Object, bool> && o2 is List) {
29 o2 = new Map.fromIterable(o2, key: (item) => item, value: (item) => true);
30 }
31
32 if (o1 is Map && o2 is Map) {
33 return mergeMap(o1, o2);
34 }
35 if (o1 is List && o2 is List) {
36 return mergeList(o1, o2);
37 }
38 // Default to override.
39 return o2;
40 }
41
42 /// Merge lists, avoiding duplicates.
43 List mergeList(List l1, List l2) =>
44 new List()..addAll(l1)..addAll(l2.where((item) => !l1.contains(item)));
45
46 /// Merge maps (recursively).
47 Map mergeMap(Map m1, Map m2) {
48 Map merged = new HashMap()..addAll(m1);
49 m2.forEach((k, v) {
50 merged[k] = merge(merged[k], v);
51 });
52 return merged;
53 }
54 }
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698