18

GitHub - hustcc/tplv: Nano(~170b) string template library for modern, based on E...

 4 years ago
source link: https://github.com/hustcc/tplv?
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Nano(~170 bytes), High performance string template library, based on ES6 String template syntax.

Install

$ npm i --save tplv

Usage

  • render template string
import { render } from 'tplv';

const template = '${ name }, ${value}(${percent} | Top ${array[2]})';

const data = {
  name: 'Hangzhou',
  value: 1200,
  percent: '13%',
  array: [1, 2, 3, 4]
};

render(template, data); // `Hangzhou, 1200(13% | Top 3)` will be got
  • compile mode

For 13x faster performance then render mode.

import { compile } from 'tplv';

const template = '${ name }, ${value}(${percent} | Top ${array[2]})';

const data = {
  name: 'Hangzhou',
  value: 1200,
  percent: '13%',
  array: [1, 2, 3, 4]
};

const fn = compile(template, ['name', 'value', 'percent', 'array']);

fn(data); // `Hangzhou, 1200(13% | Top 3)` will be got

Run performance test with rendering-test.

perf test

Principle

The core code and principles are as follows:

function render(template, data) {
  const ks = Object.keys(data);
  const vs = ks.map((k) => data[k]);

  const t = `return \`${template}\``;
  const f = new Function(...ks, t);

  return f(...vs);
}
# install dependence
$ npm install

# run test cases
$ npm run test

# run performance for render / compile mode
$ npm run perf

# build package
$ npm run build

License

MIT@hustcc.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK