Search code examples
javascriptfunctional-programminggremlin

How can I reuse function chains in Javascript?


I'm using a functional library (Gremlin) to query a graph database. Invoking it looks like this:

g.V().has(...).out(...).hasLabel(...).in(...).next();

Some of my functional chains are very long, and I'd like to be able to reuse pieces of them for DRY purposes. For example:

const postProjection = () => (
  project("id", "title")
  .by(__.id())
  .by("title")
)

g.V().hasLabel("post").postProjection().next()

I know this doesn't work but that is the concept. I want to encapsulate a piece of this chain into a function that I can (somehow) inject into various other function chains from this library where needed. By dynamically constructing these calls with reusable segments I could dramatically cut down on repetition.

Is this possible to do?


Solution

  • If you want to call it using your exact syntax, you'd have to add functions to the Vertex (or whatever) prototype using something like this answer. That's sort of verbose, though, and not really the expected way to solve something like that. I would recommend making it a regular function call, for which your existing solution is pretty close except for needing a parameter:

    const postProjection = (vs) => (
      vs
      .project("id", "title")
      .by(__.id())
      .by("title")
    )
    
    const vs = g.V().hasLabel("post")
    postProjection(vs).next()