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

guden-core

v1.0.11

Published

util and helpers

Downloads

3

Readme

guden-core

guden-core is a utility library for TypeScript, providing a range of helper functions for common tasks such as string manipulation, date formatting, and data mapping.

Overview

guden-core aims to simplify common programming tasks by providing a set of utility functions that can be easily integrated into your TypeScript projects. Whether you're dealing with strings, dates, or complex object mappings, guden-core has you covered.

Installation

To install guden-core, you can use npm:

npm install guden-core
yarn add guden-core

setLocalStorage Methods.

This function is used to save a JavaScript object to localStorage with a specified key name. It utilizes the browser's localStorage API to persist data across browser sessions.

Parameters

  • object (any): The JavaScript object to be stored. This object will be converted to a JSON string before being stored.
  • keyName (string): The key name under which the object will be stored in localStorage. This key will be used to retrieve the object later.

Usage

const user = {
    name: "John Doe",
    age: 30
};

setLocalStorage(user, "userInfo");

getLocalStoreByName

This function retrieves a JavaScript object from localStorage using a specified key name. It returns the object as the specified generic type T, or undefined if no object is found for the given key.

Parameters

  • keyName (string): The key name under which the object is stored in localStorage. This key is used to retrieve the object.

Return Value

  • Returns the object stored in localStorage parsed as the specified type T, or undefined if no object is found for the given key.

Usage

interface User {
    name: string;
    age: number;
}

const user = getLocalStoreByName<User>("userInfo");

if (user) {
    console.log(user.name); // Output: John Doe
} else {
    console.log("No user info found.");
}

removeLocalStorage

Removes an item from localStorage using a specified key name. This function is used to delete a previously stored object or value.

Parameters

  • keyName (string): The key name of the item to be removed from localStorage.

Usage

removeLocalStorage("userInfo");

Array Utilities

isNullOrEmptyArray

Checks whether the provided value is either null, undefined, or an empty array. This function helps in validating arrays to ensure they contain elements before processing.

Parameters

  • value (any): The value to be checked. This can be any type, including null, undefined, or an array.

Return Value

  • Returns true if the value is null, undefined, or an empty array; otherwise, returns false.

Usage

const result1 = isNullOrEmptyArray(null); // true
const result2 = isNullOrEmptyArray([]); // true
const result3 = isNullOrEmptyArray([1, 2, 3]); // false

console.log(result1); // Output: true
console.log(result2); // Output: true
console.log(result3); // Output: false

divideArray

Divides an array into smaller arrays of a specified size and returns them grouped in an array of dictionaries. This function is useful for chunking large arrays into smaller, more manageable parts.

Parameters

  • array (T[]): The array to be divided. This can be an array of any type.
  • size (number): The size of each chunk. Determines the maximum number of elements in each smaller array.

Return Value

  • Returns an array of dictionaries where each dictionary contains a chunk of the original array. The keys in the dictionaries are sequential numbers starting from 1.

Usage

const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const chunked = divideArray(numbers, 3);

console.log(chunked);
[
  { "1": [1, 2, 3] },
  { "2": [4, 5, 6] },
  { "3": [7, 8, 9] }
]

sortArray

Sorts an array of objects based on a specified key. The sorting can be done in ascending or descending order, and it supports different data types including dates, numbers, and strings.

Parameters

  • array (any[]): The array of objects to be sorted.
  • key (string): The key of the objects based on which the sorting is performed.
  • isDesc (boolean, optional): A boolean indicating the sort order. If true, the array will be sorted in descending order. If false or not provided, it will be sorted in ascending order.

Return Value

  • Returns the sorted array.

Usage

const data = [
  { name: "Alice", age: 25, date: new Date("2024-01-01") },
  { name: "Bob", age: 30, date: new Date("2023-01-01") },
  { name: "Charlie", age: 20, date: new Date("2025-01-01") }
];

// Sort by age in ascending order
const sortedByAge = sortArray(data, "age");

// Sort by date in descending order
const sortedByDate = sortArray(data, "date", true);

console.log(sortedByAge);
// Output: [{ name: "Charlie", age: 20, date: ... }, { name: "Alice", age: 25, date: ... }, { name: "Bob", age: 30, date: ... }]

console.log(sortedByDate);
// Output: [{ name: "Charlie", age: 20, date: ... }, { name: "Alice", age: 25, date: ... }, { name: "Bob", age: 30, date: ... }]

removeDuplicates

Removes duplicate values from an array and returns a new array with unique values. This function is useful for ensuring that an array contains only distinct elements.

Parameters

  • arr (T[]): The array from which duplicate values will be removed.

Return Value

  • Returns a new array with all duplicate values removed. The order of the elements is preserved.

Usage

const numbers = [1, 2, 2, 3, 4, 4, 5];
const uniqueNumbers = removeDuplicates(numbers);

console.log(uniqueNumbers);
// Output: [1, 2, 3, 4, 5]

const fruits = ["apple", "banana", "apple", "orange", "banana"];
const uniqueFruits = removeDuplicates(fruits);

console.log(uniqueFruits);
// Output: ["apple", "banana", "orange"]

findAddedAndDeletedItems

Compares two arrays and identifies items that have been added or removed. This function is useful for determining changes between two versions of an array.

Parameters

  • oldArray (T[]): The original array to compare.
  • newArray (T[]): The new array to compare against the original.

Return Value

  • Returns an object with two properties:
    • addedItems (T[]): An array of items that are present in the newArray but not in the oldArray.
    • deletedItems (T[]): An array of items that are present in the oldArray but not in the newArray.

Usage

const oldArray = [1, 2, 3, 4];
const newArray = [3, 4, 5, 6];

const changes = findAddedAndDeletedItems(oldArray, newArray);

console.log(changes.addedItems);
// Output: [5, 6]

console.log(changes.deletedItems);
// Output: [1, 2]

Date Utilities

ConvertDateToString

Converts a Date object, null, or undefined to a formatted date string based on the specified format. This function handles different date formats and returns a string representation of the date.

Parameters

  • date (Date | null | undefined): The date to be converted. If null or undefined, an empty string is returned.
  • format (DateFormat): The format to use for the date string. This should be one of the predefined date formats in the DateFormat enum.

Return Value

  • Returns a string representing the date in the specified format.

DateFormat Enum

  • DateFormat.DDMMYYYYP: Formats the date as DD.MM.YYYY.
  • DateFormat.DDMMYYYYS: Formats the date as DD/MM/YYYY.
  • DateFormat.MMDDYYYYS: Formats the date as MM/DD/YYYY.
  • DateFormat.MMDDYYYYP: Formats the date as MM.DD.YYYY.

Usage

enum DateFormat {
    DDMMYYYYP,
    DDMMYYYYS,
    MMDDYYYYS,
    MMDDYYYYP
}

const date = new Date(2024, 6, 19); // 19th July 2024

const formattedDate1 = ConvertDateToString(date, DateFormat.DDMMYYYYP);
console.log(formattedDate1); // Output: "19.07.2024"

const formattedDate2 = ConvertDateToString(date, DateFormat.MMDDYYYYS);
console.log(formattedDate2); // Output: "07/19/2024"

Date Utilities

ConvertDateToTimeString

Converts a Date object, null, or undefined to a formatted time string in HH:MM format. This function handles null and undefined values gracefully and returns an empty string in such cases.

Parameters

  • date (Date | null | undefined): The date from which the time will be extracted. If null or undefined, an empty string is returned.

Return Value

  • Returns a string representing the time in HH:MM format.

Usage

const date = new Date(2024, 6, 19, 15, 5); // 19th July 2024, 15:05

const timeString = ConvertDateToTimeString(date);
console.log(timeString); // Output: "15:05"

Dictionary Utilities

updateDictionary

Updates a dictionary with a specified key-value pair. If the key already exists in the dictionary, its value is updated; otherwise, a new key-value pair is added.

Parameters

  • dictionary (Dictionary): The dictionary to be updated.
  • key (string): The key for the entry to be updated or added.
  • value (T): The value to be associated with the key.

Return Value

  • Returns the updated dictionary.

Usage

const myDict: Dictionary<number> = { "a": 1, "b": 2 };

updateDictionary(myDict, "b", 3);
console.log(myDict); // Output: { "a": 1, "b": 3 }

updateDictionary(myDict, "c", 4);
console.log(myDict); // Output: { "a": 1, "b": 3, "c": 4 }

Guden Mapper Utilities

SourceDestination

Represents a mapping configuration between source and destination properties. This interface is used in conjunction with the gudenMapper function to define how properties from a source object should be mapped to a destination object.

Properties

  • source (string): The property name in the source object.
  • destination (string): The property name in the destination object.

Usage

interface SourceDestination {
    source: string;
    destination: string;
}

// Example mapping configuration
const mapping: SourceDestination = {
    source: "id",
    destination: "userId"
};

Guden Mapper Utilities

gudenMapper

Maps properties from a source object to a destination object based on a provided configuration. This function is useful for transforming data from one structure to another according to a predefined mapping.

Parameters

  • source (any): The source object from which properties are to be mapped.
  • config (GudenMapperConfig): The configuration object that defines the mapping between source and destination properties.

Return Value

  • Returns the destination object of type T, populated with values from the source object based on the mapping configuration.

  • mapList: An array of mapping rules where each rule specifies which property from the source object should be mapped to which property in the destination object.

Usage

interface SourceObject {
    id: number;
    name: string;
    email: string;
}

interface DestinationObject {
    userId: number;
    fullName: string;
    contactEmail: string;
}

const source = {
    id: 1,
    name: "John Doe",
    email: "[email protected]"
};

const config: GudenMapperConfig = {
    mapList: [
        { source: "id", destination: "userId" },
        { source: "name", destination: "fullName" },
        { source: "email", destination: "contactEmail" }
    ]
};

const result = gudenMapper<DestinationObject>(source, config);
console.log(result);
// Output: { userId: 1, fullName: "John Doe", contactEmail: "[email protected]" }

gudenAutoMapper

Maps properties from a source object to a destination object with the same property names. This function is useful for automatically copying properties from one object to another without requiring explicit mapping configuration.

Parameters

  • source (any): The source object from which properties will be copied.

Return Value

  • Returns a new object of type T, populated with values from the source object. Property names must match between the source and destination objects.

Usage

interface SourceObject {
    id: number;
    name: string;
    email: string;
}

interface DestinationObject {
    id: number;
    name: string;
    email: string;
}

const source: SourceObject = {
    id: 1,
    name: "John Doe",
    email: "[email protected]"
};

const result = gudenAutoMapper<DestinationObject>(source);
console.log(result);
// Output: { id: 1, name: "John Doe", email: "[email protected]" }

gudenAutoMapperList

Maps a list of source objects to a list of destination objects using automatic property mapping. This function applies the gudenAutoMapper function to each item in the source array, assuming that property names match between the source and destination objects.

Parameters

  • source (any[]): An array of source objects that need to be mapped to destination objects.

Return Value

  • Returns a new array of objects of type T, where each object is mapped from the source array using the gudenAutoMapper function.

Usage

interface SourceObject {
    id: number;
    name: string;
}

interface DestinationObject {
    id: number;
    name: string;
}

const sourceList: SourceObject[] = [
    { id: 1, name: "John Doe" },
    { id: 2, name: "Jane Smith" }
];

const resultList = gudenAutoMapperList<DestinationObject>(sourceList);
console.log(resultList);
// Output: [ { id: 1, name: "John Doe" }, { id: 2, name: "Jane Smith" } ]

gudenMapperList

Maps a list of source objects to a list of destination objects based on a specified mapping configuration. This function uses the gudenMapper function to apply the mapping rules defined in the config to each item in the source array.

Parameters

  • source (any[]): An array of source objects that need to be mapped to destination objects.
  • config (GudenMapperConfig): The configuration object that defines the mapping between source and destination properties for each item in the array.

Return Value

  • Returns a new array of objects of type T, where each object is mapped from the source array according to the provided config.

GudenMapperConfig

  • mapList: An array of SourceDestination mappings where each mapping specifies the source property name and the destination property name.

Usage

interface SourceObject {
    id: number;
    name: string;
    email: string;
}

interface DestinationObject {
    userId: number;
    fullName: string;
    contactEmail: string;
}

const sourceList: SourceObject[] = [
    { id: 1, name: "John Doe", email: "[email protected]" },
    { id: 2, name: "Jane Smith", email: "[email protected]" }
];

const config: GudenMapperConfig = {
    mapList: [
        { source: "id", destination: "userId" },
        { source: "name", destination: "fullName" },
        { source: "email", destination: "contactEmail" }
    ]
};

const resultList = gudenMapperList<DestinationObject>(sourceList, config);
console.log(resultList);
// Output: [
//   { userId: 1, fullName: "John Doe", contactEmail: "[email protected]" },
//   { userId: 2, fullName: "Jane Smith", contactEmail: "[email protected]" }
// ]

Object Utilities

This section includes utility functions for manipulating and working with objects in TypeScript. These functions simplify common tasks such as property checks, value retrieval, and object transformations.

isNull

Checks if a given value is null. This function is useful for determining if a value has been explicitly set to null or if it is not yet initialized.

Parameters

  • value (any): The value to be checked.

Return Value

  • Returns true if the value is null, otherwise returns false.

Usage

const result1 = isNull(null);
console.log(result1); // Output: true

const result2 = isNull(undefined);
console.log(result2); // Output: false

const result3 = isNull(0);
console.log(result3); // Output: false

isUndefined

Checks if a given value is undefined. This function is useful for determining if a value has not been initialized or explicitly set.

Parameters

  • value (any): The value to be checked.

Return Value

  • Returns true if the value is undefined, otherwise returns false.

Usage

const result1 = isUndefined(undefined);
console.log(result1); // Output: true

const result2 = isUndefined(null);
console.log(result2); // Output: false

const result3 = isUndefined(0);
console.log(result3); // Output: false

isNullOrUndefined

Checks if a given value is either null or undefined. This function is useful for verifying whether a value is uninitialized or explicitly set to null.

Parameters

  • value (any): The value to be checked.

Return Value

  • Returns true if the value is null or undefined, otherwise returns false.

Usage

const result1 = isNullOrUndefined(null);
console.log(result1); // Output: true

const result2 = isNullOrUndefined(undefined);
console.log(result2); // Output: true

const result3 = isNullOrUndefined(0);
console.log(result3); // Output: false

const result4 = isNullOrUndefined('');
console.log(result4); // Output: false

IModel

Represents a model where the properties are defined dynamically with string keys and any type of values. This interface is useful for scenarios where the structure of the model is not fixed or varies.

Properties

  • [key: string]: any: Defines a model with dynamic keys where the key is a string and the value can be of any type.

Usage

const model: IModel = {
    id: 1,
    name: "John Doe",
    email: "[email protected]",
    isActive: true
};

console.log(model.id); // Output: 1
console.log(model.name); // Output: John Doe
console.log(model.email); // Output: [email protected]
console.log(model.isActive); // Output: true

convertToJSON

Converts an IModel object into a JSON string. This function supports nested properties and array indexing, allowing complex structures to be serialized into JSON format.

Parameters

  • model (IModel): The model object to be converted into a JSON string. This object can contain nested properties and arrays.

Return Value

  • Returns a JSON string representing the structure and values of the input model.

Details

The function performs the following steps:

  1. Initialize an Empty Object: Creates an empty json object to hold the transformed structure.
  2. Define Helper Function: Defines setNestedValue, a helper function that sets a value in the nested json object based on a dot-separated key string.
    • Key Parsing: The key is split into parts using . as the delimiter.
    • Array Handling: Handles array indices specified in the keys, e.g., array[0].
    • Nested Object Creation: Creates nested objects or arrays if they do not exist.
  3. Process Model Properties: Iterates over each property in the input model and uses setNestedValue to assign the property values to the json object.
  4. Serialize to JSON: Converts the json object to a JSON string using JSON.stringify.

Usage

interface IModel {
    "user.name": string;
    "user.address[0].city": string;
    "user.address[1].city": string;
}

const model: IModel = {
    "user.name": "John Doe",
    "user.address[0].city": "New York",
    "user.address[1].city": "Los Angeles"
};

const jsonString = convertToJSON(model);
console.log(jsonString);
// Output: '{"user":{"name":"John Doe","address":[{"city":"New York"},{"city":"Los Angeles"}]}}'

createModel

Converts a JSON string into an IModel object. This function reconstructs the model object from a JSON string, handling nested properties and arrays based on the structure of the JSON data.

Parameters

  • jsonData (string): The JSON string representing the model object. It should be a properly formatted JSON string with nested properties and arrays.

Return Value

  • Returns an IModel object that represents the data structure defined in the jsonData.

Details

The function performs the following steps:

  1. Parse JSON: Parses the input JSON string into a JavaScript object (parsedData).
  2. Define Helper Function: Defines setNestedValue, a helper function that sets a value in a nested object based on a dot-separated key string.
    • Key Parsing: The key is split into parts using . as the delimiter.
    • Array Handling: Handles array indices specified in the keys, e.g., array[0].
    • Nested Object Creation: Creates nested objects or arrays if they do not exist.
  3. Process Parsed Data: Iterates over each property in the parsed JSON object and uses setNestedValue to assign the property values to the model object.
  4. Return Model: Returns the reconstructed IModel object.

Usage

interface IModel {
    user: {
        name: string;
        address: {
            [index: number]: {
                city: string;
            };
        };
    };
}

const jsonData = '{"user":{"name":"John Doe","address":[{"city":"New York"},{"city":"Los Angeles"}]}}';

const model = createModel(jsonData);
console.log(model);
// Output: { user: { name: 'John Doe', address: [ { city: 'New York' }, { city: 'Los Angeles' } ] } }

String Utilities

This section includes utility functions for manipulating and working with strings in TypeScript. These functions simplify common tasks such as trimming, case conversion, and string formatting.

## isNullOrEmptyString

Checks if a given value is either `null`, `undefined`, or an empty string. This function is useful for determining if a value is not provided or is an empty string.

### Parameters

- `value` (any): The value to be checked.

### Return Value

- Returns `true` if the value is `null`, `undefined`, or an empty string (`""`), otherwise returns `false`.

### Usage

```typescript
const result1 = isNullOrEmptyString(null);
console.log(result1); // Output: true

const result2 = isNullOrEmptyString(undefined);
console.log(result2); // Output: true

const result3 = isNullOrEmptyString("");
console.log(result3); // Output: true

const result4 = isNullOrEmptyString("hello");
console.log(result4); // Output: false

const result5 = isNullOrEmptyString(0);
console.log(result5); // Output: false

isIncludeValue

Checks if a given searchString is included within a source string. The function supports case sensitivity based on the provided flag.

Parameters

  • searchString (string): The substring to search for within the source string.
  • source (string): The string in which to search for the searchString.
  • isCaseSensitive (boolean, optional): Determines if the search should be case-sensitive. Defaults to false.

Return Value

  • Returns true if the searchString is found within the source string; otherwise, returns false.

Usage

const result1 = isIncludeValue("test", "This is a test string");
console.log(result1); // Output: true

const result2 = isIncludeValue("TEST", "This is a test string", true);
console.log(result2); // Output: false

const result3 = isIncludeValue("TEST", "This is a test string");
console.log(result3); // Output: true

generateGUID

Generates a globally unique identifier (GUID) in the format xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx. This function is useful for creating unique identifiers for objects, sessions, or other entities.

Return Value

  • Returns a string representing a GUID in the format xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx.

Details

The function works by:

  1. Pattern Replacement: Replaces the x and y placeholders in the GUID pattern with random hexadecimal digits.
  2. Random Hexadecimal Generation: Uses Math.random() to generate random values and applies bitwise operations to ensure the correct format:
    • x is replaced by a random hexadecimal digit (0-15).
    • y is replaced by a random hexadecimal digit from the set {8, 9, A, B} to comply with the GUID specification.

Usage

const guid = generateGUID();
console.log(guid); // Output: Example: "f47ac10b-58cc-4372-a567-0e02b2c3d479"

stringFormat

Formats a string by replacing placeholders with specified values, similar to the String.Format method in C#. This function supports indexed placeholders and allows for dynamic string formatting.

Parameters

  • format (string): The format string containing placeholders in the form {0}, {1}, etc.
  • ...args (any[]): Values to replace the placeholders in the format string. The values are indexed and replaced based on their position in the args array.

Return Value

  • Returns a formatted string with placeholders replaced by the corresponding values from the args array.

Details

The function works by:

  1. Pattern Matching: Uses a regular expression (/{(\d+)}/g) to find placeholders in the format string. Placeholders are identified by {0}, {1}, etc.
  2. Replacement: Replaces each placeholder with the corresponding value from the args array. If an argument for a placeholder is not provided, the placeholder remains unchanged.

Usage

const formattedString = stringFormat("Hello, {0}! You have {1} new messages.", "Alice", 5);
console.log(formattedString); // Output: "Hello, Alice! You have 5 new messages."

const missingArgString = stringFormat("The value is {0} and the default is {1}.", "42");
console.log(missingArgString); // Output: "The value is 42 and the default is {1}."

UĞURCAN GÜDEN