npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@e22m4u/js-format

v0.0.10

Published

Расширенная версия format из Node.js модуля util

Downloads

35

Readme

@e22m4u/js-format

Расширенная версия format из Node.js модуля util

  • стандартные спецификаторы %s, %d и %j
  • добавлен %v для вывода примитивных значений и имен конструктора
  • добавлен %l для вывода списка через запятую 1, 2, 3

дополнительно:

  • встроенный класс Errorf с интерполяцией сообщения об ошибке

Установка

npm install @e22m4u/js-format

Примеры

Es-импорт

import {format} from '@e22m4u/js-format';

Спецификатор %v

Строки оборачиваются в кавычки, остальные примитивы приводятся к строке, а для более сложных типов выводится имя конструктора.

format('> %v', 'foo');        // > "foo"
format('> %v', '');           // > ""
format('> %v', 10);           // > 10
format('> %v', 0);            // > 0
format('> %v', NaN);          // > NaN
format('> %v', Infinity);     // > Infinity
format('> %v', true);         // > true
format('> %v', false);        // > false
format('> %v', {foo: 'bar'}); // > Object
format('> %v', new Date());   // > Date
format('> %v', new Map());    // > Map
format('> %v', () => 10);     // > Function
format('> %v', undefined);    // > undefined
format('> %v', null);         // > null

Спецификатор %v проектировался для вывода значений в сообщениях об ошибке, когда важно иметь представление об их типах. При этом, вывод содержимого объекта может быть избыточен для такой задачи. По этой причине, объекты приводятся к имени конструктора, что позволяет относительно точно определить тип выводимого значения.

class MyClass {}

format('> %v', 'MyClass');     // > "MyClass"
format('> %v', MyClass);       // > MyClass
format('> %v', new MyClass()); // > MyClass (экземпляр)

Спецификатор %l

Вывод элементов массива через запятую.

format('> %l', ['foo', 10, true]); // > "foo", 10, true

Элементы массива приводятся к строке по логике спецификатора %v

format('> %l', ['foo']);        // > "foo"
format('> %l', ['']);           // > ""
format('> %l', [10]);           // > 10
format('> %l', [0]);            // > 0
format('> %l', [NaN]);          // > NaN
format('> %l', [Infinity]);     // > Infinity
format('> %l', [true]);         // > true
format('> %l', [false]);        // > false
format('> %l', [{foo: 'bar'}]); // > Object
format('> %l', [new Date()]);   // > Date
format('> %l', [new Map()]);    // > Map
format('> %l', [() => 10]);     // > Function
format('> %l', [undefined]);    // > undefined
format('> %l', [null]);         // > null

Errorf

Конструктор класса Errorf передает аргументы функции format для формирования сообщения об ошибке.

Пример:

import {Errorf} from '@e22m4u/js-format';

throw new Errorf(
  'It requires one of %l, but %v given.',
  [true, false, 'y', 'n'],
  new Map(),
);
// Error: It requires one of true, false, "y", "n", but Map given.

Тесты

npm run test

Лицензия

MIT