maybeFromCode static method

NaturalLanguage? maybeFromCode(
  1. Object? code, [
  2. Iterable<NaturalLanguage>? languages
])

Returns an instance of the NaturalLanguage class from a three-letter Terminological ISO 639-2 code if it exists. Returns null otherwise.

The code parameter is required and should be an object representing the three-letter Terminological ISO 639-2 code for the language. Provided value could be any type of Object that returns ISO code on toString() call. For example it could be an instance of StringBuffer, String, Enum (in case of enum - .name.toUpperCase() will be used):

import 'package:sealed_languages/sealed_languages.dart';

enum IsoEnum { de, fr, ar }

void main() {
  final lang = NaturalLanguage.fromCode(IsoEnum.de);
  assert(lang == const LangDeu());
}

Or has a custom toString() override, i.e.:

import 'package:sealed_languages/sealed_languages.dart';

class CustomIsoCodeClass {
  const CustomIsoCodeClass({String code = 'deu'}) : _code = code;
  final String _code;

  @override
  String toString() => _code;
}

void main() {
  final lang = NaturalLanguage.fromCode(const CustomIsoCodeClass());
  assert(lang == const LangDeu());
}

The optional languages parameter can be used to specify a list of NaturalLanguage objects to search through. If this optional array is not provided (it's default to null), this will search in 0(1) access time case-insensitive UpperCaseIsoMap hash-map. Otherwise it will search in provided array with equivalent of firstWhere method, which might not be that fast comparing to the hashmap one, especially for large arrays. If you only need to add additional custom ISO instances of yours - consider using the copyWith method with your custom instances in default maps of this class (i.e. codeMap.copyWith(), map.copyWith() etc.). This will ensure O(1) performance for your custom instances too.

Implementation

static NaturalLanguage? maybeFromCode(
  Object? code, [
  Iterable<NaturalLanguage>? languages,
]) => languages == null
    ? codeMap.maybeFindByCode(code)
    : languages.firstIsoWhereCodeOrNull(
        IsoObject.maybe(code)?.maybeToValidIsoUpperCaseCode(
          exactLength: IsoStandardized.codeLength,
        ),
      );