5 JavaScript functions to add to your utilities library

Eddie Aich on October 16, 2019

We all have our own utilities - dealing with date/time, validating common forms, etc, or maybe you use a third-party utility library like lodash or... [Read Full]
markdown guide

Nice. My only comment would be that the ellipsis cut-off should probably subtract the length of the ellipsis, as typically you may want to conform to a database field size. I.e varchar(100) you could end up with 103 chars including the ellipsis,

so like:

function summarize(str, max) {
  return str.length > max ? str.substring(0, max-3) + '...' : str;

Even better, it should split at the end of a word and not in the middle of one

function summarize(str, max) {
  if (str.length <= max) return str;
  const subString = str.substring(0, max - 1);
  return subString.substring(0, subString.lastIndexOf(" ")) + "...";

Even better, use the unicode ellipsis (; \u2026).


If you sprinkle a little "data last" with some partial application and you really got something on the groupBy.

- function groupBy(arr, key) {
+ function groupBy(key, arr) {
+  if(arguments.length === 1) {
+    return groupBy.bind(null, key);
+  }

  return arr.reduce(
   (acc, i) => {
      (acc[i[key]] = acc[i[key]] || []).push(i);
      return acc;
    }, {});

Now you can have a factory of functions:

const groupByType = groupBy('type');
const groupByName = groupBy('name');
// and many more

groupByType(roleModels) // stuff...

// or just call it like a normal person
groupBy('type', roleModels);

It's a neat trick, but it's a little YAGNI isn't it? I can't really think of a situation where I would use this


Is certainly not necessary. You can always wrap the thing in another function.

const groupByType = arr => groupBy(arr, 'type');

It does come handy when callbacks are involve.

// function composition in ramda style
const complexFunc = pipe(someFunc, groupBy('type'), otherFunc);

// when mapping

// a raw promise (if you are one of those)
code of conduct - report abuse