DEV Community 👩‍💻👨‍💻

Dragoljub Bogićević
Dragoljub Bogićević

Posted on

Utils for JavaScript - what do you use regularly?

Recently, I started working on my own utils set of JavaScript functions that can be used on every day basis.

This is the current list (full docs can be found here):

  • Compare objects
  • Compare arrays
  • Check if an array or an object is empty
  • Make array unique
  • Get min value of an array of numbers
  • Get max value of an array of numbers
  • Check if variable is an integer
  • Create random number
  • Cache function result
  • Calculate how much time a function takes to run

Which functions do you use, in which cases, please comment down bellow, certainly I would consider all suggestions and add new functions as part of npm package.

Thank you for reading and all suggestions!

Top comments (5)

Collapse
vonheikemen profile image
Heiker

map and filter for objects. I've done this a couple of times.

const Obj = {
  map(fn, data) {
    let result = {};
    for (let [key, value] of Object.entries(data)) {
      result[key] = fn(value, key, data);
    }

    return result;
  },
  filter(fn, data) {
    let result = {};
    for (let [key, value] of Object.entries(data)) {
      if(fn(value, key, data)) {
        result[key] = value;
      }
    }

    return result;
  }
};

I've also used a "better" typeof.

function what_is(arg) {
  const is = Object.prototype.toString.call(arg);

  return {
    val: () => is,
    object: () => is == '[object Object]',
    array: () => is == '[object Array]',
    promise: () => is == '[object Promise]',
    undefined: () => is == '[object Undefined]',
    null: () => is == '[object Null]',
    number: () => is == '[object Number]',
    func: () => is == '[object Function]'
  };
}
Collapse
bravemaster619 profile image
bravemaster619 • Edited on

Safe number for price calculations.

const safeNumber = (num, defaultValue = 0, allowNegative = false) => {
  if (!num) {
    num = 0;
  }
  num = Number(num)
  if (isNaN(num)) {
    if (defaultValue === undefined) {
      console.log(num)
      throw new Error('Given argument is NaN')
    } else {
      return defaultValue
    }
  }
  if (num === Infinity) {
    if (defaultValue === undefined) {
      console.log(num)
      throw new Error('Given argument is infinity')
    } else {
      return defaultValue
    }
  }
  if (!allowNegative && num < 0) {
    if (defaultValue === undefined) {
      console.log(num)
      throw new Error('Given argument is negative')
    } else {
      return defaultValue
    }
  }
  return num
}
Collapse
patarapolw profile image
Pacharapol Withayasakpunt • Edited on
export async function mapAsync<T, R = T> (
  arr: T[],
  cb: (el: T, i: number, a0: T[]) => Promise<R>,
): Promise<R[]> {
  return Promise.all(arr.map(async (el, i, a0) => {
    return await cb(el, i, a0)
  }))
}

export function distinctBy<T> (arr: T[], k: string, undefinedIsDistinct?: boolean): T[] {
  const arrK = arr.map((a) => hash((a as any)[k]))
  return arr.filter((a, i) => {
    const aK = (a as any)[k]
    if (aK === undefined) {
      return !!undefinedIsDistinct
    } else {
      return arrK.indexOf(hash(aK)) === i
    }
  })
}

export function * chunk<T> (arr: T[], n: number) {
  for (let i = 0; i < arr.length; i += n) {
    yield arr.slice(i, i + n)
  }
}

Are you trying to create next lodash or something?

Collapse
brightknight08 profile image
Tim Anthony Manuel • Edited on

Hmm... What about..

[array].every(item=>[array2].includes(item))
Collapse
bogicevic7 profile image
Dragoljub Bogićević Author • Edited on

Good one! Added to version 1.0.9...

🌚 Browsing with dark mode makes you a better developer.

It's a scientific fact.