class FilterCore implements FilterResolver, Serializable {

    @Override
    public LinkedHashSet<String> resolveCascadingOrder(Map<String, Set<String>> masterDependencies) {
        Deque<String> orderedNames = new LinkedList<String>();
        Queue<String> workingQueue = new LinkedList<String>(masterDependencies.keySet());
        int maxIterations =  (masterDependencies.size() * (masterDependencies.size() + 1)) / 2 + 1;
        while (workingQueue.size() > 0 && maxIterations-- > 0) {
            String currentName = workingQueue.remove();

            Set<String> masterDependency = masterDependencies.get(currentName);
            if (masterDependency == null || masterDependency.isEmpty()) {
                orderedNames.addFirst(currentName);
            } else {
                if (orderedNames.containsAll(masterDependency)) {
                    orderedNames.addLast(currentName);
                } else {
                    workingQueue.add(currentName);
                }
            }
        }
        if (maxIterations > 0) {
            return new LinkedHashSet<String>(orderedNames);
        } else {
            throw new JSException("Order cannot be resolved because of circular or non-existing dependencies.");
        }
    }

}