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

@apicart/js-utils

v1.0.0-alpha7

Published

A small set of useful utilities for easier development

Downloads

96

Readme

Website: https://apicart.net Sign Up: https://accounts.apicart.net/

  • A small set of useful utilities for simpler development.
  • 7 Kb minified (3 Kb Gzipped)
  • ✅ Supports IE 10 +
  • TRY IT ON CODEPEN

Content

Installation

Cdn

<!-- Master version from Github -->
<script src="https://cdn.jsdelivr.net/gh/apicart/js-utils/dist/utils.min.js"></script>

<!-- v1.0.0-alpha1 from jsdelivr.net -->
<script src="https://cdn.jsdelivr.net/npm/@apicart/[email protected]/dist/utils.min.js" integrity="sha256-eo4u9fSxiYhrAT7PpLhbWEFHsiuBnTV0krDfY7VeQE4=" crossorigin="anonymous"></script>

Npm & Yarn

npm i @apicart/js-utils

yarn add @apicart/js-utils

Ajax (Utils.ajax)

This component simplifies work with the XMLHttpRequest.

Parameters

| Parameter | async | cache | data | headers | method | queryParameters | timeout | url | withCredentials | start | complete | |---------------|---------|---------|--------|---------|--------|-----------------|---------|--------|-----------------|---------------|---------------| | Type | boolean | boolean | object | object | string | object | number | string | boolean | function | function | | Default value | true | true | {} | {} | get | {} | 5000 | '' | false | function() {} | function() {} |

get(url: string, parameters: any = {}): Promise<any>
post(url: string, parameters: any = {}): Promise<any>
request(parameters: any = {}): Promise<any>
Utils.Ajax.get('https://example.com', {
    complete: function (response){
        alert('Done');
    }
});

Utils.Ajax.post('https://example.com', {
    complete: function (response){
        alert('Done');
    }
});

Utils.Ajax.request({
    url: 'https://example.com',
    method: 'post',
    complete: function (response){
        alert('Done');
    }
});

Console (Utils.Console)

Wraps the default browser console and ensures the cross-browser compatibility.

error(...args: any[]): Console
Utils.Console.error('Some', 'Value');
log(...args: any[]): Console
Utils.Console.log('Some', 'Value');
warn(...args: any[]): this
Utils.Console.warn('Some', 'Value');

DOM (Utils.Dom)

Simplifies work with Document Object Model.

addClass(element: Element, classes: string|string[]): Dom

Adds one or multiple classes to selected elements.

Utils.Dom.addClass(document.querySelector('.element'), 'first second third');
findParent(element: Element, selector: string): Element|null

Returns element parent based on selector. If the parent was not found, returns null.

Utils.Dom.findParent(Element $element, '.parent');
matches(element: Element, selector: string): boolean

Returns true if element matches selector. If not, returns false.

Utils.Dom.matches(document.querySelector('.element', '.selected');
on(eventTypes: string|string[], selectors: string|string[], callback: Function): this

Adds event listener to selected elements. Works even on dynamically added elements.

Utils.Dom.on('click', '.element', function() {...});
removeClass(element: Element, classes: string): Dom

Removes one or multiple classes from selected elements.

Utils.Dom.removeClass(document.querySelector('.element'), 'first second third');
trigger(element: any[], event: string): this

Triggers an event on selected element.

Utils.Dom.trigger(document.querySelector('.button'), 'click');

Event Dispatcher (Utils.eventDispatcher)

Event dispatcher allows you communicate between components based on events. If for example a product was added into the cart, you can trigger productAddedIntoCart event. Listeners waiting for this event will be triggered with given values.

addListener(listenerKey: string, event: string|string[], callback: Function, singleAction: boolean = false): EventDispatcher

This method registers listener. If the singleAction parameter is set to true, the listener will be triggered only once (it is useful for dynamically generated listeners).

Utils.EventDispatcher.addListener('number-dumper', 'send-number', function (number) {
    console.log(number);
}, true); // Single action is set to true, so the listener will be triggered only once
Utils.EventDispatcher.addListener('product-popup', 'product-added-into-cart', function (parameters) {...});
removeListener(listenerKey: string, event: string|string[]): this

Removes listener from given event.

Utils.EventDispatcher.removeListener('listener', 'event1 event2');
Utils.EventDispatcher.removeListener('listener', ['event1', 'event2']);
Utils.EventDispatcher.removeListener('number-dumper', 'send-number');
dispatchEvent(event: string|string[], parameters: any|null = []): EventDispatcher

Triggers selected event. Given parameters are provided to the listeners.

Utils.EventDispatcher.dispatchEvent('event1 event2');
Utils.EventDispatcher.dispatchEvent(['event1', 'event2']);
Utils.EventDispatcher.dispatchEvent('rozesli-cislo', 1);

Json (Utils.Json)

isJson(content: any|null): boolean

Checks if the provided data are json. If not returns false.

Utils.Json.isJson('{a: "b"}'); // true
Utils.Json.isJson('Text'); // false
parse(content: any|null): any

Converts json to object. If the provided data are not json, returns an empty object.

Utils.Json.parse('{a: "b"}'); // {a: "b"}
stringify(object: any): string

Converts javascript object into json.

Utils.Json.stringify({a: "b"}); // "{a: "b"}"

Local Storage (Utils.LocalStorage)

clear(): this

Clears local storage

Utils.LocalStorage.clear();
getItem(key: string): any | null

Returns item parsed as json

Utils.LocalStorage.getItem('someItem');
setItem(key: string, value: any, expiration: number | null = null): this

Saves item into local storage. Automatically converts any possible type into json and stringifies it.

Utils.LocalStorage.setItem('someItem', {a: 1});
removeItem(key: string): this

Removes item from local storage.

Utils.LocalStorage.removeItem('someItem');
hasItem(key: string): boolean

Returns true if given key exists in the local storage

Utils.LocalStorage.hasItem('someItem');
getActualTimestamp(): number

Returns actual time in timestamp

Utils.LocalStorage.getActualTimestamp();

Loops (Utils.Loops)

forEach(iterable: any | null, callback: Function): Loops

Function that is able to iterate over objects and arrays. Inside this function the this object is an object containing counter, iterableLength parameters and isFirst, isLast, isEven, isOdd functions.

Utils.Loops.forEach([1, 2, 3], function(value, key) {...});
Utils.Loops.forEach([1, 2, 3], function(value, key) {console.log(this.counter, this.isFirst());...});
Utils.Loops.forEach(document.querySelectorAll('.element'), function(element, key) {...});

Objects (Utils.Objects)

assign(object: Object, keyPath: string|string[], value: any): void

Polyfill of the Object.assign for older browsers. Is able to assign nested properties.

var a = {x: 1};
Utils.Objects.assign(a, 'y.z', 2); // {x: 1, y: {z: 2}}
copy(object: Object): Object

Returns a new copy of the provided object. Object copy is without a reference to copied object.

Utils.Objects.copy({a: "b"}); // {a: "b"}
delete(object: Object, keyPath: string|string[]): void

Removes keys from object. Is able to remove nested keys.

Utils.Objects.delete({a: {b: {c: "1", d: "2"}}}, 'a.b.c'); // {a: {b: {d: "2"}}}
find(object: Object, keyPath: string|string[]): any | null

This method is able to find a value according to provided key. The key can be arbitrarily nested. If the key doesnt exists, returns null.

Utils.Objects.find({a: {b: {c: "1"}}}, 'a.b.c'); // 1
keyExists(object: Object, keyPath: string|string[]): boolean

Returns true if given path exists

Utils.Objects.keyExists('some.nested.key');
isObject(data: any): boolean

Checks if the provided data are object.

Utils.Objects.isObject({a: "b"}); // true
Utils.Objects.isObject(null); // false
Utils.Objects.isObject([]); // false
merge(...args: Object[]): Object

Merges two or more objects into a new one. The new object is without reference to the merged objects.

Utils.Objects.merge({a: "1"}, {b: "2"}); // {a: "1", b: "2"}
Utils.Objects.merge({a: {b: "1"}}, {a: {c: "2"}}); // {a: {b: "1", c: "2"}}
values(object: Object): any[]

Removes keys from provided object and returns its data. Odstraní klíče daného objektu a vrátí jejich data.

Utils.Objects.values({a: "b", c: "d"}): // ["b", "d"]

Strings (Utils.Strings)

firstToUpper(string: string): string

Converts first letter of the given string to upper case.

Utils.Strings.firstToUpper('test') // Test
generateHash(length: number, characters = 'abcdefghijklmnopqrstuvwxyz0123456789'): string

Generates hash from given characters and length. Vytvoří hash o dané délce ze zadaných znaků.

Utils.Strings.generateHash(32) // 32 characters long hash
sprintf(content: string, parameters: any[]): string

Replaces placeholders by given values.

Utils.Strings.sprintf('%0% je %1%', ['Apicart', 'nejlepší']) // Apicart je nejlepší
Utils.Strings.sprintf('%spolecnost% je %hodnoceni%', {spolecnost: 'Apicart', hodnoceni: 'nejlepší'}) // Apicart je nejlepší

Url (Utils.Url)

getQueryParameter(name: string, url: string = (<any>window).location.href): string|null

Returns query parameter from the given url. If the parameter was not found, returns null.

Utils.Url.getQueryParameter('number', 'https://example.com?number=1') // 1

Validators (Utils.Validators)

isEmpty(data: any): boolean

Returns true if the provided data are empty. Otherwise returns false.

Utils.Validators.isEmpty([]) // true
Utils.Validators.isEmpty({}) // true
Utils.Validators.isEmpty('') // true

Flash Messages (Utils.FlashMessages)

Flash messages allows you to persist messages through redirects.

addMessage(content: any, type: string | null = null): this

Adds message. You can provide a custom type.

Utils.FlashMessages.addMessage('Text');
Utils.FlashMessages.addMessage('Warning!', 'warning');
getMessages(): Object

Returns messages.

Utils.FlashMessages.getMessages();
hasMessages(type: string | null = null): boolean

Returns true if there are some persisted messages.

Utils.FlashMessages.hasMessages();
 processMessages(callback: Function, type: string | null = null): this

Iterates over messages. If the type is set, the iteration is done only over the messages of the given type.

Utils.FlashMessages.processMessages(function (message, type) { ... }); // Processes all messages
Utils.FlashMessages.processMessages(function (message, typ) { ... }, 'info'); // Processes only the info messages