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

purejs-helpers

v1.7.0

Published

JavaScript helpers

Downloads

95

Readme

Pure JS helpers plugin

Установка

npm i purejs-helpers

или

yarn add purejs-helpers

Использование

Получение языка локализации по умолчанию

import { locale } from 'purejs-helpers';

console.log(locale); // 'ru-RU'

Определение окружения по домену

import { getEnvironment } from 'purejs-helpers';

// http://localhost:8080/
getEnvironment(); // { server: 'production', mode: 'development' }

Определение казахского домена

import { isKZ } from 'purejs-helpers';

// https://any-domain.kz
isKZ(); // true

Работа с Cookie

import { cookie } from 'purejs-helpers';

cookie.get('any_key'); // 'value'

cookie.set('name', 'value', {
  'Domain': 'domain.com', // <string>
  'Path': '/page', // <string>. Default: '/'
  'Expires': new Date(3000, 11, 31), // <Date|string>
  'Max-Age': 3600, // <number>
  'HttpOnly': true, // <boolean>
  'Secure': true, // <boolean>
  'SameSite': 'Strict', // <string>. Strict | Lax | None
});

cookie.delete('any_key');

Определение типа переданного значения

import { getType } from 'purejs-helpers';

getType(); // 'Undefined'
getType([]); // 'Array'
getType({}); // 'Object'
getType(new Date()) // 'Date'
getType(() => {}); // 'Function'
getType(function() {}); // 'Function'
getType(Promise.resolve()); // 'Promise'
getType(new Proxy({}, {})); // 'Object'
getType(new Event('any')); // 'Event'
getType(42.13); // 'Number'
getType('string'); // 'String'
getType(''); // 'String'
getType(null); // 'Null'
getType(undefined); // 'Undefined'

Добавление ведущего нуля

import { leadingZero } from 'purejs-helpers';

leadingZero(9); // '09'
leadingZero(42); // '42'

Преобразование числа в сумму

import { currencyMask } from 'purejs-helpers';

currencyMask(1840); // '1 840 ₽'
currencyMask(1840.621); // '1 840.6 ₽'
currencyMask(1840.621, 3); // '1 840.621 ₽'

Проверка объекта даты на валидность

import { dateIsValid } from 'purejs-helpers';

dateIsValid(null); // false
dateIsValid(new Date()); // true
dateIsValid(new Date('9999-99-99')); // false
dateIsValid(new Date('2023-03-16')); // true

Преобразование даты в ISO формат

import { toISODate } from 'purejs-helpers';

toISODate(new Date(2020, 9, 21)); // '2020-10-21'

Преобразование даты в формат DD.MM.YYYY

import { dateToDateShort } from 'purejs-helpers';

dateToDateShort(new Date(2020, 9, 21)); // '21.10.2020'

Преобразование ISO даты в формат DD.MM.YYYY

import { ISOToDateFormat } from 'purejs-helpers';

ISOToDateFormat('1979-12-03'); // '03.12.1979'

Преобразование даты в формат DD.MM.YYYY, HH:MM

import { dateTime } from 'purejs-helpers';

dateTime(new Date(2020, 9, 21, 8, 45)); // '21.10.2020, 08:45'

Преобразование даты в формат WW, DD MMMM YYYY

import { dateToDateLong } from 'purejs-helpers';

// '21 октября 2020'
dateToDateLong({
  date: new Date(2020, 9, 21),
});

// 'ср, 21 октября 2020'
dateToDateLong({
  date: new Date(2020, 9, 21),
  showWeekDay: true,
});

// 'ср, 21 октября'
dateToDateLong({
  date: new Date(2020, 9, 21),
  showWeekDay: true,
  showYear: false,
});

// '21 октября'
dateToDateLong({
  date: new Date(2020, 9, 21),
  showYear: false,
});

Преобразование даты в формат HH:MM

import { dateToHoursMinutes } from 'purejs-helpers';

dateToHoursMinutes(new Date(2020, 9, 21, 8, 45)); // '08:45'

Преобразование числа в формат времени HH:MM

import { minutesToHoursMinutes } from 'purejs-helpers';

minutesToHoursMinutes(480); // '08:00'
minutesToHoursMinutes(-480); // '-08:00'

Получение объекта с московским временем из даты

import { getMoscowTime } from 'purejs-helpers';

// { hour: '12', minute: '00', timestamp: 1643041320000 }
getMoscowTime('2022-05-02T08:00:00Z');

Получение номера недели в году

import { weekOfYear } from 'purejs-helpers';

weekOfYear(new Date(2020, 9, 21)); // 43

Получения даты начала недели по номеру недели

import { weekNumberToDate } from 'purejs-helpers';

weekNumberToDate(2020, 43); // Wed Oct 21 2020 00:00:00 GMT+0300

Форматирование по маске

import { maskIt } from 'purejs-helpers';

maskIt.format('+7 999 999-99-99', '12345678910'); // '+7 234 567-89-10'
maskIt.format('ZZZ-xxx', 'АБВГДЕ'); // 'АБВ-xxx'
maskIt.check('+7 999 999-99-99', '12345678910'); // true
maskIt.check('+7 999 999-99-99', '+7 234 567-89-10'); // true
maskIt.clear('+7 234 567-89-10') // '72345678910'

Окончания русских слов

import { wordEndings } from 'purejs-helpers';

wordEndings(17, ['метр', 'метра', 'метров']); // '17 метров'

Преобразование числа в расстояние

import { distanceFormat } from 'purejs-helpers';

distanceFormat(42); // '42 метра'
distanceFormat(42, true); // '42 м'
distanceFormat(1042); // '1.42 км'

Получение преобразованного размера файла

import { bytesToSize } from 'purejs-helpers';

bytesToSize(40031); // '39.09 кБ'

Преобразование файла в Base64

import { convertFileToBase64 } from 'purejs-helpers';

convertFileToBase64(<File>); // '<Base64>'

Сокращение ФИО до формата ФффИО или ФфффИ (если нет отчества)

import { shortName } from 'purejs-helpers';

shortName('Светлова Александра Андреевна'); // 'СвеАА'
shortName('Бекр фуркад'); // 'БекрФ'
shortName('cветлова'); // 'Светл'

Удаление ключей из объекта с клонированием

import { removeObjectKeys } from 'purejs-helpers';

removeObjectKeys(['a'], { a: 13, b: 42 }); // { b: 42 }

Рекурсивное (глубокое) копирование объекта (массива)

import { deepClone } from 'purejs-helpers';

const object = {
  foo: 'bar',
  obj: { a: 1, b: 2 },
  array: [{ id: 1, text: 42 }, 'string'],
  any: undefined,
  number: 0,
  date: new Date(),
};

deepClone(object);

const arr = [{ id: 1, text: 42 }, 'string'];

deepClone(arr);

Мемоизация

import { memo } from 'purejs-helpers';

const add = (x, y) => x + y;
const memoAdd = memo(add);

memoAdd(24, 42); // Calculated
memoAdd(42, 24); // From cache

Поиск по поисковой фразе в списке по переданным ключам объекта

import { searchByKeys } from 'purejs-helpers';

const options = [
  {
    title: 'Any',
    answer: {
      text: 'text',
    },
  },
];

searchByKeys({
  search: 'text any',
  options,
  keys: ['title', 'answer.text'],
});

Проверка поддержки браузером копирования/вставки

import { checkClipboardFunctionality } from 'purejs-helpers';

await checkClipboardFunctionality(); // { copy: true, paste: true }

Получение UTM-меток из поисковой строки

import { getUTMLabels } from 'purejs-helpers';

// https://any-domain?utm_any=value
getUTMLabels(); // { any: 'value' }

Good Boy License

We’ve released the helpers functions either under MIT or the Good Boy License. We invented it. Please do whatever your mom would approve of:

  • Download
  • Change
  • Fork