fullstacksjs / toolbox Goto Github PK
View Code? Open in Web Editor NEWA zero-dependency 📦 tree-shakable🌲 collection of missing JavaScript utilities.
Home Page: https://toolbox.fullstacksjs.com/
License: MIT License
A zero-dependency 📦 tree-shakable🌲 collection of missing JavaScript utilities.
Home Page: https://toolbox.fullstacksjs.com/
License: MIT License
toCamelCase
to working for "UPPER_CASE_SNAKE".
toCamelCase("UPPER_CASE_SNAKE"); // "upperCaseSnake"
toCamelCase("UPPER_CASE_SNAKE"); // "UPPER_CASE_SNAKE"
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:
pruneNullOrEmpty(obj: T): T;
removing null or empty values from an object.
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.
pruneNullOrEmpty({ firstName: null, lastName: "PRD" }) // { lastName: "PRD" }
pruneNullOrEmpty({ firstName: '', lastName: "PRD" }) // { lastName: "PRD" }
pruneNullOrEmpty({ firstName: '', lastName: "PRD", age: null }) // { lastName: "PRD"}
The isNull
guard is not working for the nested nullable chain.
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();
}
It throws the "Object is possibly 'undefined" error.
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.
function
function throttle<T extends Function>(options: { interval: number; isImmediate?: boolean }, f: T): T
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.
array
function toggleArrayValue<T extends unknown>(array: T[], value: T): T[]
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.
const minuteFormat = (value) => {
const minutes = Math.trunc(value / 60);
const seconds = value % 60;
return `${minutes < 10 ? `0${minutes}` : minutes}:${seconds < 10 ? `0${seconds}` : seconds}`;
};
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
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.
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 📦🚀
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;
};
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
const priceFormat = (value) => {
return `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
};
simply pass a number and get a nu,mber ¯_(ツ)_/¯
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:
compactArray<T extends unknown[]>(xs: T): CompactArray<T>
the compact is a function that removes all nullish values from an array
the compact function is very useful in arrays in config or optional tasks.
compact([1, false, null, 2, undefined]) // [1, false, 2]
compact([NaN, false, null, 0, undefined]) // [NaN, false, 0]
It would be useful to have an AsyncVoidFunction
type.
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.
type AsyncVoidFn = () => Promise<void>
Line 26 in 28b5465
Why do we have to accept the default value in this function?
If this variable is so necessary that we should get an error if the value of the variable is not specified, I think it is not correct to set the default value
type shuffle = <T>(arr:T[]) => T[]
a function which takes an array and returns the shuffled version of it
when we want to shuffle an array
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
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#
There should be only one link on the Function drop down menu navigating to the tryOr
utility page.
There are two links (the main one and an external one) on the Function drop down menu navigating to the tryOr
utility page.
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;
};
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
export function toDecimal(s: Nullable<string>, fallback: number = NaN): number {}
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),
function merge(obj1: T, obj2: U, composer?: (value1, value2, key, obj1, obj2): DeepMerge<T, U>
It is quite useful for configuration management.
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>
the functions purpose is to abstract the nasty try-catch syntax into a function
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
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
array
function uniq<T extends any[]>(array: T): T
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.
function
function debounce<T extends Function>(options: { delay: number; isImmediate?: boolean }, f: T): T
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.
declare global {
export interface Function {
bindArgs<T, A extends unknown[]>(this: T, ...args: A): OmitThisParameter<T>;
}
}
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
type getRandom = <T>(arr: T[]) => T
function that gets an array and returns a random element from it
when we want to get a random element from an array
getRandom([1, 2, 3]) // 1 or 2 or 3
getRandom([]) // undefined
getRandom('list') // Error: not an array
removeTrailingSlash(str: string): string;
removing trailing slash from a string.
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.
removeTrailingSlash('') // ""
removeTrailingSlash('/') // ""
removeTrailingSlash('string') // "string"
removeTrailingSlash('string/') // "string"
removeTrailingSlash('string//') // "string"
As TS 5 has better support on NodeJS ESM, we can upgrade our source code to use that.
Here are the release notes of the new typescript node16
target and bundler
module resolution.
https://devblogs.microsoft.com/typescript/announcing-typescript-5-0/
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.