Develop an encoding feature utilizing mustache templates

Exploring the world of mustache for the first time, I haven't been able to find the answer through my basic searching. I am attempting to create a template in Typescript for encoding an unknown number of fields. The structure will be something like this:

encode(writer: _m0.Writer = _m0.Writer.create()) {
  writer.uint32(10).string(xx)
  writer.uint32(18).string(xx)
  writer.uint32(26).string(xx)
  ...
  etc

I want to increment the value in uint32(xx) by 8 each time. This is what I have in my template so far:

  encode(writer: _m0.Writer = _m0.Writer.create()) {
    {{#fields}}
      writer.uint32().string({field}}
    {{/fields}}
  }

Do you think it's possible to achieve what I'm aiming for here?

Answer №1

If you are willing to incorporate some TypeScript logic, then this task can definitely be accomplished.

Before diving in: remember to enclose all tags within double curly braces. Instead of writing .string({field}}, ensure it is written as .string({{field}}}.

When it comes to interpolating a value with .uint32(), the variable tag is what you need. Let's call it counter:

.uint32({{counter}})

As a result, your complete template will appear like this:

encode(writer: _m0.Writer = _m0.Writer.create()) {
  {{#fields}}
    writer.uint32({{counter}}).string({{field}}}
  {{/fields}}
}

The pressing question now is how to guarantee that counter exists and assumes the correct value with each iteration of {{#fields}}...{{/fields}}. One straightforward method is to prep the data you provide to the template so that every field aligns with a corresponding counter with the accurate value:

{
    fields: [{
        field: 'ab',
        counter: 10,
    }, {
        field: 'cd',
        counter: 18,
    }, {
        field: 'ef',
        counter: 26,
    }],
}

However, if you prefer an automatic computation method, lambdas can help (refer to the link provided for more details). To begin with, create a function that generates functions which produce the subsequent number in a series upon invocation:

function iterate(initialValue, increment) {
    let value = initialValue;
    return function() {
        const oldValue = value;
        value += increment;
        return oldValue;
    };
}

Now, introduce this function as the counter in the data passed to the template:

{
    fields: [{
        field: 'ab',
    }, {
        field: 'cd',
    }, {
        field: 'ef',
    }],
    counter: iterate(10, 8),
}

Using either approach will yield the same outcome:

encode(writer: _m0.Writer = _m0.Writer.create()) {
    writer.uint32(10).string(ab}
    writer.uint32(18).string(cd}
    writer.uint32(26).string(ef}
}

You can experiment with this setup in the Wontache playground by inserting the provided code into its load/store box.

{"data":{"text":"{\n    fields: [{\n        field: 'ab',\n    }, {\n        field: 'cd',\n    }, {\n        field: 'ef',\n    }],\n    counter: (function(initialValue, increment) {\n        let value = initialValue;\n        return function() {\n            const oldValue = value;\n            value += increment;\n            return oldValue;\n        };\n    }(10, 8)),\n}"},"templates":[{"name":"encoding","text":"encode(writer: _m0.Writer = _m0.Writer.create()) {\n  {{#fields}}\n    writer.uint32({{counter}}).string({{field}}}\n  \{{/fields}}\n}"}]}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When TableRow's onSelectChange is activated, it correctly selects the entire Table Group instead of an

In my React TypeScript application, I am working with an Array of Objects to populate a table. Each table row is grouped by category, and within each row, there is a select box that triggers an event to select all items with the same category: https://i.s ...

Tips for updating the font size of your MUI Accordion title

I was attempting to adjust the font size of the MUI-5 Accordion title. It seems like I need to override it, but I am unsure about how to do so with CSS in MUI-5. Instead of 'SX', it uses 'htmlSx'. When I tried using it, it did not produ ...

Guide on Linking a Variable to $scope in Angular 2

Struggling to find up-to-date Angular 2 syntax is a challenge. So, how can we properly connect variables (whether simple or objects) in Angular now that the concept of controller $scope has evolved? import {Component} from '@angular/core' @Comp ...

Encountering a sort error in Angular 8 when attempting to sort an Observable

I am struggling to organize an observable that is retrieved from a service using http.get. I have attempted to sort the data both from the service and in the component after subscribing. However, I keep encountering the error "Sort is not a function". As ...

Middleware transformation pipeline implemented using Typescript types

In my quest to create a function that empowers middlewares (specifically Express ones) to enhance the Request object by adding properties to it, I aim for subsequent middlewares in the chain to utilize these additions while preserving data types. An examp ...

What is the best method for excluding attributes from a nested model in sequelize?

In my project, there are 2 models called User and Role, and they have a many-to-many relationship. To manage this connection, I introduced a third model named UserRole. The issue arises when the UserRole is also retrieved in the query below: async getUser ...

Using TypeScript, the Generator functions in Redux Saga do not execute nested effects in sequence when using yield put

I need to handle multiple asynchronous actions and ensure that a third action is only triggered after the first two have successfully completed. I have created three saga workers for this purpose: export function* emailUpdateRequestSaga(action: IEmailUpda ...

When implementing Typescript, utilizing the useContext() function may result in the following error: "Cannot assign type 'never[]' as an argument to the parameter type

When attempting to utilize the useContext() hook in TypeScript, I encountered several errors. Initially, useState is set to an empty array of the interface Phone which is imported. The state and setState are then passed in the value prop. import { createCo ...

Sending a parameter between files in a React application: a step-by-step guide

I am currently working on a Pokedex website where I have Pokemon cards displaying data from a JSON file. When a user clicks on a card, a modal view appears with more detailed information about that specific card. I need help in ensuring that only the deta ...

Show the current time using Moment.js

I am currently working on developing a clock component that displays the current time in real-time. Issue: The initial time is correctly displayed when the page loads (HH:mm A), but the clock does not update dynamically. clock.component.ts : import { ...

Typescript's dynamic React component and its conditional types

I am currently working on a dynamic React component and I am facing an issue with properly passing the correct propType based on the selected component. The error arises when using <SelectComponent {...props.props} /> because the props do not match t ...

What is the best way to import a TypeScript file in index.js?

I've recently developed an application using the react-express-starter template. I have a "server" directory where the backend is created by nodejs, containing an index.js file: const express = require('express'); const app = express(); c ...

UI not reflecting updated form validation after changes made

Currently, I have a situation where I am passing a form from the Parent component to the Child component. All the validations are being handled in the Parent component and the Child component is simply rendering it. However, there is a specific field calle ...

Conceal certain components when a user is authenticated

Below is the content of my app.component.html: <nav class="navbar navbar-expand-lg navbar-light bg-light"> <div class='container'> <ul class="nav navbar-nav"> <li class='nav-item'> <a clas ...

Performing optimized searches in Redis

In the process of creating a wallet app, I have incorporated redis for storing the current wallet balance of each user. Recently, I was tasked with finding a method to retrieve the total sum of all users' balances within the application. Since this in ...

How can Typescript help enhance the readability of optional React prop types?

When working with React, it is common practice to use null to indicate that a prop is optional: function Foo({ count = null }) {} The TypeScript type for this scenario would be: function Foo({ count = null }: { count: number | null }): ReactElement {} Wh ...

Accessing Webpack bundles using an "@" symbol for imports

I am currently working on bundling a Node Express server that was created using TypeScript and is being packaged with Webpack. Everything seems to be running smoothly when I compile/transpile the code into one JavaScript file called server.js. However, af ...

How can you alter the background color of a Material UI select component when it is selected?

I am attempting to modify the background color of a select element from material ui when it is selected. To help illustrate, I have provided an image that displays how it looks when not selected and selected: Select Currently, there is a large gray backgr ...

Is there a way to efficiently convert several strings within an object that has been retrieved from an HTTP request into another language, and subsequently save this object with the

Is there a way for me to translate some strings in an object before storing it in another http request using the Google Translate API? I am currently getting the object from one http request and saving it with a put method. How can this be achieved? servi ...

What is the best way to encode a type that necessitates a specific superclass and interface implementation?

In order to achieve my goal, I need to extend a library class that is part of the React components I am creating. Here's an example of the original library class I'm working with: class ReactComponent<T, U> { render() { return "some ht ...