Usage
Morphing Keys

Morphing Keys

Since the key returned from calling the $use or $get method is an array of strings, crafted from the nodes in the register, it is possible to transform the key using any array method (opens in a new tab). There are several methods, on the array prototype (opens in a new tab), that can be used to transform the key. You can learn more about these methods in the MDN Web Docs (opens in a new tab).

The following code snippet is a continuation of the previous example:

const register = {
  foo: {
    baz: (id: number) => `/bazaar/${id}`,
    bar: 10,
  },
};
 
const builder = createBuilder(register, { prefix: ["root"] });

The slice method

One of such methods is the slice (opens in a new tab) method. The slice (opens in a new tab) method is a function that extracts a section of an array and returns a new array. The following code snippet demonstrates how to use the slice (opens in a new tab) method:

// extracting the first two elements of the array
builder.foo.baz.get().slice(2); // ["root", "foo"]

The join method

Another array method that can be used to transform the key is the join (opens in a new tab) method. The join (opens in a new tab) method is a function that concatenates the value in an array into a single string, using a separator. The following code snippet demonstrates how to use the join (opens in a new tab) method:

// concatenating the elements of the array into a single string
builder.foo.baz.get().join("."); // "root.node.foo.baz"

Conclusion

Note that to get the key as a string, you can call the $get method on the root node, then pass it the key, as an argument. This will return the key as a string. The $get method is typed to suggest the possible keys that can be passed to it, based on the structure of the register.

The following code snippet demonstrates how to get the key as a string:

builder.$get("root.node.foo.baz"); // "root.node.foo.baz"