|
1 | | -import { countObj, objType } from 'tiny-essentials'; |
2 | | - |
3 | 1 | /** |
4 | 2 | * Validates the total value based on the type of the input. |
5 | 3 | * |
@@ -74,3 +72,54 @@ export function superValidator(obj) { |
74 | 72 | // Complete |
75 | 73 | return result; |
76 | 74 | } |
| 75 | + |
| 76 | +/** |
| 77 | + * Checks the type of a given object or returns its type as a string. |
| 78 | + * |
| 79 | + * @param {*} obj - The object to check or identify. |
| 80 | + * @param {string} [type] - Optional. If provided, checks whether the object matches this type (e.g., "object", "array", "string"). |
| 81 | + * @returns {boolean|string|null} - Returns `true` if the type matches, `false` if not, |
| 82 | + * the type string if no type is provided, or `null` if the object is `undefined`. |
| 83 | + * |
| 84 | + * @example |
| 85 | + * objType([], 'array'); // true |
| 86 | + * objType({}, 'object'); // true |
| 87 | + * objType('hello'); // "string" |
| 88 | + * objType(undefined); // null |
| 89 | + */ |
| 90 | +export function objType(obj, type) { |
| 91 | + // Is Defined |
| 92 | + if (typeof obj !== 'undefined') { |
| 93 | + // Get Obj Type |
| 94 | + const result = Object.prototype.toString.call(obj).toLowerCase(); |
| 95 | + // Check Obj Type |
| 96 | + if (typeof type === 'string') { |
| 97 | + if (result === `[object ${type}]`) return true; |
| 98 | + return false; |
| 99 | + } |
| 100 | + // Send Result |
| 101 | + return result.substring(8, result.length - 1); |
| 102 | + } |
| 103 | + // Nope |
| 104 | + return null; |
| 105 | +} |
| 106 | + |
| 107 | +/** |
| 108 | + * Counts the number of elements in an array or the number of properties in an object. |
| 109 | + * |
| 110 | + * @param {*} obj - The array or object to count. |
| 111 | + * @returns {number} - The count of items (array elements or object keys), or `0` if the input is neither an array nor an object. |
| 112 | + * |
| 113 | + * @example |
| 114 | + * countObj([1, 2, 3]); // 3 |
| 115 | + * countObj({ a: 1, b: 2 }); // 2 |
| 116 | + * countObj('not an object'); // 0 |
| 117 | + */ |
| 118 | +export function countObj(obj) { |
| 119 | + // Is Array |
| 120 | + if (Array.isArray(obj)) return obj.length; |
| 121 | + // Object |
| 122 | + if (objType(obj, 'object')) return Object.keys(obj).length; |
| 123 | + // Nothing |
| 124 | + return 0; |
| 125 | +} |
0 commit comments