DEV Community

Cover image for Which functions/methods do you...

Which functions/methods do you...

JoelBonetR 🥇 on May 09, 2022

Which functions/methods do you copy from a project to another or re-code just to have them in some utils.js or utils.ts?
Collapse
 
danielfy profile image
Daniel Fyhr

This little snippet to sleep

const delay = (ms) => new Promise((r) => setTimeout(r, ms));
await delay(1000);
Enter fullscreen mode Exit fullscreen mode
Collapse
 
joelbonetr profile image
JoelBonetR 🥇

I'm afraid to ask where you need this one 😂😂

Collapse
 
danielfy profile image
Daniel Fyhr

I've used it for polling. And... Sometimes you got to do what you got to do 😂

Thread Thread
 
joelbonetr profile image
JoelBonetR 🥇

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);
};
Enter fullscreen mode Exit fullscreen mode

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.

Args explained:

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.

😁

Thread Thread
 
rishadomar profile image
Rishad Omar

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!

Thread Thread
 
joelbonetr profile image
JoelBonetR 🥇

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 😁

Thread Thread
 
rishadomar profile image
Rishad Omar • Edited

Apologies, I didn't explain correctly.
Initially, I called the poll function incorrectly as follows:

poll(myFunction, myValidate, myInterval, myMaxAttempts)
Enter fullscreen mode Exit fullscreen mode

The correct method (using your code) is:

poll({
   fn: myFunction,
   validate: myValidate,
   interval: myInterval,
   maxAttempts: myMaxAttempts
})
Enter fullscreen mode Exit fullscreen mode
Thread Thread
 
joelbonetr profile image
JoelBonetR 🥇 • Edited

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 ) => {
Enter fullscreen mode Exit fullscreen mode

and we should be good 😁

Thread Thread
 
alexparra profile image
Alex Parra • Edited

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))
Enter fullscreen mode Exit fullscreen mode
Thread Thread
 
joelbonetr profile image
JoelBonetR 🥇 • Edited

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));
Enter fullscreen mode Exit fullscreen mode

instead handling it as generic inside the polling function.

But sure you can tweak it as you wish to fullfill your needs 😄

Collapse
 
rgolawski profile image
Rafał Goławski

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" } ]))
Enter fullscreen mode Exit fullscreen mode
Collapse
 
danielfy profile image
Daniel Fyhr

I love that one!

Collapse
 
camco profile image
Camco

Love this

Collapse
 
tim012432 profile image
Timo

I've never used that one xD

Collapse
 
lionelrowe profile image
lionel-rowe

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
Enter fullscreen mode Exit fullscreen mode
Collapse
 
joelbonetr profile image
JoelBonetR 🥇

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');
}
Enter fullscreen mode Exit fullscreen mode

I'll check the differences later 😁

Collapse
 
brunnerlivio profile image
Livio Brunner • Edited

The base64 functions from @lionel-rowe are compatible with (most) browser. The fs module is only available in Node.js :)

Thread Thread
 
joelbonetr profile image
JoelBonetR 🥇 • Edited

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 😂

Thread Thread
 
lionelrowe profile image
lionel-rowe

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).

Thread Thread
 
joelbonetr profile image
JoelBonetR 🥇

Thanks you for the explanation! 😁

Collapse
 
ben profile image
Ben Halpern

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.

Collapse
 
joelbonetr profile image
JoelBonetR 🥇

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😂

Collapse
 
mrdulin profile image
official_dulin

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];
Enter fullscreen mode Exit fullscreen mode
Collapse
 
joelbonetr profile image
JoelBonetR 🥇

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';
Enter fullscreen mode Exit fullscreen mode

so it's more clear for everyone than saying

const foo: MaybeNull<string> = 'whatever';
Enter fullscreen mode Exit fullscreen mode

but to keep the honesty in this comment, this is opinionated and I may be wrong 😅

Collapse
 
moopet profile image
Ben Sinclair • Edited

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>^
Enter fullscreen mode Exit fullscreen mode

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.

Collapse
 
alessandrocipolletti profile image
Alessandro Cipolletti • Edited

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

getQuadraticBezierCurvePointAtTime

Collapse
 
psnapier profile image
P.S. Napier • Edited

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.

Collapse
 
joelbonetr profile image
JoelBonetR 🥇

We all have those TODO: Refactor this function/method at the bottom of our TODO list 😂

Collapse
 
siddsarkar profile image
Siddhartha Sarkar

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()
Enter fullscreen mode Exit fullscreen mode
Collapse
 
joelbonetr profile image
JoelBonetR 🥇 • Edited

It seems a bit overcomplicated to me, I'd do something like:

const getInitials = (str = '') =>  str.split(' ').map( part => part.charAt(0).toUpperCase()).join('');
Enter fullscreen mode Exit fullscreen mode

I think it does the same but... Am I missing something maybe? Probably some use case that is not in my mind 😅

Collapse
 
kamil7x profile image
Kamil Trusiak

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...)

Thread Thread
 
joelbonetr profile image
JoelBonetR 🥇 • Edited

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()}`; 
Enter fullscreen mode Exit fullscreen mode

and still getting ML as initials which would be the most correct output as far as I can tell.

Thread Thread
 
kevinleebuchan profile image
KevinLeeBuchan

Here I am enjoying all the great, open conversations about programming and now I learn something about other cultures too. #Winning

Collapse
 
siddsarkar profile image
Siddhartha Sarkar

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 😅

Collapse
 
brampayrequest profile image
Bram Hammer

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,)

Collapse
 
wiseai profile image
Mahmoud Harmouch

The rafce shortcut is a life-saver.

Collapse
 
efraimjer profile image
Efraim Jerszurki

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

Collapse
 
joelbonetr profile image
JoelBonetR 🥇 • Edited

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

Collapse
 
mangor1no profile image
Mangor1no

Can you share it with us? Framer motion is a great package tho

Collapse
 
efraimjer profile image
Efraim Jerszurki

@mangor1no I have to implement it, and for sure I will, and it will be open for contributions too

Collapse
 
sjatkins profile image
Samantha Atkins

I would rather build a reusable library and make it available to anyone that finds it useful.

Collapse
 
c_basso profile image
Vladimir Ivakhnenko

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>);

Enter fullscreen mode Exit fullscreen mode

and use it like this

const [data, error] = await to(fetchData());

if (error) {
   console.error(error);
   return;
}

console.log(data);
Enter fullscreen mode Exit fullscreen mode
Collapse
 
fedyk profile image
Andrii Fedyk

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)
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
kevinleebuchan profile image
KevinLeeBuchan

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.

Collapse
 
joelbonetr profile image
JoelBonetR 🥇 • Edited

😂 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]);
Enter fullscreen mode Exit fullscreen mode

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();
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Hope it helps! 😁

Collapse
 
ajinspiro profile image
Arun Kumar

let callApi=(path) => fetch(path).then(response => response.json())

Collapse
 
joelbonetr profile image
JoelBonetR 🥇

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)
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

Working example

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' })
Enter fullscreen mode Exit fullscreen mode

usage:

getPokemonByName('ditto')
Enter fullscreen mode Exit fullscreen mode
Collapse
 
siddsarkar profile image
Siddhartha Sarkar

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;
Enter fullscreen mode Exit fullscreen mode
Collapse
 
jgomo3 profile image
Jesús Gómez

The identity function in any language that doesn't have it.

Collapse
 
andrewbaisden profile image
Andrew Baisden

I have a function that I use for Mock API Calls that gets reused a lot.

Collapse
 
himanshupal0001 profile image
Himanshupal0001

I see very experienced coders here. It would be great if anyone could guide me with my little project.🥲

Collapse
 
luiz0x29a profile image
Real AI

none, I publish my standard library to public repos and import it.