Giter Club home page Giter Club logo

utils's Introduction

@teteu/utils

npm (scoped)

✨ Library to commonly used cross-projects utilities methods ✨

Run

npm install @teteu/utils --save

Usage

const utils = require('@teteu/utils');

utils.random(10, 20); // should return a random number between 10 and 20

Methods Docs

Arrays

Method What It Does Parameters Return Example
uniqueElements returns an array with unique elements (array) array with unique elements here
groupBy receives an array of objects and returns a grouped by object (array of literal object, key) object with keys being the values of array[i][key] here
randomizeArray recieves an array and returns a randomized version of it (array to randomize) randomized array here

Promises

Method What It Does Parameters Return Example
sleep pretty much sleeps until the specified time passes (time in milliseconds) Promise here

Strings

Method What It Does Parameters Return Example
replaceTokens replace tokens in a string based on a custom regular expression (string, tokens and regex) new string with tokens replaced here
isEmail validates if the input string is a valid email (string) True if the string is a valid email, false otherwise. here

Phone Numbers

Method What It Does Parameters Return Example
validBrazilianPhoneNumber Checks if a string phone number has valid brazilian phone number format (string phone number) True if the string is a valid brazilian phone number, false otherwise here

Numbers

Method What It Does Parameters Return Example
random receives a min and max number and returns a random number between them (min, max) random number between min-max here
mean receives a numeric array and returns its average (arr) the average here
max receives an array of numbers and returns the biggest number (arr of numbers) the biggest number or undefined here
maxBy receives an array and finds the maximum element in an array based on a provided callback function (array, callback) element with maximum value in array based on callback function here
divideFixed receives a number, divisor and precision and returns the result of the division with provided precision (dividend, divisor, precision) result of the division with provided precision here
meanBy receives an array and returns the mean of value given by callback function (array, callback) The mean of the values given by callback function from the array here

Date And Time

Method What It Does Parameters Return Example
getGreeting Returns a greeting based on the current hour of the day void greeting string here
getCurrentDate Returns the current date in the format "YYYY-MM-DD" void current date here
getCurrentTime Returns the current time in the format "HH:MM:SS" void current time here
getDaysBetweenDates Calculates the number of days between two given dates (date1, date2) number of days between the two dates here
formatDateToBrazilianDate Formats a given date to the Brazilian date format "DD/MM/YYYY" (date) formatted date string here

Databases

Method What It Does Parameters Return Example
sanitize This method recieves an string input and sanitizes removing all SQL injection (string to sanitize and optionally an object containing the options for sanitization, check Example for better understanding) sanitized string here

Calculations

Method What It Does Parameters Return Example
getDiscountedValue Calculate the discount amount based on the original price and discount percentage (price, discount percentage [0 - 100]) discounted value here
applyDiscount Calculates the discounted price based on the original price and discount percentage (price, discount percentage) result of price after discount here

Objects

Method What It Does Parameters Return Example
deepClone recieves an object and returns a deep clone of it (object to clone) cloned object here
pick receives an object and an array of keys and returns a new object with only the keys specified (source object and array of keys to pick from the source object) new object with only the keys specified here
omit receives an object and an array of keys and returns a new object without the keys specified (source object and array of keys to omit from the source object) new object without the keys specified here
isObject receives a value and checks if it is a javascript object literal (value to check) boolean here
deepPick receives an object with nested properties and an array of keys and returns a new object with only the keys specified. (source object and array of keys) new object with only the keys specified here

Contribute

Feel free to contribute. Check if we have open issues or request your utility method. Your code here is very welcome 🤝🤝

utils's People

Contributors

ahn0min avatar eng-assys avatar giri-madhan avatar gustavohbo avatar marcosviniciuscl avatar matheus-rodrigues00 avatar nullsploit01 avatar santyasm avatar teixeirista avatar ycarooliveira avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

utils's Issues

Create timeout Method

Implement a timeout method that creates a promise that rejects with a timeout error if it doesn't resolve within a specified time.
Example Usage:

const fetchDataPromise: Promise<any> = fetchData(); 
try {
  const result: Promise<any> = await timeout(fetchDataPromise, 1000);
  // Handle the successful result
} catch (error) {
  if (error instanceof TimeoutError) {
    // Handle the timeout error
  } else {
    // Handle other errors
  }
}

Create meanBy Method at numbers.ts

Implement a new method called meanBy. This method should calculate the mean (average) value of an array of objects or values by applying an iteratee function to each element to generate the values to be averaged. The iteratee function should be invoked with one argument: value.

Usage:

const arr = [{ 'value': 1 }, { 'value': 2 }, { 'value': 3 }];
const average = meanBy(arr, (obj) => obj.value);
console.log(average); // Should return 2

The implementation should provide flexibility by accepting an iteratee function and ensure strong type definitions for usability.

Automation to Compile TypeScript

We need to create an pipeline automation to compile the TypeScript files to JavaScript on the act of merging a branch into main.

Expected behavior:

  • A branch gets merged with main;
  • A pipeline runs tsc, this creates the javascript files;

Replace placeholders in a string based on tokens object.

It's needed to pretty much translate this code to TypeScript, also make some great tests to make sure everything is fine. 😊

/**
 * Replace placeholders in a string with corresponding token values
 * @param {string} string - The input string containing the placeholders.
 * @param {object} tokens - An object containing the tokens for replacement.
 * @param {string} placeholderFormat - The format of the placeholders. Default is "{placeholder}".
 * @returns {string} - The string with placeholders replaced.
 */
function replacePlaceholders(string, tokens = {}, placeholderFormat = "{placeholder}") {
  const cleanedString = string.replace(/\n\r|\n|\r|\t/g, ' ');

  const placeholderRegex = new RegExp(placeholderFormat.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&'), 'g');

  Object.entries(tokens).forEach(([key, item]) => {
    const regex = new RegExp(placeholderRegex.source.replace('placeholder', key), 'g');
    const value = typeof item === 'object' ? JSON.stringify(item) : item;
    cleanedString = cleanedString.replace(regex, value);
  });

  return cleanedString;
}

String Token Replace Method

Create a method that replaces the tokens of a string based on a regex expression. Follows the code in javascript. It mus be translated to TypeScript in order to be well aligned with the library code.

/**
 * Replace tokens in a string based on a custom regular expression
 * @param {string} string - The input string containing the tokens.
 * @param {object} tokens - An object containing the tokens for replacement.
 * @param {RegExp} regex - The regular expression for identifying tokens.
 * @returns {string} - The string with tokens replaced.
 */
function replaceTokens(string, tokens, regex) {
  const newString = string.replace(regex, (match, ...groups) => {
    const tokenVar = groups.pop();

    if (tokens[tokenVar] !== undefined) {
      let aux = tokens[tokenVar];

      if (Array.isArray(aux)) {
        aux = aux.length;
      } else if (typeof aux === 'object') {
        aux = Object.keys(aux).length;
      } else {
        aux = 0;
      }

      return match.replace(regex, aux);
    }

    return match;
  });

  return newString;
}

Create mean Method at numbers.ts

Develop a new method called mean. This method should calculate the mean (average) value of an array of numbers.

const numbers = [1, 2, 3, 4, 5];
const average = mean(numbers);
console.log(average); // Should return 3

The implementation should include robust type definitions for optimal usability.

Create retry Method

Implement a retry method that executes a promise-returning function repeatedly until it succeeds or reaches a maximum number of retries. Also allows specifying the interval between retry attempts.
Example Usage:

async function retry<T>(
  promise_function: () => Promise<T>,
  max_retries: number,
  retry_interval_ms: number
): Promise<T> {
  // Implementation goes here
}

Create race Method - promises.ts

Implement a race method that takes an array of promises and returns a new promise that resolves or rejects with the value or reason of the first promise in the array to settle (either resolve or reject). It effectively races the promises against each other.
Example Usage:

function race<T>(promises: Promise<T>[]): Promise<T> {
  // Implementation goes here
}

Method to Evaluate String and Throw Callback Error

The method will try to run the built-in javascript eval() in a string and if the string has some evaluation error it will throw a callback function passed also by the parameters. So it must be in a try catch. The method goes like below:

function tryEval(string_code: string, callback?: (error: Error) => void): any {
    try {
        return eval(string_code);
    } catch (e) {
        if (callback) {
            callback(e);
        } else {
            throw e;
        }
    }
}

Make sure to write some tests.

Create isObject Method At objects.ts

The isObject method should pretty much receive a value and check if it's a JavaScript object literal.
Method signature:

function isObject(value: any): boolean {
  // logic goes here
}

‼️ tests required.

Create object.ts

Create an objects.ts category on the utilities. Initially it can have a method like:

  • deepClone (should recieve an object and return a deep copy of it);

Create calculations.ts

The calculation.ts module will be responsible for housing calculation methods. Initially, we need to implement two methods: discountOnPrice and discountedPrice. These methods will take in two parameters, the price and the discount, and return the corresponding values.

  • discountOnPrice(price: number, discount: number): number: This method should calculate the discount amount based on the original price and discount percentage.

  • discountedPrice(price: number, discount: number): number: This method should calculate the discounted price based on the original price and discount percentage.

Additionally, please include test implementations for these methods to ensure their correctness and reliability.

Docs Improvement: README.md

Create tables for each utility type. Containing it's name, the description of what it does, the arguments and the return. Like:

randomizeArray | This method recieves an array and returns a randomized version of it. | randomizeArray(array: any[]) | returns {Array}

How we specify the arguments and return type can be improved, just didn't figured anything better rn.

Phone Number Utilities

Create a phoneNumber.ts category on the utilities methods, mainly focused on global phone number methods.
Start with the validBrazilianPhoneNumber
Method signature:

function validBrazilianPhoneNumber(phoneNumber: string): boolean {
  // your code.
}

reference

Docs: Create Section to Files

Create a Files section at the "Methods Docs" on the README.md. Document as well the current file methods we have, just by copying and pasting the function headers. Example:

/**
 * This method receives an array of extension types and a file and returns true if the file is of one of the media types.
 * @param {string[]} extension_types - The array of media types.
 * @param {Buffer} file - The buffered file to check.
 * @returns {Promise<boolean>} - Returns a promise that resolves to a boolean.
 */
Method What It Does Parameters Return Example
checkMediaTypes receives an array of extension types and a file and returns true if the file is of one of the media types (extension types and file buffered) promise that resolves to a boolean here

Create mapObject Method At objects.ts

The ** mapObject** method should create a new object and apply the parameter's function to every value.
Method signature:

function mapObject(source: object, fn: (value: any) => any): object {
  // logic goes here
}

‼️ tests required.

Create omit Method At objects.ts

The omit method should create a new object with the specified properties removed.
Method signature:

function omit(source: object, keys: string[]): object {
  // Implement the omit logic here
}

‼️ tests required.

Create file.ts Module

It's interesting to have file related utilities grouped, therefore create a file.ts module.

Create cancel Method - promises.ts

Implement a cancel method that allows the cancellation of a promise that supports cancellation, such as an HTTP request.
Example Usage:

function cancel<T>(promise: Promise<T>): void {
  // Implementation goes here
}

Date and Time Utilities Category

Create a DateAndTime category, the starting methods can be:
getTimezoneOffset: This method retrieves the user's current timezone offset from UTC.
getGreeting: This method takes the timezone offset as input and returns a suitable greeting based on the current time.

Move randomizeArray Method

The randomizeArray method is at the numbers.ts module. Since it's more related to arrays than numbers, it should be moved to the arrays.ts module.

Extra improvement that can be made is the refactor to use the random method at the sort callback function.

Create throttle Method

Implement a throttle method that limits the concurrency of executing promise-returning functions to a specified number.
Method Signature:

async function throttle<T>(
  promises: (() => Promise<T>)[],
  maxConcurrency: number
): Promise<T[]> {
  // Implementation goes here
}

Create sequential Method

Implement a method that executes an array of promise-returning functions sequentially, waiting for each to complete before starting the next.
Method signature:

async function sequence<T>(
  promiseFunctions: (() => Promise<T>)[]
): Promise<T[]> {
  // Implementation goes here
}

Create max Method

Create a new method called max. This method should compute the maximum value of an array. If the array is empty or falsy, it should return undefined.

function max(arr: number[] | undefined): number | undefined {
    // Implementation goes here
}

Create divideFixed Method

Create a new method called divideFixed. This method should perform a division and format the return the result with precision decimal numbers formated. Ensure that it handles edge cases and returns the result with the specified precision.

function divideFixed(dividend: number, divisor: number, precision: number): string {
    // Implementation goes here, and at the end, convert the result to a string using .toFixed(precision)
}

Create getFile Method

We need to implement a TypeScript function based on the following JavaScript function:

/**
 * Return a file and his type from local Media folder or from an URL, the folder takes priority, if the file is not found it throws a exception
 * @param filename name of the file
 * @param url url of the file
 */
async function getFile(url, extension = null) {
    var type;
    var file;

    const result = await fetch(url);

    file = await result.buffer();

    type = await fileType.fromBuffer(file);

    if (!type && extension == '.txt') type = { mime: 'text/plain', ext: 'txt' };

    console.log(type);

    if (!type && extension == '.txt') type = { mime: 'text/txt', ext: 'txt' };

    if (!type) {
        throw new Error('File not Found');
    }

    return { file, type };
}

This function is somewhat strict and lack types. We can implement it making as generic as possible, but still preserving its functionalities, like the .txt treatment for retro-compatibility purposes.

Create pick Method At objects.ts

The pick method should create a new object based on selected properties.
Method signature:

function pick(source: object, keys: string[]): object {
  // Implement the pick logic here
}

‼️ tests required.

Create colors.ts Category

It would be really great to have a colors category. A category responsible for colors method utilities like one that gets the best contrast of a color, returning either black or white hexadecimals. The method can be like:

function getBlackOrWhiteContrastColor(hex: string): string {
    // Normalize the hex code to a 6-digit format if it's a 3-digit format
    hex = hex.replace(/^#?([a-f\d])([a-f\d])([a-f\d])$/i, (_, r, g, b) => r + r + g + g + b + b);

    // Convert hex to RGB
    let [r, g, b] = hex.match(/\w\w/g)!.map(val => parseInt(val, 16));

    // Calculate the relative luminance (perceived brightness) of the color
    let luminance = (0.299 * r + 0.587 * g + 0.114 * b) / 255;

    // Return black or white based on luminance
    return luminance > 0.5 ? '#000' : '#fff';
}

Also, as an improvement, you can make the method more versatile. Accepting even RGB or RGBA colors 🙂

Create deepPick Method

The pick method implemented by @GustavoHBO works great! It would be even better if we can tell which nested properties we actually want from nested objects.

Method signature:

function deepPick<T extends object, K extends keyof T>(
  source: T,
  keys: K[]
): Pick<T, K> {
   // Gustavo code here 🕺
}

formatMoneyToBrazilianReal

Create a method that formats an input number or string to Brazilian real format: "R$ 1.562,47"

input (number | string)
output (formatted_value)

*Also make sure to check if number is empty string / invalid character.

Example:
->: 1562,47
<-: "R$ 1.562,47"

Create maxBy Method

This method is similar to the max(), which accepts an array and return the maximum element. Difference is, this method should find the maximum element in an array based on a provided callback function that specifies the criteria for comparison. Example:

const arr = [{ 'val': 1 }, { 'val': 4 }, { 'val': 3 }, { 'val': 2 }];

console.log(maxBy(arr, (obj) => obj.n)); // Should return {'val': 4}, since it's the biggest by the criteria.

The implementation can be sophisticated, with good type definitions.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.