Introduction to kind-of
kind-of
is a versatile JavaScript library that allows developers to determine the type of a JavaScript value with ease. It offers a robust and efficient way to handle type-checking for various data types, including primitives, arrays, objects, and more.
Getting Started with kind-of
// Install the kind-of library
npm install kind-of
// Require kind-of in your project
const kindOf = require('kind-of');
Basic API Examples
// Check for primitive types
console.log(kindOf('hello')); // 'string'
console.log(kindOf(42)); // 'number'
console.log(kindOf(true)); // 'boolean'
console.log(kindOf(null)); // 'null'
console.log(kindOf(undefined)); // 'undefined'
console.log(kindOf(Symbol('foo'))); // 'symbol'
// Check for complex types
console.log(kindOf([])); // 'array'
console.log(kindOf({})); // 'object'
console.log(kindOf(new Date())); // 'date'
console.log(kindOf(new RegExp('foo'))); // 'regexp'
console.log(kindOf(function() {})); // 'function'
// Additional type checks
console.log(kindOf(new Error())); // 'error'
console.log(kindOf(Promise.resolve())); // 'promise'
console.log(kindOf(Buffer.from('foo'))); // 'buffer'
Advanced API Examples
// Check for specific object types
console.log(kindOf(new Map())); // 'map'
console.log(kindOf(new Set())); // 'set'
console.log(kindOf(new WeakMap())); // 'weakmap'
console.log(kindOf(new WeakSet())); // 'weakset'
// Custom class instance
class MyClass {}
console.log(kindOf(new MyClass())); // 'object'
Application Example with kind-of
Here is a practical example of how kind-of
can be used in a Node.js application to dynamically handle different input types.
const kindOf = require('kind-of');
function processInput(input) {
switch (kindOf(input)) {
case 'string':
console.log('Processing string:', input);
break;
case 'number':
console.log('Processing number:', input);
break;
case 'boolean':
console.log('Processing boolean:', input);
break;
case 'array':
console.log('Processing array:', input);
input.forEach(item => processInput(item));
break;
case 'object':
console.log('Processing object:', input);
for (let key in input) {
processInput(input[key]);
}
break;
default:
console.log('Unrecognized type:', kindOf(input));
}
}
// Example usage:
processInput('Hello World');
processInput(123);
processInput(true);
processInput([1, 'foo', false]);
processInput({ a: 1, b: 'bar', c: [2, 3] });
With kind-of
, managing different data types becomes straightforward, enhancing the robustness and flexibility of your applications.
Hash: 2b91f9d1e2cfc4abb30c89013ce671d162eb3b30cfb9cb469fac0065dcc2d863