Coder Social home page Coder Social logo

fullstacksjs / toolbox Goto Github PK

View Code? Open in Web Editor NEW
49.0 49.0 14.0 4.38 MB

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

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

License: MIT License

JavaScript 1.24% Shell 1.11% TypeScript 97.65%
fullstacksjs javascript typescript utility

toolbox's Introduction

FullstacksJS

Header

About US

FullstacksJS is an open-source community focused on knowledge sharing, exploring, and enhancing developer experience. The primary objective of this community is to establish a professional environment for in-depth contents in software development and engineering field. In order to learn and strengthen the culture of open source development and contribution, the projects that are developed in this community are entirely open source, and members are encouraged to participate.

Vision

WE GROW TOGETHER

Motivation

The Internet is full of unfiltered programming content, tutorials, and forums, which provide incomplete, outdated, and sometimes incorrect information to the knowledge seekers in this field. Therefore, we decided to establish a community where experts control and review the contents and activities.This creates a community that values in-depth and correct content.

Values

Values form our community and influence its behavior also have a direct impact on community's decision-making and contents.

  • Ethics: Ethics is the most important value in the community, which has the highest priority in decisions. In the community, moral principles are never sacrificed for the sake of other activities.

  • Validity: Expert approval is required for every community-produced and published content. If an error is discovered in previously published content, the community must notify the appropriate parties and update the content.

Social Media

toolbox's People

Contributors

abxlfazl avatar alirezaalatifi avatar amirabbasj avatar amirhbeigi avatar amirhoseinsalimi avatar amirhosseinkarimi avatar asafaeirad avatar createdbymahmood avatar erfan-goodarzi avatar freakingeek avatar hamed-bavar avatar keivan-sf avatar mahdi-sheibak avatar mohammadizanloo55 avatar pourdaavar avatar

Stargazers

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

Watchers

 avatar  avatar  avatar

toolbox's Issues

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

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"}

[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]: 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.

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.

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"

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 📦🚀

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>

[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]: 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.

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"

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]: 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.

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]

[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]: 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),

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]: 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

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

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

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

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.