Coder Social home page Coder Social logo

fullstacksjs / toolbox Goto Github PK

View Code? Open in Web Editor NEW
50.0 3.0 14.0 4.63 MB

A zero-dependency 📦 tree-shakable🌲 collection of missing JavaScript utilities.

Home Page: https://toolbox.fullstacksjs.com/

License: MIT License

JavaScript 1.21% Shell 1.08% TypeScript 97.71%
javascript typescript utility fullstacksjs

toolbox's Issues

toCamelCase not working for UPPER_CASE_SNAKE

Describe the bug

toCamelCase to working for "UPPER_CASE_SNAKE".

Expected behavior

toCamelCase("UPPER_CASE_SNAKE"); // "upperCaseSnake"

Actual behavior

toCamelCase("UPPER_CASE_SNAKE"); // "UPPER_CASE_SNAKE"

Documentation

The readme is becoming bloated as the number of utility functions grows. It's time to use a program to produce a proper documentation page to make functions easier to identify and document.

Any tool with the following properties is acceptable for use:

  • Code generation: the ability to regenerate documentation upon each update
  • Filters: the ability to search and filter via utilities
  • Groups: the ability to group the specific functions together
  • Customizable tools are preferred

pruneNullOrEmpty

Function signature

pruneNullOrEmpty(obj: T): T;

What utility function do you need?

removing null or empty values from an object.

What motivates us?

it's common to have an object which contains values with an empty string or null, in most cases to have a valid and clear object we need to ensure the null or empty string is removed from an object.

List of examples

pruneNullOrEmpty({ firstName: null, lastName: "PRD"  }) // { lastName: "PRD" }
pruneNullOrEmpty({ firstName: '', lastName: "PRD"  })  // { lastName: "PRD" }
pruneNullOrEmpty({ firstName: '', lastName: "PRD", age: null  }) // { lastName: "PRD"}

isNull Guard on Nested Nullable Chain

Describe the bug

The isNull guard is not working for the nested nullable chain.

Expected behavior

The following code should compile with the --strict flag.

function f(x: {
  foo: { bar: (string | undefined)[] | undefined } | undefined;
}) {
  if (isNull(x.foo?.bar?.[0])) return;
  x.foo.bar[0].toLowerCase();
}

Actual behavior

It throws the "Object is possibly 'undefined" error.

Code Coverage Badge

a coverage badge and threshold enable us to identify any code paths within the library that are not covered by tests and let library users make sure the library code is well-tested.

To achieve this, the implementation will involve integrating vitest coverage into the CI workflow and extracting the coverage data to be displayed as a badge in the readme file.

[Proposal]: throttle

Scope

function

Function Signature

function throttle<T extends Function>(options: { interval: number; isImmediate?: boolean }, f: T): T

Motivation

In numerous applications, there are functions that are executed frequently, such as during window resizing, text input, or mouse movements. These repeated function calls might cause performance bottlenecks, particularly when they lead to hefty computations or disruptive visual updates.

The throttle function serves to control the execution rate of a function.

[Proposal]: toggleArrayValue

Scope

array

Function Signature

function toggleArrayValue<T extends unknown>(array: T[], value: T): T[]

Motivation

This function, called toggleArrayValue, is useful for toggling the presence of a specific value within an array. It allows you to easily add the value to the array if it is not already present, or remove it if it is already present.

This can be particularly motivating in scenarios where you need to manage a list of selected items or toggling options on and off. By using this function, you can easily update the array without having to write conditional checks or multiple statements.

[Proposal]: format minutes into a nice time format

Function Signature

const minuteFormat = (value) => {
	const minutes = Math.trunc(value / 60);
	const seconds = value % 60;

	return `${minutes < 10 ? `0${minutes}` : minutes}:${seconds < 10 ? `0${seconds}` : seconds}`;
};

Motivation

by using this helper function , we can easily format a minute number like 120 into " 02:00" time format. also it can be more customized and make it more reusable for any format we want by passing extra parameters

The automated release is failing 🚨

🚨 The automated release from the main branch failed. 🚨

I recommend you give this issue a high priority, so other packages depending on you can benefit from your bug fixes and new features again.

You can find below the list of errors reported by semantic-release. Each one of them has to be resolved in order to automatically publish your package. I’m sure you can fix this 💪.

Errors are usually caused by a misconfiguration or an authentication problem. With each error reported below you will find explanation and guidance to help you to resolve it.

Once all the errors are resolved, semantic-release will release your package the next time you push a commit to the main branch. You can also manually restart the failed CI job that runs semantic-release.

If you are not sure how to resolve this, here are some links that can help you:

If those don’t help, or if this issue is reporting something you think isn’t right, you can always ask the humans behind semantic-release.


Invalid npm token.

The npm token configured in the NPM_TOKEN environment variable must be a valid token allowing to publish to the registry https://registry.npmjs.org/.

If you are using Two Factor Authentication for your account, set its level to "Authorization only" in your account settings. semantic-release cannot publish with the default "
Authorization and writes" level.

Please make sure to set the NPM_TOKEN environment variable in your CI with the exact value of the npm token.


Good luck with your project ✨

Your semantic-release bot 📦🚀

working with params and queries in the url

Function Signature

const getUrlParams = () => {
	const pl = /\+/g;
	const search = /([^&=]+)=?([^&]*)/g;
	const decode = (s) => {
		return decodeURIComponent(s.replace(pl, " "));
	};
	const query = window.location.search.substring(1);
	const urlParams = {};
	let match;

	while ((match = search.exec(query))) urlParams[decode(match[1])] = decode(match[2]);

	Object.keys(urlParams).map((keyName) => {
		if (!isNaN(urlParams[keyName])) urlParams[keyName] = parseFloat(urlParams[keyName]);
	});

	return urlParams;
};

Motivation

we typically use useSearchParams in nextjs ( or other related hooks in react ), in order to get a query from the url, it's ok , but you need to be specific which query you are looking for and pass it as string to searchParams.get("name").

by using this function (getUrlParams) , we can get all queries in the url at a time. and destructor the one we need.

as an example :
imagine we have this url

sample.com/page?test=idk&orderBy=DATE

and need to get orderBy query, we simply do this :

const {orderBy} = getUrlParams();  // it return all queries {test:"idk",orderBy:"DATE"}
console.log(orderBy); // DATE

[Proposal]: Format price in a easy way

Function Signature

Function Signature

const priceFormat = (value) => {
	return `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
};

Motivation

simply pass a number and get a nu,mber ¯_(ツ)_/¯

Test and coverage CI

It would be ideal to have a continuous integration environment where we could run our unit tests and report on test coverage. A badge in a README file is also a plus.

Tools we are using:

  • Github Actions
  • vitest

compact

Function signature

compactArray<T extends unknown[]>(xs: T): CompactArray<T>

What utility function do you need?

the compact is a function that removes all nullish values from an array

What motivates us?

the compact function is very useful in arrays in config or optional tasks.

List of examples

compact([1, false, null, 2, undefined]) // [1, false, 2]
compact([NaN, false, null, 0, undefined]) // [NaN, false, 0]

AsyncVoidFn

It would be useful to have an AsyncVoidFunction type.

Motivation

There is a VoidFunction type in the toolbox, but the function may be async at times. Because it does not raise the bundle size, we may include this utility function to have cleaner code.

Definition

type AsyncVoidFn = () => Promise<void>

shuffle

Function signature

type shuffle = <T>(arr:T[]) => T[]

What utility function do you need?

a function which takes an array and returns the shuffled version of it

What motivates us?

when we want to shuffle an array

List of examples

shuffle([]) // []
shuffle([1]) // [1]
shuffle([1, 2, 3]) // any combination of these three numbers e.g: [3, 1, 2]
shuffle('array') // Error: not an array

[Bug]: External `tryOr` link in the docs

Describe the issue

In the docs, there's an external link among the Function drop down menu links, navigating to the tryOr utility section.

The main link: https://toolbox.fullstacksjs.com/function/tryOr

The external link: https://toolbox.fullstacksjs.com/function/tryOr#

Click to preview

Expected Behavior

There should be only one link on the Function drop down menu navigating to the tryOr utility page.

Actual Behavior

There are two links (the main one and an external one) on the Function drop down menu navigating to the tryOr utility page.

[Proposal]: Camel case maker in order to format Json/data object keys that we get from backend

Function Signature

const toCamel = value => {
	return value.replace(/([-_][a-z])/gi, $1 => {
		return $1.toUpperCase().replace("-", "").replace("_", "");
	});
};

const keysToCamel = (obj) => {
	if (isObject(obj)) {
		const n = {};

		Object.keys(obj).forEach((k) => {
			n[toCamel(k)] = keysToCamel(obj[k]);
		});

		return n;
	} else if (isArray(obj)) {
		return obj.map((i) => {
			return keysToCamel(i);
		});
	}

	return obj;
};

Motivation

As we know ,backend developers usually naming keys in 'snake_case"format, and in JavaScript we use CamelCase, with this helper function we can pass a string like hello_world and get "helloWorld" in return, also it we can use "keysToCamel" in order to format entire object keys at a time

[Proposal]: toDecimal fallback

Function Signature

export function toDecimal(s: Nullable<string>, fallback: number = NaN): number {}

Motivation

To parse environment variables, we must use the following pattern.

port: toDecimal(process.env.PORT ?? "3000", 3000),

If the toDecimal function supports nullable values as input, we can write the code simply like this.

port: toDecimal(process.env.PORT, 3000),

[Proposal]: merge

Function Signature

function merge(obj1: T, obj2: U, composer?: (value1, value2, key, obj1, obj2): DeepMerge<T, U>

Motivation

It is quite useful for configuration management.

tryCatch + nullableTryCatch

Function signature

type TryCatch = <T, E>(f: () => T, onErr: (e?: unknown) => E) => E | T
type AsyncTryCatch = <T, E>(f: () => Promise<T>, onErr: (e?: unknown) => E) => Promise<E | T>
type NTryCatch = <T>(f: () => T) => Nullable<T>
type AsyncNTryCatch = <T>(f: () => Promise<T>) => Nullable<T>

What utility function do you need?

the functions purpose is to abstract the nasty try-catch syntax into a function

List of examples

 const f = () => {
  if (Math.random() > 0.5) return true;
  throw Error('something bad happened');
};

const trueOrErr = TryCatch(f,  () => 'bad luck')  // true | 'bad luck'
const dataOrErr = await AsyncTryCatch( () => fetch('hello'),  () => 'failed to fetch')  // data | 'failed to fetch'
const trueOrNull = await N.asyncTryCatch(f)  // true | null
const dataOrNull = await N.asyncTryCatch(() => fetch('hello'))  // data | null

Note:

in the last two line the N refers to the object which holds the nullable module
so we also need to have such syntax for nullables:

import * as N from 'toolbox/nullable';

N.Nullable // refers to the typescript nullable type not a value
N.asyncTryCatch, N.tryCatch // refers to the nullable functions which was mentioned above

[Proposal]: uniq

Scope

array

Function Signature

function uniq<T extends any[]>(array: T): T

Motivation

The motivation behind the uniq function is to simplify the process of obtaining a new array with all duplicate values removed. It aims to provide an efficient and convenient way to remove duplicates from an array, without modifying the original array.

[Proposal]: debounce

Scope

function

Function Signature

function debounce<T extends Function>(options: { delay: number; isImmediate?: boolean }, f: T): T

Motivation

The motivation behind proposing this feature is based on the potential performance benefits it offers. It's common in many applications to have functions that are executed often, like when resizing a window, typing into a field, or moving the mouse. These repeated function calls can sometimes lead to performance issues, especially when they lead to a significant amount of computation or a disruptive visual update.

The debounce function helps limit the rate at which a function can fire.

[Proposal]: bindArgs (only-args, exclude `thisArg`)

Function Signature

declare global {
  export interface Function {
    bindArgs<T, A extends unknown[]>(this: T, ...args: A): OmitThisParameter<T>;
  }
}

Motivation

With the bind method, we must pass thisArg as the first argument to the function we want to bind (the target). What if we didn't want to go through it? Yes, there is a solution below

const bound = fn.bind(null, ...otherArgsToBind);
// Or
const bound = fn.bind({}, ...otherArgsToBind);

But, what if we don't want to modify thisArg? What should be passed?

const bound = fn.bindArgs(...onlyArgsToBind);
// Then
Bound(...anotherArgsNotInBind);

In the actual example, it was used in chalk, perhaps, when we write:

class LogColor {
  public static readonly DEBUG = chalk.gray.bind(null, ' [DEBUG] ');
  public static readonly INFO = chalk.blue.bind(null, ' [INFO] ');
  public static readonly WARN = chalk.yellow.bind(null, ' [WARN] ');
  public static readonly ERROR = chalk.red.bind(null, ' [ERROR] ');
}

Or in miniaml

const logColor = {
  DEBUG: chalk.gray.bind(null, ' [DEBUG] '),
  INFO: chalk.blue.bind(null, ' [INFO] '),
  WARN: chalk.yellow.bind(null, ' [WARN] '),
  ERROR: chalk.red.bind(null, ' [ERROR] '),
};

We need to pass null exactly to pass thisArg

getRandom

Function signature

  type getRandom = <T>(arr: T[]) => T

What utility function do you need?

function that gets an array and returns a random element from it

What motivates us?

when we want to get a random element from an array

List of examples

  getRandom([1, 2, 3]) // 1 or 2 or 3
  getRandom([]) // undefined
  getRandom('list') // Error: not an array

removeTrailingSlash

Function signature

removeTrailingSlash(str: string): string;

What utility function do you need?

removing trailing slash from a string.

What motivates us?

it's common to have URLs/Paths which end with a trailing slash, in most cases to concat paths we need to ensure the trailing slash is not there.

List of examples

removeTrailingSlash('') // ""
removeTrailingSlash('/') // ""
removeTrailingSlash('string') // "string"
removeTrailingSlash('string/') // "string"
removeTrailingSlash('string//') // "string"

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.