0.0.2 • Published 3 years ago

text-with-benefits v0.0.2

Weekly downloads
-
License
MIT
Repository
github
Last release
3 years ago

text-with-benefits

Tiny library for storing data in strings

  • Created with TypeScript;
  • 100% unit tests coverage;
  • tiny library size (only ~600 bytes).

Motivation

Sometimes you work with data that only affects the view layer. In my case, the attributes of a text comment became such data. They were not taken into account in the backend business logic and were immutable.

I decided that we could store these values directly in text. Before displaying the text, they need to be cut out, when saving, they must be added again.

As a result, this project was born.

Documentation

There are two exported functions: pack and unpack.

pack takes two arguments: string with your text and object with data. The data types at the top level of an object are limited: only strings, numbers, booleans, arrays, and objects are supported. Arrays and objects are converted using the JSON.stringify method so that all nested data restrictions match the specifications of this method.

pack returns special string that contains original text with formatted data. This string is ready to be stored on back-end or other storages.

Example:

const textWithBenefints = pack('My text', { 
    registered: true 
});

// Output: 
// My%20text<$$registered boolean "true"$$>

unpack takes a string generated by pack method and returns object with two keys:

  • text: clear text without values;
  • data: object with stored data.

TypeScript is well-supported, so you can pass a type argument to pack.

If string passed to unpack is malformed or doesn't contain any data, it will be returned as text key. data key will be null.

Example:

const { text, data } = unpack(textWithBenefits);

// text: "My text"
// data: { registered: true }

TypeScript example:

interface TextData {
    registered: boolean
}
const { text, data } = unpack<TextData | null>(textWithBenefits);

// text: "My text"
// data: { registered: true }

TODO

  • built-in integrations for React and Vue;
  • final data size optimization.