UNPKG

2.84 kBJavaScriptView Raw
1/*!
2 Copyright (c) 2018 Jed Watson.
3 Licensed under the MIT License (MIT), see
4 http://jedwatson.github.io/classnames
5*/
6/* global define */
7
8(function () {
9 'use strict';
10
11 var classNames = (function () {
12 // don't inherit from Object so we can skip hasOwnProperty check later
13 // http://stackoverflow.com/questions/15518328/creating-js-object-with-object-createnull#answer-21079232
14 function StorageObject() {}
15 StorageObject.prototype = Object.create(null);
16
17 function _parseArray (resultSet, array) {
18 var length = array.length;
19
20 for (var i = 0; i < length; ++i) {
21 _parse(resultSet, array[i]);
22 }
23 }
24
25 var hasOwn = {}.hasOwnProperty;
26
27 function _parseNumber (resultSet, num) {
28 resultSet[num] = true;
29 }
30
31 function _parseObject (resultSet, object) {
32 if (object.toString !== Object.prototype.toString && !object.toString.toString().includes('[native code]')) {
33 resultSet[object.toString()] = true;
34 return;
35 }
36
37 for (var k in object) {
38 if (hasOwn.call(object, k)) {
39 // set value to false instead of deleting it to avoid changing object structure
40 // https://www.smashingmagazine.com/2012/11/writing-fast-memory-efficient-javascript/#de-referencing-misconceptions
41 resultSet[k] = !!object[k];
42 }
43 }
44 }
45
46 var SPACE = /\s+/;
47 function _parseString (resultSet, str) {
48 var array = str.split(SPACE);
49 var length = array.length;
50
51 for (var i = 0; i < length; ++i) {
52 resultSet[array[i]] = true;
53 }
54 }
55
56 function _parse (resultSet, arg) {
57 if (!arg) return;
58 var argType = typeof arg;
59
60 // 'foo bar'
61 if (argType === 'string') {
62 _parseString(resultSet, arg);
63
64 // ['foo', 'bar', ...]
65 } else if (Array.isArray(arg)) {
66 _parseArray(resultSet, arg);
67
68 // { 'foo': true, ... }
69 } else if (argType === 'object') {
70 _parseObject(resultSet, arg);
71
72 // '130'
73 } else if (argType === 'number') {
74 _parseNumber(resultSet, arg);
75 }
76 }
77
78 function _classNames () {
79 // don't leak arguments
80 // https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#32-leaking-arguments
81 var len = arguments.length;
82 var args = Array(len);
83 for (var i = 0; i < len; i++) {
84 args[i] = arguments[i];
85 }
86
87 var classSet = new StorageObject();
88 _parseArray(classSet, args);
89
90 var list = [];
91
92 for (var k in classSet) {
93 if (classSet[k]) {
94 list.push(k)
95 }
96 }
97
98 return list.join(' ');
99 }
100
101 return _classNames;
102 })();
103
104 if (typeof module !== 'undefined' && module.exports) {
105 classNames.default = classNames;
106 module.exports = classNames;
107 } else if (typeof define === 'function' && typeof define.amd === 'object' && define.amd) {
108 // register as 'classnames', consistent with npm package name
109 define('classnames', [], function () {
110 return classNames;
111 });
112 } else {
113 window.classNames = classNames;
114 }
115}());