DEV Community

Cover image for Which functions/methods do you...
JoelBonetR πŸ₯‡
JoelBonetR πŸ₯‡

Posted on • Edited on

Which functions/methods do you...

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?

Oldest comments (52)

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
 
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
 
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
 
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
 
andrewbaisden profile image
Andrew Baisden

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

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
 
tim012432 profile image
Timo

I've never used that one xD

Collapse
 
camco profile image
Camco

Love this

Collapse
 
sjatkins profile image
Samantha Atkins

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

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