All Downloads are FREE. Search and download functionalities are using the official Maven repository.

graphql.util.NodeZipper Maven / Gradle / Ivy

There is a newer version: 230521-nf-execution
Show newest version
package graphql.util;

import graphql.PublicApi;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;

import static graphql.Assert.assertNotNull;

@PublicApi
public class NodeZipper {

    private final T curNode;
    private final NodeAdapter nodeAdapter;
    // reverse: the breadCrumbs start from curNode upwards
    private final List> breadcrumbs;


    public NodeZipper(T curNode, List> breadcrumbs, NodeAdapter nodeAdapter) {
        this.curNode = assertNotNull(curNode);
        this.breadcrumbs = assertNotNull(breadcrumbs);
        this.nodeAdapter = nodeAdapter;
    }

    public T getCurNode() {
        return curNode;
    }

    public List> getBreadcrumbs() {
        return new ArrayList<>(breadcrumbs);
    }

    public T getParent() {
        return breadcrumbs.get(0).getNode();
    }

    public static  NodeZipper rootZipper(T rootNode, NodeAdapter nodeAdapter) {
        return new NodeZipper(rootNode, new ArrayList<>(), nodeAdapter);
    }

    public NodeZipper modifyNode(Function transform) {
        return new NodeZipper(transform.apply(curNode), breadcrumbs, nodeAdapter);
    }

    public NodeZipper withNewNode(T newNode) {
        return new NodeZipper(newNode, breadcrumbs, nodeAdapter);
    }

    public NodeZipper moveUp() {
        T node = getParent();
        List> newBreadcrumbs = breadcrumbs.subList(1, breadcrumbs.size());
        return new NodeZipper<>(node, newBreadcrumbs, nodeAdapter);
    }

    public T toRoot() {
        T curNode = this.curNode;
        for (Breadcrumb breadcrumb : breadcrumbs) {
            // just handle replace
            Map> newChildren = nodeAdapter.getNamedChildren(breadcrumb.getNode());
            final T newChild = curNode;
            NodeLocation location = breadcrumb.getLocation();
            newChildren.get(location.getName()).set(location.getIndex(), newChild);
            curNode = nodeAdapter.withNewChildren(breadcrumb.getNode(), newChildren);
        }
        return curNode;
    }


}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy