function sortFactories (factories) {
  const factoriesByName = {}

  factories.forEach(factory => {
    factoriesByName[factory.fn] = factory
  })

  function containsDependency (factory, dependency) {
    // TODO: detect circular references
    if (isFactory(factory)) {
      if (factory.dependencies.includes(dependency.fn || dependency.name)) {
        return true
      }

      if (factory.dependencies.some(d => containsDependency(factoriesByName[d], dependency))) {
        return true
      }
    }

    return false
  }

  const sorted = []

  function addFactory (factory) {
    let index = 0
    while (index < sorted.length && !containsDependency(sorted[index], factory)) {
      index++
    }

    sorted.splice(index, 0, factory)
  }

  // sort regular factory functions
  factories
    .filter(isFactory)
    .forEach(addFactory)

  // sort legacy factory functions AFTER the regular factory functions
  factories
    .filter(factory => !isFactory(factory))
    .forEach(addFactory)

  return sorted
}
Sort all factories such that when loading in order, the dependencies are resolved.

@param {Array} factories
@returns {Array} Returns a new array with the sorted factories.