npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@zdepot/utils

v1.2.1

Published

Safety Type Conversion Utility Library, providing type judgment and conversion methods with fallback values

Downloads

388

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/utils

Usage

// 默认导入
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')     // false

array(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)       // 0

jsonParse(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)   // fallback

function(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)    // 0

jsonStringify(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