extend method

Interface extend(
  1. Set<InterfaceAttribute> otherAttributes
)

Extend this interface with another interface. If an attribute only exists one interface, then make it optional.

Implementation

Interface extend(Set<InterfaceAttribute> otherAttributes) {
  if (equalAttributes(attributes, otherAttributes)) {
    return this;
  }

  final Map<String, InterfaceAttribute> extendedAttributes = {};
  final otherAttributesMap = {
    for (final attribute in otherAttributes)
      attribute.attributeName: attribute,
  };
  for (final attribute in attributes) {
    if (!attribute.optional &&
        (otherAttributesMap[attribute.attributeName]?.optional ?? true)) {
      // This mandatory attribute does not exist in the other interface
      // Or the attribute is optional in the other interface
      // Make it optional.
      extendedAttributes[attribute.attributeName] =
          attribute.copyAsOptional();
    } else {
      extendedAttributes[attribute.attributeName] = attribute;
    }
  }
  for (final attribute in otherAttributes) {
    if (!attribute.optional &&
        (extendedAttributes[attribute.attributeName]?.optional ?? true)) {
      // Make it optional.
      extendedAttributes[attribute.attributeName] =
          attribute.copyAsOptional();
    } else {
      extendedAttributes[attribute.attributeName] = attribute;
    }
  }
  return Interface(
    name: name,
    attributes: extendedAttributes.values.toSet(),
  );
}