API Reference

nb.pubfn Public Function Library

Tool function library designed with reference to vk-unicloud

Time Processing · Data Validation · Array Operations · Tree Structure


🎯 Overview

nb.pubfn is NextJS Base's public function library, designed with reference to vk-unicloud's pubfn API, providing unified utility functions.

Usage

import nb from '@/lib/function'

// Usage Examples
nb.pubfn.isNull(value)
nb.pubfn.timeFormat(new Date())
nb.pubfn.tree.arrayToTree(list)

📚 API Directory

CategoryFunctions
Time ProcessingtimeFormat, getDateInfo, getCommonTime, sleep
Data ValidationisNull, isNotNull, test, validator
Type CheckingisArray, isObject, isString, getType
Object OperationsdeepClone, getData, setData, formAssign
Array OperationsgetListItem, arrayUnique, arraySort, groupBy
Tree StructurearrayToTree, treeToArray, mapTree, findInTree
String Processinghidden, random, trim, truncate
Encoding Conversionuuid, encodeBase64, parseJSON
Math CalculationsformatMoney, priceFilter, toDecimal
Function Utilitiesdebounce, throttle, batchRun

⏰ Time Processing

timeFormat - Date Formatting

nb.pubfn.timeFormat(date, format, targetTimezone)
ParameterTypeDefaultDescription
dateDate/Number/String-Date object, timestamp, or string
formatString'yyyy-MM-dd hh:mm:ss'Format template
targetTimezoneNumber8Target timezone

Format Placeholders: yyyy(year), MM(month), dd(day), hh(hour), mm(minute), ss(second), S(millisecond)

nb.pubfn.timeFormat(new Date(), 'yyyy-MM-dd')
// "2025-12-03"

nb.pubfn.timeFormat(1733136000000, 'yyyy年MM月dd日 hh:mm')
// "2025年12月02日 18:00"

getDateInfo - Parse Date

const info = nb.pubfn.getDateInfo(new Date())
// { year: 2025, month: 12, day: 3, hour: 10, minute: 30, second: 0, week: 3, quarter: 4 }

getCommonTime - Common Time Ranges

const time = nb.pubfn.getCommonTime()
// { todayStart, todayEnd, monthStart, monthEnd, yearStart, yearEnd, weekStart, weekEnd, now }

sleep - Sleep Wait

await nb.pubfn.sleep(1000)  // Wait 1 second

✅ Data Validation

isNull / isNotNull - Null Value Check

The following values are considered null: undefined, null, "", {}, []

nb.pubfn.isNull(null)       // true
nb.pubfn.isNull('')         // true
nb.pubfn.isNull({})         // true
nb.pubfn.isNull([])         // true
nb.pubfn.isNull(0)          // false
nb.pubfn.isNotNull('hello') // true

isNullOne / isNullAll / isNotNullAll - Batch Check

nb.pubfn.isNullOne(a, b, c)     // At least one is null
nb.pubfn.isNullAll(a, b, c)     // All are null
nb.pubfn.isNotNullAll(a, b, c)  // All are not null

test - Format Validation

typeDescription
mobileMobile number
emailEmail
urlURL
ipIP address
cardID card
numberPure numbers
chinesePure Chinese
passwordPassword (6-18 characters)
nb.pubfn.test('13800138000', 'mobile')  // true
nb.pubfn.test('[email protected]', 'email')  // true

🔍 Type Checking

nb.pubfn.isArray([1, 2, 3])      // true
nb.pubfn.isObject({ a: 1 })      // true
nb.pubfn.isString('hello')       // true
nb.pubfn.isNumber(123)           // true
nb.pubfn.isFunction(() => {})    // true
nb.pubfn.isDate(new Date())      // true

nb.pubfn.getType([])             // 'array'
nb.pubfn.getType({})             // 'object'
nb.pubfn.getType(null)           // 'null'

📦 Object Operations

deepClone - Deep Clone

const newObj = nb.pubfn.deepClone(obj)

getData / setData - Path Get/Set

const obj = { a: { b: { c: 1 } } }

nb.pubfn.getData(obj, 'a.b.c')           // 1
nb.pubfn.getData(obj, 'a.b.d', 'default') // 'default'

nb.pubfn.setData(obj, 'a.b.c', 2)
nb.pubfn.setData(obj, 'x.y.z', 3)  // Auto-create path

formAssign - Form Data Fill

const defaultData = { name: '', age: 0, enable: true }
const itemData = { name: 'John', age: 25 }

const formData = nb.pubfn.formAssign(defaultData, itemData)
// { name: 'John', age: 25, enable: true }

getNewObject / deleteObjectKeys

const obj = { id: 1, name: 'John', password: '123' }

nb.pubfn.getNewObject(obj, ['id', 'name'])  // { id: 1, name: 'John' }
nb.pubfn.deleteObjectKeys(obj, ['password']) // { id: 1, name: 'John' }

📋 Array Operations

getListItem - Get Object in Array

const list = [
  { id: 1, name: 'John' },
  { id: 2, name: 'Jane' }
]

nb.pubfn.getListItem(list, 'id', 2)  // { id: 2, name: 'Jane' }
nb.pubfn.getListIndex(list, 'id', 2) // 1

arrayToJson - Array to Object

const list = [
  { id: 'a', name: 'John' },
  { id: 'b', name: 'Jane' }
]

nb.pubfn.arrayToJson(list, 'id')
// { a: { id: 'a', name: 'John' }, b: { id: 'b', name: 'Jane' } }

arrayObjectGetArray - Extract Field

nb.pubfn.arrayObjectGetArray(list, 'id')  // ['a', 'b']

arrayUnique - Array Deduplication

nb.pubfn.arrayUnique([1, 2, 2, 3])  // [1, 2, 3]
nb.pubfn.arrayUnique([{id:1},{id:2},{id:1}], 'id')  // [{id:1},{id:2}]

arraySort - Array Sort

nb.pubfn.arraySort([3, 1, 2])  // [1, 2, 3]
nb.pubfn.arraySort([{age:30},{age:20}], 'age', 'desc')  // [{age:30},{age:20}]

arrayDiff / arrayIntersect / arrayUnion - Set Operations

nb.pubfn.arrayDiff([1,2,3], [2,3,4])       // [1] (difference)
nb.pubfn.arrayIntersect([1,2,3], [2,3,4])  // [2,3] (intersection)
nb.pubfn.arrayUnion([1,2,3], [2,3,4])      // [1,2,3,4] (union)

groupBy - Group

const list = [
  {type:'a', v:1},
  {type:'b', v:2},
  {type:'a', v:3}
]
nb.pubfn.groupBy(list, 'type')
// { a: [{type:'a',v:1},{type:'a',v:3}], b: [{type:'b',v:2}] }

sum / average / max / min - Statistics

nb.pubfn.sum([1, 2, 3])       // 6
nb.pubfn.average([1, 2, 3])   // 2
nb.pubfn.max([1, 2, 3])       // 3
nb.pubfn.min([1, 2,3])       // 1

nb.pubfn.sum([{v:1},{v:2}], 'v')  // 3

shuffle / sample - Random

nb.pubfn.shuffle([1, 2, 3, 4, 5])      // Random shuffle
nb.pubfn.sample([1, 2, 3, 4, 5])       // Random pick one
nb.pubfn.sampleSize([1, 2, 3, 4, 5], 3) // Random pick 3

🌳 Tree Structure

All tree utilities are under nb.pubfn.tree.

arrayToTree - Array to Tree

nb.pubfn.tree.arrayToTree(arr, options)
ParameterTypeDefaultDescription
idString'id'Primary key field
parentIdString'parentId'Parent field
childrenString'children'Children field
rootParentIdanynullRoot node parentId
filterFunction-Filter function
sortByArray-Sort configuration
const list = [
  { id: 1, parentId: null, name: 'System Management' },
  { id: 2, parentId: 1, name: 'User Management' },
  { id: 3, parentId: 1, name: 'Role Management' },
]

const tree = nb.pubfn.tree.arrayToTree(list, {
  filter: (item) => item.enable !== false,
  sortBy: [{ field: 'sort', order: 'asc' }]
})

treeToArray - Tree to Array

nb.pubfn.tree.treeToArray(tree, { addLevel: true })
// [{ id: 1, name: 'A', level: 0 }, { id: 2, name: 'B', level: 1 }, ...]

mapTree - Map Tree

const selectTree = nb.pubfn.tree.mapTree(menuTree, (node) => ({
  title: node.name,
  value: node.id,
  key: node.id,
}))

findInTree - Find Node

const node = nb.pubfn.tree.findInTree(tree, (item) => item.id === 'menu-1')

filterTree - Filter Tree

const filtered = nb.pubfn.tree.filterTree(tree, (item) => 
  item.name.includes('User')
)

getLeaves - Get Leaf Nodes

const leaves = nb.pubfn.tree.getLeaves(tree)

📝 String Processing

hidden - Hide Middle Characters

nb.pubfn.hidden('13800138000', 3, 4)  // '138****8000'

random - Random String

nb.pubfn.random(6)                // '123456' (numbers only)
nb.pubfn.random(8, 'a-z,0-9')     // 'a1b2c3d4'
nb.pubfn.random(10, 'a-z,A-Z,0-9') // 'aB1cD2eF3g'

trim / truncate

nb.pubfn.trim('  hello  ')         // 'hello'
nb.pubfn.truncate('hello world', 8) // 'hello...'

capitalize / uncapitalize

nb.pubfn.capitalize('hello')    // 'Hello'
nb.pubfn.uncapitalize('Hello')  // 'hello'

🔐 Encoding Conversion

uuid / shortUuid

nb.pubfn.uuid()       // 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'
nb.pubfn.shortUuid()  // 'a1b2c3d4' (8 characters)

encodeBase64 / decodeBase64

nb.pubfn.encodeBase64('hello')     // 'aGVsbG8='
nb.pubfn.decodeBase64('aGVsbG8=')  // 'hello'

parseJSON / stringifyJSON

nb.pubfn.parseJSON('{"a":1}')      // { a: 1 }
nb.pubfn.parseJSON('invalid', {})  // {} (returns default value on parse failure)

💰 Math Calculations

formatMoney - Thousand Separator Formatting

nb.pubfn.formatMoney(1234567.89)     // '1,234,567.89'
nb.pubfn.formatMoney(1234567.89, 0)  // '1,234,568'

priceFilter - Cents to Yuan

nb.pubfn.priceFilter(100)   // '1.00'
nb.pubfn.priceFilter(1234)  // '12.34'

toDecimal - Keep Decimals

nb.pubfn.toDecimal(1.56555, 2)  // 1.57

🔧 Function Utilities

debounce - Debounce

nb.pubfn.debounce(() => {
  // Execute search
}, 300)

throttle - Throttle

nb.pubfn.throttle(() => {
  // Execute operation
}, 1000)

batchRun - Concurrent Execution

const tasks = [
  () => fetch('/api/1'),
  () => fetch('/api/2'),
]
const results = await nb.pubfn.batchRun(tasks, 2)  // Max 2 concurrent

✅ Best Practices

1. Prefer nb.pubfn for Type Checking

// ✅ Recommended
if (nb.pubfn.isArray(value)) { }
if (nb.pubfn.isNull(data)) { }

// ❌ Not Recommended
if (Array.isArray(value)) { }
if (!data || data === '') { }

2. Use tree Utilities for Tree Data

// ✅ Recommended
const tree = nb.pubfn.tree.arrayToTree(list)
const node = nb.pubfn.tree.findInTree(tree, predicate)

// ❌ Not Recommended: Manual recursion
function buildTree(list, parentId = null) { ... }

3. Use uuid Uniformly for ID Generation

// ✅ Recommended
const id = nb.pubfn.uuid()

// ❌ Not Recommended
import { v4 as uuidv4 } from 'uuid'

On this page

nb.pubfn Public Function Library
🎯 Overview
Usage
📚 API Directory
⏰ Time Processing
timeFormat - Date Formatting
getDateInfo - Parse Date
getCommonTime - Common Time Ranges
sleep - Sleep Wait
✅ Data Validation
isNull / isNotNull - Null Value Check
isNullOne / isNullAll / isNotNullAll - Batch Check
test - Format Validation
🔍 Type Checking
📦 Object Operations
deepClone - Deep Clone
getData / setData - Path Get/Set
formAssign - Form Data Fill
getNewObject / deleteObjectKeys
📋 Array Operations
getListItem - Get Object in Array
arrayToJson - Array to Object
arrayObjectGetArray - Extract Field
arrayUnique - Array Deduplication
arraySort - Array Sort
arrayDiff / arrayIntersect / arrayUnion - Set Operations
groupBy - Group
sum / average / max / min - Statistics
shuffle / sample - Random
🌳 Tree Structure
arrayToTree - Array to Tree
treeToArray - Tree to Array
mapTree - Map Tree
findInTree - Find Node
filterTree - Filter Tree
getLeaves - Get Leaf Nodes
📝 String Processing
hidden - Hide Middle Characters
random - Random String
trim / truncate
capitalize / uncapitalize
🔐 Encoding Conversion
uuid / shortUuid
encodeBase64 / decodeBase64
parseJSON / stringifyJSON
💰 Math Calculations
formatMoney - Thousand Separator Formatting
priceFilter - Cents to Yuan
toDecimal - Keep Decimals
🔧 Function Utilities
debounce - Debounce
throttle - Throttle
batchRun - Concurrent Execution
✅ Best Practices
1. Prefer nb.pubfn for Type Checking
2. Use tree Utilities for Tree Data
3. Use uuid Uniformly for ID Generation
📚 Related Documentation