About: Tech Lead/Team Lead. Senior WebDev. Intermediate Grade on Computer Systems- High Grade on Web Application Development- MBA (+Marketing+HHRR). Studied a bit of law, economics and design
So this kind of things that are informal till you make a repo out of it because you've used it in like 30 projects and it has been standarized in some sort across your software😂
I have a framer motion animations file whith all pre coded I just need to import to the new project, thinking about to turn it into a Npm package, so it will be even easier to import
That's a great thing to do! (and usually pretty convenient).
I just did it yesterday with this thing here. Got 200 downloads the first day so I guess others found it useful 😅
I'll need to wait till next Sunday for the weekly stats to update
@mangor1no I have to implement it, and for sure I will, and it will be open for contributions too
I have an rng function that returns a random number between 1-x, and a randomizer function that returns a random item from an array-- the latter is probably used even more than the former!
I also set up a janky function to populate complicated dropdown menus based on arrays and nested arrays (element ID, array, dropdown type). I've ended up reusing it much more than anticipated, so should probably refactor it, ha.
We all have those TODO: Refactor this function/method
at the bottom of our TODO list 😂
Depends on the type of project.
For react websites I have a blocker (loading animation, waiter) which is 80% universal, maybe add a custom (s)css to style it.
I also keep a standard react-table setup that adds a layer upon react-table fixing the issues it has in typescript (types aren't extended when a function is added,)
This little snippet to sleep
const delay = (ms) => new Promise((r) => setTimeout(r, ms));
await delay(1000);
Hahaha no judgements. Still I let you some polling thingy I had here that may be more suitable:
const poll = async ({ fn, validate, interval, maxAttempts }) => {
let attempts = 0;
const executePoll = async (resolve, reject) => {
const result = await fn();
attempts++;
if (validate(result)) {
return resolve(result);
} else if (maxAttempts && attempts === maxAttempts) {
return reject(new Error('Exceeded max attempts'));
} else {
setTimeout(executePoll, interval, resolve, reject);
}
};
return new Promise(executePoll);
};
poll
function is a higher-order function that returns a function, executePoll
.
executePoll
function returns a promise
and will run recursively until the condition is met.
fn
: an API request (or another async thingy that suits for this polling).
validate
: Test function to see if the data matches what we want, in which case it will end the poll.
interval
: To specify how much it wait between poll requests.
maxAttempts
: how many tries before throwing an error.
😁
I couldn't sleep last night and read this comment at 3am. Coincidentally, today, I needed this poll. Works great in my usEffect().
The only thing that caught me is that the parameters to the above poll function are in a class, instead of individual parameters.
Thanks for the code!
Didn't get the meaning of the sentence "The only thing that caught me is that the parameters to the above poll function are in a class, instead of individual parameters." still glad to see it helped you 😁
Apologies, I didn't explain correctly.
Initially, I called the poll function incorrectly as follows:
poll(myFunction, myValidate, myInterval, myMaxAttempts)
The correct method (using your code) is:
poll({
fn: myFunction,
validate: myValidate,
interval: myInterval,
maxAttempts: myMaxAttempts
})
Oh! nothing to do with classes it's just it receives an object but this is opinionated as I prefer to have the object structure for those "config" thingies, you can simply delete the brackets on the function declaration like that:
const poll = async ( fn, validate, interval, maxAttempts ) => {
and we should be good 😁
Nice snippet.
The new Promise callback should not be an async function. By passing an async fn to new Promise you’re “double promising”.
Refactoring to not depend on resolve/reject would solve that.
Or maybe
new Promise((res, rej) => executePoll(res, rej))
Having it as async lets you handle the response, the error and any action to perform either it went OK or KO, so it can be customised specifically on it's environment.
myPoll.then( res => res ).catch( err => console.error( 'myCustomError', err )).finally( () => setExecutionFinished(true));
instead handling it as generic inside the polling function.
But sure you can tweak it as you wish to fullfill your needs 😄
This one is pretty neat, I also use it sometimes to "mock" API responses like this 👇
await delay(1000).then(() => ([ { id: 1, data: "some data" } ]))
I would rather build a reusable library and make it available to anyone that finds it useful.
I don't really have snippets I reuse. I might occasionally pinch a function from another project, but there's nothing I can think of that would be worth a snippet, and I've never really remembered to use them when I've tried.
I do have these vim mappings for older PHP projects which don't have much in the way of development tools:
autocmd FileType php nnoremap <buffer> <leader>dump Oheader('X-XSS-Protection:0');ob_get_clean(); echo '<pre>'; var_dump([]); echo '</pre>'; die(__FILE__ . ':' . __LINE__);<esc>F[a
autocmd FileType php nnoremap <buffer> <leader>args Oheader('X-XSS-Protection:0');ob_get_clean(); echo '<pre>'; var_dump(func_get_args()); echo '</pre>'; die(__FILE__ . ':' . __LINE__);<esc>F[a
autocmd FileType php nnoremap <buffer> <leader>back Oheader('X-XSS-Protection:0');ob_get_clean(); echo '<pre>'; foreach (debug_backtrace() as $d) { echo $d['file'] . ':' . $d['line'] . ' ' . $d['function'] . "()\n"; } echo '</pre>'; d ie(__FILE__ . ':' . __LINE__);<esc>^
They'll let me paste in a variable dump with my cursor positioned where I need to put in the thing to debug, or a generic stack trace. They also cope with frameworks that do tricky things with output buffering.
That's about it.
This will work just for GET requests without authentication, let me do a little tweak on it by just adding an optional "options" parameter 😁
services/api/utils.js
const requestBuilder = (path, options) => fetch(path, options).then(response => response.json()).catch(error => error)
now you can perform any HTTP verb request on a new layer of functions like
PUT example (POST will look mostly the same):
services/api/users.js
:
const updateUser = (user) => requestBuilder( Process.env.API_URL, {
method: 'PUT',
body: JSON.stringify(user),
headers: {
'Content-Type': 'application/json',
Authorization: getToken(),
},
}).then( result => result);
You can try it in your browser terminal right now:
services/api/pokemon.js
:
const getPokemonByName = (pokemon) =>requestBuilder(`https://pokeapi.co/api/v2/pokemon/${pokemon}`, { method: 'GET' })
usage:
getPokemonByName('ditto')
This is my favourite one and universal too:
/**
* Global network request handler
* @param {RequestInfo} url url to fetch
* @param {RequestInit=} options fetch options
* @returns json response
*/
const processFetchRequest = async (url, options) => {
const ts = Date.now();
const method = options?.method || 'GET';
const endpoint = url.match(
/((?!\S+\s)?\S*[/].*?(?:\S+\s)?\S*[/])([\s\S]*)/,
)[2];
const response = await fetch(url, options);
console.log(`${method}${response.status}: ${Date.now() - ts}ms /${endpoint}`);
if (response.ok) {
return response.json();
}
throw response.json();
};
export default processFetchRequest;
Here are a few of the more generally useful ones:
const isSameOrigin = (url: string) =>
new URL(url, window.location.href).origin === window.location.origin
const isTouchDevice = window.matchMedia('(pointer: coarse)').matches
const isMobile = navigator.userAgent.includes('Mobi')
const capitalize = (str: string) => str.charAt(0).toUpperCase() + str.slice(1)
const decodeBase64 = (base64: string) =>
new TextDecoder().decode(new Uint8Array(atob(base64).split('').map((char) => char.charCodeAt(0))))
const encodeBase64 = (str: string) =>
btoa(Array.from(new TextEncoder().encode(str))
.map((n) => String.fromCharCode(n))
.join(''))
const xor = (...args: any[]) =>
args.filter(Boolean).length === 1
Those are currently very useful ones!
I've a slightly different base64encode one
/**
* encodes a file into base64
* @param {import('fs').PathOrFileDescriptor} fileOrigin
* @returns {string}
*/
function base64_encode(fileOrigin) {
/** @type {Buffer} */
const file = fs.readFileSync(fileOrigin);
return Buffer.from(file).toString('base64');
}
I'll check the differences later 😁
The base64 functions from @lionel-rowe are compatible with (most) browser. The fs module is only available in Node.js :)
Of course but what I want to check is the details on what's happening on this TextDecoder()
, it's decode
method and also the reason for it to use an array of 8-bit unsigned integers 😂
TextEncoder
and TextDecoder
convert strings to and from their equivalent UTF-8 bytes. So for example, new TextEncoder().encode('foo 福 🧧')
gives Uint8Array [102, 111, 111, 32, 231, 166, 143, 32, 240, 159, 167, 167]
, where bytes 0..2 represent the 3 ASCII characters "foo", 4..6 represent the single 3-byte character "福", and 8..11 represent the single 4-byte character "🧧" (3 and 7 are spaces).
This is one I made and using across many projects.
/**
* Takes full name and converts into initials
* @param {string} string full name of user e.g John Doe
* @returns initials e.g JD
*/
const getInitials = (string = '') =>
string
.split(' ')
.map(([firstLetter]) => firstLetter)
.filter((_, index, array) => index === 0 || index === array.length - 1)
.join('')
.toUpperCase()
It seems a bit overcomplicated to me, I'd do something like:
const getInitials = (str = '') => str.split(' ').map( part => part.charAt(0).toUpperCase()).join('');
I think it does the same but... Am I missing something maybe? Probably some use case that is not in my mind 😅
For input like Mary Jane Watson
, your function returns MJW
, and his returns MW
.
It's common practice to use only two letters as initials on avatars (eu.ui-avatars.com/api/?name=Mary+J...)
That was one of my first thoughts but initials depend on the country, so my name is Joel Bonet Rxxxxx, being Joel my name and Bonet + Rxxxxx my two surnames.
So in this case I'll be JR with this approach which in my country and according to my culture or what is reasonable, it should be JB. (first character of the name + first character of the surname).
That's the main reason for getting separate fields for name and surname/s.
So your name can be "Mary Jane Linda" and your surnames can be "Lee Bonet".
const initials = `${user.name.charAt(0).toUpperCase()}${user.surname.charAt(0).toUpperCase()}`;
and still getting ML as initials which would be the most correct output as far as I can tell.
Here I am enjoying all the great, open conversations about programming and now I learn something about other cultures too. #Winning
You must restrict your initials to some letter count either one or two, see your initial from the above fn will grow with no. of words in a name which is not favourable to be called 'initials'
And yes my country surnames is at last so picking the last one in my code 😅
utils/ts-utility-types.ts
:
export type PartialBy<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;
export type MaybeNull<T> = T | null;
export type MaybeUndefined<T> = T | undefined;
export type MaybeNil<T> = T | null | undefined;
export type AsyncFn = (...args: any[]) => Promise<any>;
export type AnyFn = (...args: any[]) => any;
export type UnboxPromise<T extends Promise<any>> = T extends Promise<infer U> ? U : never;
export type Nullable<T> = {
[P in keyof T]: MaybeNull<T[P]>;
};
export type NullableBy<T, K extends keyof T> = Omit<T, K> & Nullable<Pick<T, K>>;
export type DistributedArray<U> = U extends any ? U[] : never;
/**
* type ID = string | number;
* type T0 = ID[];
* type T1 = DistributedArray<ID>;
* type EQ1 = IfEquals<T0, T1, 'same', 'different'>; // different
*/
export type IfEquals<T, U, Y = unknown, N = never> = (<G>() => G extends T ? 1 : 2) extends <G>() => G extends U ? 1 : 2 ? Y : N;
export type Optional<T, K extends keyof T> = Pick<Partial<T>, K> & Omit<T, K>;
export type ValueOf<T> = T[keyof T];
C'mon show us some functions 🤣🤣
I'm not sure about those TypeDefs honestly, I think it's better to have an inline, let's say:
const foo: string | null = 'whatever';
so it's more clear for everyone than saying
const foo: MaybeNull<string> = 'whatever';
but to keep the honesty in this comment, this is opinionated and I may be wrong 😅
Function for prevent using try catch
in all async await calls
type Result<DataType> = [
Error | undefined,
DataType | undefined
];
export const to = <DataType = any>(
promise: Promise<DataType>
): Promise<Result<DataType>> => promise
.then((data) => ([undefined, data]) as Result<DataType>)
.catch((err: Error) => ([err, undefined]) as Result<DataType>);
and use it like this
const [data, error] = await to(fetchData());
if (error) {
console.error(error);
return;
}
console.log(data);
to
- funny name. I use similar helper, but I call it go
. Here my recent post about it dev.to/fedyk/golang-errors-handing...
function go<T>(promise: T) {
return Promise.resolve(promise)
.then(result => [null, result] as const)
.catch(err => [err, null] as const)
}
You should do a post on this. I use JavaScript all the time but I'm seeing syntax I'm not familiar with. I feel like I'm peeking through a window from a room I didn't know I was stuck in.
😂 Both @c_basso and @fedyk solutions are coded in TS that can be the cause of your confusion @kevinleebuchan, here's a JS translation (guys correct me if I miss something)
/**
* Handles promise resolution
* @param {Promise} promise
* @returns {any}
*/
export const go = (promise) =>
Promise.resolve(promise)
.then((result) => [result, null])
.catch((error) => [null, error]);
Usage example:
/** Retrieves Ditto data */
const getDitto = async () => {
const [result, error] = await go(fetch('https://pokeapi.co/api/v2/pokemon/ditto'));
if (error) console.error(error);
else console.log(await result.json());
};
await getDitto();
Note that the return value of the go
function is always an array with two positions, the first one intended to be a successful result, the second one reserved for the error so in case it succeeds it sends [result, null]
and in case it fails it sends back [null, error]
, this may help to understanding:
const [result, error] = ['Success!', null];
result; // 'Success!'
error; // null
Hope it helps! 😁
I see very experienced coders here. It would be great if anyone could guide me with my little project.🥲
😂 I was recently wondering why should I keep doing that for every new project idea, so I made a ts npm package to just import my own code everywhere.
Take a look if you want: npmjs.com/package/js-math-and-ui-u...
I work a lot with animations and free-hand user input so one often use is getQuadraticBezierCurvePointAtTime
:
I have an informal stash of useful regexes I copy and paste as needed. Informal meaning it's not quite organized enough for me to cleanly list them here, but it's sort of a system I have that has evolved naturally.