Skip to content
ReferenceVersion 6.0.2

Core, Date, and Number Utilities ​

Import these utilities from @/utils. Core implementations are available from @/utils/core and precision functions from @/utils/precision.

Core utilities example ​

Compare PromiseLike values with async functions, try synchronous and asynchronous error callbacks, or inspect paths, date ranges, and object updates.

View core example source
tsx
import { useI18n } from '@/hooks'
import {
  callWithAsyncErrorHandling,
  callWithErrorHandling,
  detectOperatingSystem,
  equalRouterPath,
  getAppEnvironment,
  getDateByNaiveDatePicker,
  isAsyncFunction,
  isPromise,
  isValueType,
  removeDuplicateKeys,
  updateObjectValue,
  uuid,
} from '@/utils'
import {
  NButton,
  NCard,
  NDatePicker,
  NFlex,
  NInput,
  NInputNumber,
  NSelect,
  NSwitch,
} from 'naive-ui'
import DemoPage from './components/DemoPage'
import DemoResult from './components/DemoResult'

export default defineComponent({
  name: 'DocsCoreUtils',
  setup() {
    const { t } = useI18n('docsExamples')
    const text = (key: string) => t<string>(key)
    const kind = ref<'text' | 'thenable' | 'async'>('thenable')
    const length = ref<number | null>(8)
    const radix = ref<number | null>(36)
    const generated = ref('')
    const fail = ref(false)
    const errorResult = ref('')
    const first = ref('/orders/?page=1')
    const second = ref('/orders#details')
    const field = ref(text('core.pending'))
    const range = ref<[number, number] | null>(null)
    const row = reactive<{ order: { id?: string; status: string } }>({
      order: { id: 'ORD-001', status: text('core.initial') },
    })
    const { MODE, DEV, PROD } = getAppEnvironment()
    const sample = computed(() => {
      if (kind.value === 'async') return async () => text('core.complete')

      if (kind.value === 'thenable')
        return { then: () => text('core.complete') }

      return text('core.complete')
    })
    const generate = () => {
      generated.value =
        callWithErrorHandling(
          () => uuid(length.value ?? 0, radix.value ?? 36),
          (error: Error) => {
            generated.value = error.message
          },
        ) ?? generated.value
    }
    const handleError = (error: Error) => {
      errorResult.value = error.message
    }
    const run = async (asyncMode: boolean) => {
      const execute = () => {
        if (fail.value) throw new Error(text('core.failed'))

        return text('core.succeeded')
      }
      const result = asyncMode
        ? await callWithAsyncErrorHandling(async () => execute(), handleError)
        : callWithErrorHandling(execute, handleError)

      if (result) errorResult.value = result
    }

    return () => (
      <DemoPage title={text('core.title')} description={text('core.intro')}>
        <div class="r-demo-grid">
          <NCard title="isValueType · isPromise · isAsyncFunction">
            <NSelect
              aria-label={text('core.inputType')}
              options={[
                { label: text('core.text'), value: 'text' },
                { label: text('core.thenable'), value: 'thenable' },
                { label: text('core.asyncFn'), value: 'async' },
              ]}
              v-model:value={kind.value}
            />
            <DemoResult label={text('core.checkResult')}>
              <pre>
                {JSON.stringify(
                  {
                    String: isValueType(sample.value, 'String'),
                    Function: isValueType(sample.value, 'Function'),
                    isPromise: isPromise(sample.value),
                    isAsyncFunction: isAsyncFunction(sample.value),
                  },
                  null,
                  2,
                )}
              </pre>
            </DemoResult>
          </NCard>
          <NCard title={text('core.errorCallbacks')}>
            <NFlex>
              <NInputNumber
                v-model:value={length.value}
                min={0}
                max={64}
                aria-label={text('core.idLength')}
              />
              <NInputNumber
                v-model:value={radix.value}
                min={1}
                max={62}
                aria-label={text('core.radix')}
              />
              <NButton onClick={generate}>{text('core.generate')}</NButton>
            </NFlex>
            <DemoResult label={text('core.identifier')}>
              {generated.value}
            </DemoResult>
            <NFlex align="center">
              <NSwitch
                v-model:value={fail.value}
                aria-label={text('core.simulateFailure')}
              />{' '}
              {text('core.simulateFailure')}
              <NButton onClick={() => run(false)}>
                {text('core.runSync')}
              </NButton>
              <NButton onClick={() => run(true)}>
                {text('core.runAsync')}
              </NButton>
            </NFlex>
            <DemoResult label={text('core.execution')}>
              {errorResult.value}
            </DemoResult>
          </NCard>
          <NCard title={text('core.pathAndObject')}>
            <NFlex>
              <NInput
                v-model:value={first.value}
                aria-label={text('core.pathOne')}
              />
              <NInput
                v-model:value={second.value}
                aria-label={text('core.pathTwo')}
              />
              <code>{String(equalRouterPath(first.value, second.value))}</code>
            </NFlex>
            <NFlex>
              <NInput
                v-model:value={field.value}
                aria-label={text('core.orderStatus')}
              />
              <NButton
                onClick={() =>
                  updateObjectValue(row, 'order', {
                    status: field.value,
                  })
                }
              >
                {text('core.merge')}
              </NButton>
            </NFlex>
            <DemoResult label={text('core.shallowCopy')}>
              <code>{JSON.stringify(removeDuplicateKeys(row))}</code>
            </DemoResult>
          </NCard>
          <NCard title={text('core.dateAndEnvironment')}>
            <NDatePicker
              v-model:value={range.value}
              type="daterange"
              clearable
              aria-label={text('core.dateRange')}
            />
            <DemoResult label={text('core.dateResult')}>
              <code>
                {JSON.stringify(getDateByNaiveDatePicker(range.value, true))}
              </code>
            </DemoResult>
            <DemoResult label={text('core.environment')}>
              <code>
                {JSON.stringify({
                  MODE,
                  DEV,
                  PROD,
                  os: detectOperatingSystem(),
                })}
              </code>
            </DemoResult>
          </NCard>
        </div>
      </DemoPage>
    )
  },
})

Types, identifiers, and error handling ​

APIInput and return value
isValueType<T>(value, type)Checks the Object.prototype.toString tag. Ordinary and async functions both match Function.
isPromise<T>(value)Returns true for a callable then, including custom PromiseLike values.
isAsyncFunction(fn)Tests for an async declaration. Returning a promise from an ordinary function does not match.
uuid(length = 16, radix = 62)Web Crypto random identifier. The character set is digits, uppercase letters, then lowercase letters. Radix is 1–62 and length is a nonnegative safe integer. Invalid input throws RangeError. The identifier uses this custom format.
callWithErrorHandling(fn, onError, args?)Returns the synchronous result. On exception, calls the callback and returns undefined. It does not await promises.
callWithAsyncErrorHandling(fn, onError, args?)Awaits the result and handles both synchronous exceptions and rejections. Errors thrown by the callback reach the caller.
ts
import { callWithAsyncErrorHandling, uuid } from '@/utils'

export const draftId = () => 'draft-' + uuid(12, 36)

export function loadOrReport<T>(
  load: () => Promise<T>,
  report: (error: Error) => void,
) {
  return callWithAsyncErrorHandling(load, report)
}

Objects, paths, and dates ​

  • updateObjectValue(obj, key, value, callback?) updates only own properties. If both values are plain objects, it shallow-merges them. Otherwise it replaces the old value. Success invokes the callback.
  • removeDuplicateKeys(obj) returns a shallow copy of own enumerable properties. Duplicate keys in a JavaScript literal already use the last value by object creation.
  • equalRouterPath(a, b) ignores query, hash, and trailing slash. Use full paths when filters or tab instances matter.
  • getDateByNaiveDatePicker(value, isRange) converts an empty range from null to [null, null] and preserves other values, including units, time zone, and format.
  • getAppEnvironment() exposes Vite import.meta.env for values such as MODE, DEV, and PROD. Keep secrets out of client-visible configuration.
  • detectOperatingSystem() uses the User-Agent to return an OperatingSystem such as iOS (including iPad with a desktop identifier), Android, Windows, macOS, Linux, or Unknown. Use it for display hints and detect capabilities separately.

Fixed-point arithmetic ​

CurrencyArguments can be a number, string, or currency.js instance. The template defaults to eight decimal places. Results are currency.js instances with .value and .toString().

Interactive example ​

Change both numbers and compare add with JavaScript +. This example calls @ray-template/utils/precision directly.

每个数最多输入 7 位整数和 8 位小数。

定点运算:0.30000000
JavaScript 加法:0.30000000000000004
isCurrency: true / false
View example source
vue
<template>
  <div class="ray-demo" :lang="locale ?? 'zh-CN'">
    <div class="ray-demo-fields">
      <div>
        <label :for="firstId">{{ copy.first }}</label>
        <input
          :id="firstId"
          v-model.trim="first"
          class="ray-demo-input"
          inputmode="decimal"
          :aria-describedby="hintId"
          :aria-invalid="!isDecimal(first)"
        />
      </div>
      <div>
        <label :for="secondId">{{ copy.second }}</label>
        <input
          :id="secondId"
          v-model.trim="second"
          class="ray-demo-input"
          inputmode="decimal"
          :aria-describedby="hintId"
          :aria-invalid="!isDecimal(second)"
        />
      </div>
    </div>
    <p :id="hintId" class="ray-demo-hint">{{ copy.hint }}</p>
    <output class="ray-demo-result" :for="`${firstId} ${secondId}`">
      <span v-if="result">
        {{ copy.fixed }}:<code>{{ result.fixed }}</code>
        <br />
        {{ copy.native }}:<code>{{ result.native }}</code>
        <br />
        <code>isCurrency: {{ result.isFixed }} / {{ result.isNative }}</code>
      </span>
      <span v-else>{{ copy.invalid }}</span>
    </output>
  </div>
</template>

<script setup lang="ts">
import { add, isCurrency } from '@ray-template/utils/precision'
import { computed, ref, useId } from 'vue'

const props = defineProps<{ locale?: 'zh-CN' | 'en' }>()
const copy = computed(() =>
  props.locale === 'en'
    ? {
        first: 'First number',
        second: 'Second number',
        fixed: 'Fixed precision',
        native: 'JavaScript addition',
        hint: 'Enter up to 7 integer digits and 8 decimal places per number.',
        invalid: 'Enter two valid decimal numbers.',
      }
    : {
        first: '第一个数',
        second: '第二个数',
        fixed: '定点运算',
        native: 'JavaScript 加法',
        hint: '每个数最多输入 7 位整数和 8 位小数。',
        invalid: '请输入两个有效的十进制数。',
      },
)
const first = ref('0.1')
const second = ref('0.2')
const firstId = useId()
const secondId = useId()
const hintId = useId()
const isDecimal = (value: string) =>
  /^[+-]?(?:\d{1,7}(?:\.\d{0,8})?|\.\d{1,8})$/.test(value)
const result = computed(() => {
  if (!isDecimal(first.value) || !isDecimal(second.value)) return

  const fixed = add(first.value, second.value)
  const native = Number(first.value) + Number(second.value)

  return {
    fixed: fixed.toString(),
    native,
    isFixed: isCurrency(fixed),
    isNative: isCurrency(native),
  }
})
</script>

The admin precision demo also provides subtraction, multiplication, division, and allocation.

View the complete precision demo source
tsx
import { useI18n } from '@/hooks'
import { add, distribute, divide, format, multiply, subtract } from '@/utils'
import {
  NCard,
  NDynamicTags,
  NFormItem,
  NGrid,
  NGridItem,
  NInputNumber,
} from 'naive-ui'
import DemoPage from '../components/DemoPage'
import DemoResult from '../components/DemoResult'

const operations = { add, subtract, multiply, divide }

export default defineComponent({
  name: 'CalculatePrecision',
  setup() {
    const { t } = useI18n('demoDetails')
    const operands = reactive({
      add: ['0.1', '0.2'],
      subtract: ['1', '0.7'],
      multiply: ['0.1', '0.2'],
      divide: ['1', '3'],
    })
    const amount = ref<number | null>(10)
    const parts = ref<number | null>(3)
    const allocation = computed(() =>
      amount.value === null || parts.value === null
        ? []
        : distribute(amount.value, parts.value),
    )

    return () => (
      <DemoPage title={t('precision.title')} description={t('precision.intro')}>
        <div class="r-demo-grid">
          {(Object.keys(operations) as (keyof typeof operations)[]).map(
            (operation) => {
              const values = operands[operation]
              const invalid =
                !values.length ||
                values.some(
                  (value) => !/^-?(?:\d+(?:\.\d*)?|\.\d+)$/.test(value),
                )
              const zeroDivisor =
                operation === 'divide' &&
                values.slice(1).some((value) => Number(value) === 0)
              let result = t('precision.invalid')

              if (!invalid && !zeroDivisor) {
                try {
                  result = String(format(operations[operation](...values)))
                } catch {
                  result = t('precision.invalid')
                }
              }

              return (
                <NCard key={operation} title={t(`precision.${operation}`)}>
                  <div class="r-demo-card-stack">
                    <NDynamicTags v-model:value={operands[operation]} />
                    <DemoResult
                      label={t('result')}
                      error={invalid || zeroDivisor}
                    >
                      <strong>
                        {zeroDivisor ? t('precision.zero') : result}
                      </strong>
                    </DemoResult>
                  </div>
                </NCard>
              )
            },
          )}
          <NCard class="r-demo-grid__wide" title={t('precision.allocation')}>
            <div class="r-demo-card-stack">
              <NGrid cols="1 480:2" responsive="self" xGap={16}>
                <NGridItem>
                  <NFormItem label={t('precision.amount')} showFeedback={false}>
                    <NInputNumber v-model:value={amount.value} />
                  </NFormItem>
                </NGridItem>
                <NGridItem>
                  <NFormItem label={t('precision.parts')} showFeedback={false}>
                    <NInputNumber
                      v-model:value={parts.value}
                      min={1}
                      max={12}
                      precision={0}
                    />
                  </NFormItem>
                </NGridItem>
              </NGrid>
              <DemoResult label={t('result')}>
                <code>
                  {allocation.value.length
                    ? allocation.value.join(' + ')
                    : t('empty')}
                </code>
              </DemoResult>
            </div>
          </NCard>
        </div>
      </DemoPage>
    )
  },
})

API ​

APIBehavior
add(...values)Sum. No arguments return zero.
subtract(first, ...rest)Subtract in order.
multiply(first, ...rest)Multiply in order, parsing string factors first.
divide(first, ...rest)Divide in order. Zero divisors or nonfinite results throw RangeError.
format(value, options?)Convert at the chosen precision. Defaults to a number. type: 'string' returns a string retaining precision.
distribute(value, length, options?)Split evenly and assign rounding remainders to the first shares. 0 and 1 both mean one share. Negative or noninteger counts throw. Supports precision and type.
isCurrency(value)Checks for an instance of the current currency.js class.
ts
import { add, distribute, format } from '@/utils'

export const amount = format(add('0.1', '0.2'), {
  precision: 2,
  type: 'string',
})
export const parts = distribute(10, 3, { precision: 2, type: 'string' })

Define decimal places and rounding rules for allocation and settlement in the business code. currency.js stores scaled integers as JavaScript numbers, so the amount times 10 ** precision must remain within the safe integer range. Transfer strings or integer minor units across APIs to avoid binary floating-point artifacts in display.

Core utilities · Precision implementation · Date picker helper