Skip to content

Wrong merge with empty list #12

@n-borisov-ms

Description

@n-borisov-ms

So, sometimes we can have a source map which built with other custom maps. Sometimes some of the them may be an empty.

Data:

$map1: ( 
  x: (), 
  y: (2: 2) 
);

$map2: ( 
  x: (1: 1), 
  y: (3: 3) 
);

// Result
(
  x: (),
  y: (2: 2, 3: 3)
)

// Expected
(
  x: (1: 1),
  y: (2: 2, 3: 3)
);

Solution:

// Add small helper function 
@function convert-empty-list-to-map($source) {
  @if ( type-of($source) == list and length($source) == 0 ) {
    @return map-remove((x:x), x);
  }
  @return $source;
};

// Updated function
@function recursive-map-merge($source1, $source2 ) {
  @if ( type-of($source1) == map or ( type-of($source1) == list and length($source1) == 0) ) and
      ( type-of($source2) == map or ( type-of($source2) == list and length($source2) == 0) ) {
    
    // Check both maps and convert to [map] when empty 
    $map1: convert-empty-list-to-map($source1);
    $map2: convert-empty-list-to-map($source2);

    $result: $map1;

    @each $key, $value in $map2 {
      // Check both childs and convert to map when empty
      $map1-child: convert-empty-list-to-map(map-get($map1, $key));
      $map2-child: convert-empty-list-to-map($value);

      @if ( type-of($map1-child) == map and type-of($map2-child) == map ) {
        $result: map-merge($result, ($key: recursive-map-merge($map1-child, $map2-child)));
      }
      @else {
        $result: map-merge($result, ($key: $value));
      }
    }

    @return $result;
  }
  @else {
    @warn "recursive-map-merge() expects it\'s parameters to be map types!";
    @return null;
  }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions