Run details:
Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:96.0) Gecko/20100101 Firefox/96.0
Firefox 96
Mac OS X 10.15
Desktop
2 years ago
Test name Executions per second
classnames 2387848.2 Ops/sec
clsx 3628755.5 Ops/sec
My attempt using templateLiterals 2508559.0 Ops/sec
HTML Preparation code:
x
 
1
2
<script src='https://cdnjs.cloudflare.com/ajax/libs/classnames/2.2.6/index.min.js'></script>
3
<script src='https://unpkg.com/clsx@1.1.0/dist/clsx.min.js'></script>
Script Preparation code:
 
var str = 'style';
var obj = {
     'style-2': true,
     'style-3': false,
     'style-4': true,
}
var arr = ['style-5', 'style-6']
Tests:
  • classnames

     
    let result = window.classNames(str, obj, arr, 'test classname')
  • clsx

     
    let result = window.clsx(str, obj, arr, 'test classname')
  • My attempt using templateLiterals

     
    const classname = (...args) => {
      let joined = "";
      args.forEach((arg) => {
        if (!arg || typeof arg === 'boolean') {
          return;
        }
        if (typeof arg === "string") {
          joined += ` ${arg} `;
        } else if (typeof arg === "object") {
          if (arg?.join) {
            joined += arg.filter((v) => !!v).join(" ");
          } else {
            const keys = Object.keys(arg);
            keys.forEach(key => {
              if(!!arg[key]){
                joined += ` ${key} `
              }
            })
          }
        }
      });
      return joined;
    };
    let result = classname(str, obj, arr, 'test classname')