@zdepot/utils
v1.2.1
Published
Safety Type Conversion Utility Library, providing type judgment and conversion methods with fallback values
Downloads
388
Maintainers
Readme
@zdepot/utils
Safe type conversion tool library, which provides the method of type judgment and conversion with bottom value, to ensure that your code will not throw exceptions because of type problems.
Features
✅ Type Safety - Accurate type detection based on Object.prototype.toString
✅ Fallback Protection - All conversion methods have default fallback values to prevent runtime errors
✅ JSON Parsing - Smart JSON parsing with automatic type detection
✅ Circular References - Safe JSON serialization with automatic circular reference and function handling
✅ TypeScript Support - Complete TypeScript type definitions
✅ Tree-shaking - Side-effect free, compatible with bundler optimization
Installation
npm install @zdepot/utilsUsage
// 默认导入
import safe from '@zdepot/utils'
// 或命名导入
import { safe } from '@zdepot/utils'API
isSameType(a, b)
Checks if two values are of the same type, using Object.prototype.toString for precise detection.
safe.isSameType([], []) // true
safe.isSameType({}, []) // false
safe.isSameType(1, '1') // falsearray(value)
Ensures an array is returned. Returns the input directly if it's an array; parses JSON strings automatically; otherwise returns an empty array [].
safe.array([1, 2]) // [1, 2]
safe.array('[1,2]') // [1, 2]
safe.array('hello') // []
safe.array(null) // []string(value, fallback?)
Ensures a string is returned. Returns the input directly if it's a string, otherwise returns the fallback value (default "").
safe.string('hello') // 'hello'
safe.string(123) // ''
safe.string(123, 'default') // 'default'number(value, fallback?)
Ensures a number is returned. Uses Number() for conversion, returns fallback value (default 0) if result is NaN or Infinity.
safe.number(123) // 123
safe.number('456') // 456
safe.number('abc') // 0
safe.number('abc', -1) // -1
safe.number(Infinity) // 0jsonParse(value, fallback)
JSON.parse with fallback value. Returns fallback if parsing fails or result type doesn't match fallback type.
safe.jsonParse('{"a":1}', {}) // { a: 1 }
safe.jsonParse('invalid', {}) // {}
safe.jsonParse('"hello"', []) // [] (type mismatch)
safe.jsonParse(null, {}) // {}jsonParseObj(value, fallback)
Enhanced jsonParse that only processes strings starting with [ or { (objects/arrays), otherwise returns fallback directly. Built-in length limit prevents DoS attacks.
safe.jsonParseObj('{"a":1}', {}) // { a: 1 }
safe.jsonParseObj('[1,2]', []) // [1, 2]
safe.jsonParseObj('"hello"', {}) // {} (doesn't start with [ or {)
safe.jsonParseObj('invalid', {}) // {}split(value, splitStr)
Safe String.split. Empty strings return [] instead of [''], errors also return [].
safe.split('a,b,c', ',') // ['a', 'b', 'c']
safe.split('', ',') // []
safe.split(null, ',') // []boolean(value, fallback?)
Ensures a boolean is returned. Supports true/false strings (case-insensitive) and 0/1 numbers.
safe.boolean(true) // true
safe.boolean('TRUE') // true
safe.boolean(1) // true
safe.boolean('false') // false
safe.boolean(0) // false
safe.boolean('hello') // false (fallback value)date(value, fallback?)
Ensures a Date object is returned. Supports Date objects, timestamps, and date strings.
safe.date(new Date()) // returns as-is
safe.date(1700000000000) // new Date(1700000000000)
safe.date('2023-01-01') // new Date('2023-01-01')
safe.date('invalid') // new Date() (current time)
safe.date('invalid', fallback) // fallbackfunction(value, fallback?)
Ensures a function is returned. Returns the input directly if it's a function, otherwise returns the fallback value (default empty function).
safe.function(fn) // fn
safe.function(null) // () => undefined
safe.function(null, () => 'hi') // () => 'hi'nonEmptyString(value, fallback?)
Ensures a non-empty string is returned. Returns the input if it's a non-empty string, otherwise returns the fallback value.
safe.nonEmptyString('hello') // 'hello'
safe.nonEmptyString(' ') // '' (whitespace only)
safe.nonEmptyString('') // ''
safe.nonEmptyString(123, 'N/A') // 'N/A'email(value, fallback?)
Ensures a valid email string is returned.
safe.email('[email protected]') // '[email protected]'
safe.email('invalid') // ''
safe.email('bad', '[email protected]') // '[email protected]'timestamp(value, fallback?)
Ensures a valid timestamp is returned.
safe.timestamp(1700000000000) // 1700000000000
safe.timestamp(new Date()) // date.getTime()
safe.timestamp('2023-01-01') // 1672531200000
safe.timestamp('invalid', 0) // 0jsonStringify(value, indent?)
Safe JSON serialization. Automatically handles circular references and functions without throwing.
safe.jsonStringify({ a: 1 }) // '{"a":1}'
safe.jsonStringify({ fn: () => {} }) // '{"fn":"[Function]"}'
const obj: any = { name: 'test' }
obj.self = obj
safe.jsonStringify(obj) // '{"name":"test","self":"[Circular]"}'Use Cases
// API response handling
const data = safe.jsonParse(response.data, defaultValue)
const items = safe.array(data.items)
// Config file parsing
const config = safe.jsonParseObj(fs.readFileSync('config.json', 'utf-8'), {})
// User input processing
const username = safe.string(input.username, 'guest')
const age = safe.number(input.age, 0)
// String splitting
const parts = safe.split(input.tags, ',') // avoids split(',a', ',') returning ['', 'a']License
MIT
