Skip to content
loading...

Utils for JavaScript - what do you use regularly?

bogicevic7 profile image Dragoljub Bogićević twitter logo github logo ・1 min read  

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!

twitter logo DISCUSS (5)
Discussion
markdown guide
 

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]'
  };
}
 

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

 

Hmm... What about..

[array].every(item=>[array2].includes(item))
 
Classic DEV Post from Jul 27 '19

If You Don't Know, Now You Know - GitHub Is Restricting Access For Users From Iran And A Few Other Embargoed Countries

Please help our cause against modern-day discrimination

Dragoljub Bogićević profile image
202 Accepted