wsemi

wsemi

new wsemi()

Source:

Members

(static) execCliCore

Description:
  • execCli系列函數之共用核心, 提供可獨立使用之函數: buildSpawnArgs(將命令轉為Windows安全之spawn參數)與buildSpawnEnv(建立子進程環境變數)

    本核心自行匯入fs、path(僅Node環境使用), 不需由呼叫端注入相依(無opt.fs等注入鍵); buildSpawnEnv之envExtra非一般物件視為未給, 不拋錯亦不展開為環境變數鍵

    Unit Test: Github

Source:

execCli系列函數之共用核心, 提供可獨立使用之函數: buildSpawnArgs(將命令轉為Windows安全之spawn參數)與buildSpawnEnv(建立子進程環境變數)

本核心自行匯入fs、path(僅Node環境使用), 不需由呼叫端注入相依(無opt.fs等注入鍵); buildSpawnEnv之envExtra非一般物件視為未給, 不拋錯亦不展開為環境變數鍵

Unit Test: Github

Example
//need test in nodejs

let { buildSpawnArgs, buildSpawnEnv } = execCliCore

//buildSpawnArgs, Windows下npm全域命令(.cmd)會被解析為以node執行其JS入口
let sp = buildSpawnArgs('node', ['-e', 'console.log(1)'])
console.log(sp)
// => { file: 'C:\\...\\node.exe', args: [ '-e', 'console.log(1)' ], opt: {} } (Windows)
// => { file: 'node', args: [ '-e', 'console.log(1)' ], opt: {} } (非Windows)

//spawn
import { spawn } from 'child_process'
let proc = spawn(sp.file, sp.args, { stdio: 'pipe', windowsHide: true, ...sp.opt })

//buildSpawnEnv, 以process.env為底併入額外變數, 不動本進程
let env = buildSpawnEnv({ API_KEY: 'abc' })
console.log(env.API_KEY, env.PYTHONIOENCODING, process.env.API_KEY)
// => abc utf-8 undefined

Methods

(static) ab2blob(ab, optopt) → {Blob|Object}

Description:
  • ArrayBuffer資料轉Blob資料

    Unit Test: Github

Source:
Example
need test in browser

let ab = (new Uint8Array([66, 97, 115])).buffer
let bb = ab2blob(ab)
console.log(bb)
// => Blob {size: 3, type: ""}

console.log(ab2blob('abc', { returnWithStateAndMsg: true }))
// => { state: 'error', msg: 'invalid ab: must be an ArrayBuffer' }
Parameters:
Name Type Attributes Default Description
ab ArrayBuffer

輸入ArrayBuffer資料

opt Object <optional>
{}

輸入設定物件,預設{}

Properties
Name Type Attributes Default Description
returnWithStateAndMsg Boolean <optional>
false

輸入是否回傳含狀態與訊息物件布林值,若為true則回傳{ state, msg }物件,state為'success'或'error',msg於success時為回傳結果、於error時為錯誤訊息字串,預設false

Returns:

回傳Blob資料,輸入非ArrayBuffer時回傳空Blob;若opt.returnWithStateAndMsg為true則回傳{ state, msg }物件 失敗之辨識:預設模式於本函數所偵測之失敗(輸入無效或轉換失敗)時不拋錯而回傳空Blob(size為0),而空Blob(size為0)亦為合法輸入之結果(如ab2blob(new ArrayBuffer(0))),故不可由回傳值判斷成敗;須辨識失敗時請設opt.returnWithStateAndMsg為true,以回傳之state === 'error'判定(只涵蓋本函數所偵測之失敗,msg為錯誤訊息)

Type
Blob | Object

(static) ab2u8arr(ab, optopt) → {Uint8Array|Object}

Description:
  • ArrayBuffer轉Uint8Array

    Unit Test: Github

Source:
Example
let ab = (new Uint8Array([66, 97, 115])).buffer
console.log(ab2u8arr(ab))
// => new Uint8Array([66, 97, 115])
Parameters:
Name Type Attributes Default Description
ab ArrayBuffer

輸入ArrayBuffer

opt Object <optional>
{}

輸入設定物件,預設{}

Properties
Name Type Attributes Default Description
returnWithStateAndMsg Boolean <optional>
false

輸入是否回傳含狀態與訊息物件布林值,若為true則回傳{ state, msg }物件,state為'success'或'error',msg於success時為回傳結果、於error時為錯誤訊息字串,預設false

Returns:

回傳Uint8Array,輸入非ArrayBuffer時回傳空Uint8Array;若opt.returnWithStateAndMsg為true則回傳{ state, msg }物件 失敗之辨識:預設模式於本函數所偵測之失敗(輸入無效或轉換失敗)時不拋錯而回傳空Uint8Array(長度0),而空Uint8Array(長度0)亦為合法輸入之結果(如ab2u8arr(new ArrayBuffer(0))),故不可由回傳值判斷成敗;須辨識失敗時請設opt.returnWithStateAndMsg為true,以回傳之state === 'error'判定(只涵蓋本函數所偵測之失敗,msg為錯誤訊息)

Type
Uint8Array | Object

(static) addExcelWorksheetFromData(wb, data, sheetNameopt) → {Object}

Description:
  • 由數據陣列轉成為Excel的Worksheet物件並添加至Workbook物件

    Workbook物件格式為{ sheets: [{ name, rows }] }(見createExcelWorkbook),數據陣列可為二維陣列(mat)或物件陣列(ltdt),見getExcelWorksheetFromData

    Unit Test: Github

Source:
Example
let data = [
    ['a', '123', 456],
    [null, 'abc123', '', 111.222333],
]

let wb = createExcelWorkbook()
console.log(wb)
// => { sheets: [] }

wb = addExcelWorksheetFromData(wb, data, 'tester')
console.log(JSON.stringify(wb))
// => {"sheets":[{"rows":[["a","123",456],[null,"abc123","",111.222333]],"name":"tester"}]}
Parameters:
Name Type Attributes Default Description
wb Object

輸入Excel的Workbook物件

data Array

輸入數據陣列,可為二維陣列(mat)或物件陣列(ltdt)

sheetName String <optional>
'data'

輸入輸出為Excel時所在分頁(sheet)名稱字串,預設為'data'

Returns:

回傳添加分頁後的Workbook物件,輸入無效時回傳{ error }物件

Type
Object

(static) addMonth(g, n) → {String}

Description:
  • 輸入年月並增加/減少月份數量

    g與n為必須參數,n須為有效整數(iseint,數字字串亦可,去頭尾空白後取值,可為正負值),無效(含Infinity、小數、'0x10'、包裝物件)回傳'';計算後日期無效(月份數量過大而超出dayjs可表示範圍)或計算後年份超出0~9999(如加上100000個月得10353年)亦回傳''

    Unit Test: Github

Source:
Example
console.log(addMonth('2019-01', 2))
// => '2019-03'

console.log(addMonth('2018-12', -1))
// => '2018-11'

console.log(addMonth('2019-01', '3'))
// => '2019-04'

console.log(addMonth('2019-01', Infinity))
// => ''

console.log(addMonth('9999-12', 1))
// => '' (計算後年份10000超出0~9999)
Parameters:
Name Type Description
g String

輸入月時間字串

n Integer | String

輸入要增加的月份數量整數,可為正負值,須為有效整數(安全整數,數字字串亦可),無效回傳''

Returns:

回傳新的月時間字串,輸入無效或計算後日期無效、年份超出0~9999時回傳''

Type
String

(static) aes2str(str, key, base64opt, optopt) → {String|Object}

Description:
  • AES字串轉一般字串 為str2aes之解密函數,使用AES-128-CBC解密,字串採用PKCS#7填充 str與base64須與加密時str2aes所用之設定相同,否則解不出原文而回傳空字串

    Unit Test: Github

Source:
Example
let str = '53616c7465645f5f47214797ac01bc03cceb69ebced4948501ab94ca9644a6dfd277456aead4432cb9c9d74c38c42c79'
let key = '1234567890abcdefghijk'
console.log(aes2str(str, key))
// => 'test中文abcdefghijklmn'
Parameters:
Name Type Attributes Default Description
str String

輸入AES加密字串,非有效字串時回傳空字串

key String

輸入加密key,非有效字串時回傳空字串

base64 Boolean <optional>
false

輸入來源字串是否為base64格式,須與加密時str2aes所用之設定相同,非布林值時回退為false,預設為false

opt Object <optional>
{}

輸入設定物件,預設{}

Properties
Name Type Attributes Default Description
returnWithStateAndMsg Boolean <optional>
false

輸入是否回傳含狀態與訊息物件布林值,若為true則回傳{ state, msg }物件,state為'success'或'error',msg於success時為回傳結果、於error時為錯誤訊息字串,預設false

Returns:

回傳經AES解密後字串,str或key非有效字串、或key錯誤而解不出明文時回傳空字串;若opt.returnWithStateAndMsg為true則回傳{ state, msg }物件,可據此分辨解密失敗與明文為空 失敗之辨識:預設模式於本函數所偵測之失敗(輸入無效或轉換失敗)時不拋錯而回傳空字串'';須可靠辨識失敗時請設opt.returnWithStateAndMsg為true,以回傳之state === 'error'判定(只涵蓋本函數所偵測之失敗,msg為錯誤訊息)

Type
String | Object

(static) alive(optopt) → {Object}

Description:
  • 偵測單元是否在線

    Unit Test: Github

Source:
Example
async function topAsync() {

    function test1() {
        return new Promise((resolve, reject) => {
            let ms = []

            let oAL = alive({ timeAlive: 1500 })
            let t = Date.now()

            let a = { data: 123 }
            let b = { data: '34.56' }

            setTimeout(() => {
                console.log(parseInt((Date.now() - t)) + 'ms', 'trigger a1')
                oAL.trigger('a', a)
            }, 500)

            setTimeout(() => {
                console.log(parseInt((Date.now() - t)) + 'ms', 'trigger a2')
                oAL.trigger('a', a)
            }, 1900)

            setTimeout(() => {
                console.log(parseInt((Date.now() - t)) + 'ms', 'trigger b1')
                oAL.trigger('b', b)
            }, 1000)

            setTimeout(() => {
                console.log(parseInt((Date.now() - t)) + 'ms', 'trigger b2')
                oAL.trigger('b', b)
            }, 3000)

            oAL.on('message', function({ eventName, key, data, now }) {
                console.log(parseInt((Date.now() - t)) + 'ms', { eventName, key, data, now })
                ms.push(eventName + '|' + key)
            })

            setTimeout(() => {
                resolve(ms)
            }, 5000)

        })
    }
    console.log('test1')
    let r1 = await test1()
    console.log(JSON.stringify(r1))
    // test1
    // 503ms trigger a1
    // 508ms { eventName: 'enter', key: 'a', data: { data: 123 }, now: 1 }
    // 1001ms trigger b1
    // 1003ms { eventName: 'enter', key: 'b', data: { data: '34.56' }, now: 2 }
    // 1901ms trigger a2
    // 2523ms { eventName: 'leave', key: 'b', data: { data: '34.56' }, now: 1 }
    // 3002ms trigger b2
    // 3004ms { eventName: 'enter', key: 'b', data: { data: '34.56' }, now: 2 }
    // 3430ms { eventName: 'leave', key: 'a', data: { data: 123 }, now: 1 }
    // 4544ms { eventName: 'leave', key: 'b', data: { data: '34.56' }, now: 0 }
    // ["enter|a","enter|b","leave|b","enter|b","leave|a","leave|b"]

    function test2() {
        return new Promise((resolve, reject) => {
            let ms = []

            let oAL = alive({ timeAlive: 1500 })

            oAL.on('message', function({ eventName, key }) {
                ms.push(eventName + '|' + key)
            })

            oAL.trigger('a', { data: 123 })

            setTimeout(() => {
                oAL.trigger('b', { data: '34.56' })
                let r = oAL.clear() //b剛trigger尚未發出enter, 故只回傳a, 且b之enter不再發出
                ms.push('clear|' + r.map((v) => v.key).join(','))
            }, 500)

            setTimeout(() => {
                resolve(ms)
            }, 2500)

        })
    }
    console.log('test2')
    let r2 = await test2()
    console.log(JSON.stringify(r2))
    // test2
    // ["enter|a","clear|a"]

}
topAsync().catch(() => {})
Parameters:
Name Type Attributes Default Description
opt Object <optional>
{}

輸入設定物件,預設{}

Properties
Name Type Attributes Default Description
timeAlive Integer <optional>
10000

輸入判斷單元是否斷線之延時正整數(1至9007199254740991,數字字串亦可),單位為毫秒ms,預設為10000;非預期(0、負數、小數、Infinity、超過安全整數、'0x10'等)視為未給而改用預設10000,不報錯(Infinity不代表永不斷線);timeAlive只與時間差比較、不交給原生計時器,故不設2147483647之計時器上限

timeDetect Integer <optional>
50

輸入偵測佇列間隔時間正整數(1至2147483647,數字字串亦可),單位為毫秒ms,預設為50;非預期(0、負數、小數、Infinity、超過2147483647、'0x10'等)視為未給而改用預設50,不報錯、不夾至上限

debug Boolean <optional>
false

輸入是否於opt.timeAlive或opt.timeDetect為非預期之輸入時輸出警告布林值,須為true才生效,警告為固定詞彙(不含輸入值),同一參數同一行程只警告一次,預設false

funLog function <optional>
null

輸入警告輸出函數,格式為(msg, { fn, reason, key })=>{},未給則用console.warn,預設null

onTrace function <optional>
null

輸入觀察回調函數,於內部事件發生當下同步呼叫,傳入一個凍結之事件物件{ type, ... },供測試以事件(而非等待時間)同步與診斷;type為'enter'或'leave'時為即將發出該message事件(含key、now同事件內容),'tick'時為每次偵測佇列(含size為偵測前之單元數),'stop'時為佇列已空而停止偵測;回調不帶接收者呼叫,其拋錯與回傳值皆忽略,不影響偵測,clear後不再呼叫,預設null

Returns:

回傳事件物件,可呼叫函數on、trigger、get、clear。trigger給予單元的唯一key字串與攜帶數據data物件,on為監聽事件,需自行監聽message事件取得單元進出事件。get事件可取得alive內視為存活的單元清單(含剛trigger而尚未發出enter者)。clear為釋放:立即清除偵測計時器、取消尚未發出之enter、清空佇列,本身不發事件,其後不再發出任何事件、trigger無效、get回傳[],可重複呼叫(釋放為終態,需重新偵測者另建alive);clear回傳已發出enter且尚未leave之單元陣列[{ key, data }],供使用端補發離線通知,再次呼叫回傳[];監聽器於派發中呼叫clear亦安全,同一輪尚未處理之單元不再派發。事件物件為原生EventEmitter(eventemitter3)。本模組於派發處以try攔截監聽器之同步拋錯,故其不會使行程崩潰,會改以error事件回報{ fun: 'listener', name, msg, args },無error監聽者則console.error;惟依EventEmitter規範,同一次派發中先拋錯之監聽器會中止該次派發,其後之監聽器不再被呼叫。async監聽器之reject不被攔截(規範上emit不觀察監聽器回傳值),須由監聽器自行處理,否則為unhandledRejection

Type
Object

(static) arr2dt(keys, valuesopt, optopt) → {Object}

Description:
  • 結合keys與values成為物件

    keys之元素為空字串''、null、undefined、空洞、物件、陣列(及函數、Symbol)時,該欄位名連同其對應之值略過,其餘配對位置不變;有限數字視同字串;keys重複時後者覆蓋前者

    Unit Test: Github

Source:
Example
console.log(arr2dt(['a', 'b']))
// => { 'a': '', 'b': '' }

console.log(arr2dt(['a', 'b'], 'xyz'))
// => { a: 'xyz', b: 'xyz' }

console.log(arr2dt(['a', 'b'], null))
// => { a: null, b: null }

console.log(arr2dt(['a', 'b'], [12.3, '456a']))
// => { 'a': 12.3, 'b': '456a' }

console.log(arr2dt(['a', 'b'], [null, '456a']))
// => { 'a': null, 'b': '456a' }

console.log(arr2dt(['a', 'b'], [12.3]))
// => {} (長度不同)

console.log(arr2dt(['a', 'b'], {}))
// => { a: {}, b: {} }

console.log(arr2dt(['a'], ['']))
// => { a: '' } (陣列一律當作值陣列)

console.log(arr2dt(['a', '', 'c'], [1, 2, 3]))
// => { a: 1, c: 3 } (略過空字串欄位名及其值)

console.log(arr2dt(['a', 'a'], [1, 2]))
// => { a: 2 } (重複時後者覆蓋前者)

console.log(arr2dt(['a'], function() {}))
// => { a: null } (函數視為null)

console.log(arr2dt(['a', 'b'], [function() {}, 2]))
// => { a: null, b: 2 } (值陣列之元素為函數時視為null)
Parameters:
Name Type Attributes Default Description
keys Array

輸入keys字串陣列,非陣列或空陣列回傳空物件{}

values Array | * <optional>
''

輸入values陣列或需自動展開values成為的陣列,預設'';values為陣列(含['']、[null]、[{}]、[])時一律當作值陣列與keys逐一配對,長度不同時回傳空物件{},值陣列之元素為函數時該欄位視為null(不執行、不複製),其餘元素原樣(物件不複製,與輸入共用);values非陣列時各欄位皆填入values,values為物件(typeof為object且非null)時各欄位各一份以lodash cloneDeep產生之複本(無原型物件之複本為一般物件,同修前),values為函數時視為null(不執行、不複製)

opt Object <optional>
{}

輸入設定物件,預設{}

Properties
Name Type Attributes Default Description
debug Boolean <optional>
false

輸入是否輸出除錯警告布林值,非布林視為false;為true且values為陣列而長度與keys不同時,經opt.funLog(函數)或console.warn提示兩者之長度(不含值;同原因每個行程只提示一次),預設false

funLog function <optional>
null

輸入警告之出口函數,以(msg, info)呼叫,未給則用console.warn,預設null

Returns:

回傳組合後物件

Type
Object

(static) arrAccum(vec, optopt) → {Array}

Description:
  • 回傳累加後陣列

    各元素以isenum判定是否為有效數字(有限數字,或去頭尾空白後為十進位寫法之數字字串),有效者取其數值參與累加; 凡非有效數字(含標記字串'-'、'NP'、''、null、undefined、布林、NaN、Infinity、'Infinity'、'0x10'、'1e400'、包裝物件等),一律以基準值opt.base(預設0)代入累加,輸出與輸入逐筆對應,不報錯、不略過、不改成空字串。 空陣列為合法資料:輸入空陣列時空進空出,回傳空陣列,不報錯(如arrAccum([])回傳[])。 有元素的輸入陣列至少要有1個有效數字,否則throw Error('invalid vec: must contain a valid number'),訊息不帶輸入值。 輸入不是陣列時回傳空陣列(容器之處置不變,先於有效數字之檢查)。

    Unit Test: Github

Source:
Example
console.log(arrAccum([1, 2, 3, 4]))
// => [1, 3, 6, 10]

console.log(arrAccum([1, '2', '-', 3]))
// => [1, 3, 3, 6] (非有效數字以基準值0代入)

console.log(arrAccum([1, '2', '-', 3], { base: 10 }))
// => [1, 3, 13, 16] (非有效數字以基準值10代入)

console.log(arrAccum([]))
// => [] (空陣列為合法資料,空進空出)
Parameters:
Name Type Attributes Description
vec Array

輸入要被累加計算的陣列,元素為有效數字(數字或數字字串,定義見isenum)者取其數值,非有效數字者以opt.base代入;空陣列則回傳空陣列,否則至少1個有效數字,否則throw

opt Object <optional>

輸入設定物件,預設未給

Properties
Name Type Attributes Default Description
base Number | String <optional>
0

輸入非有效數字元素代入之基準值,需為有效數字(數字或數字字串,定義見isenum),非預期之輸入(非有效數字、Infinity、'0x10'、包裝物件等)視為未給而改用預設,不報錯,預設0

debug Boolean <optional>
false

輸入是否於opt.base為非預期之輸入而改用預設時輸出警告布林值,非布林視為false,警告為固定詞彙(不含傳入之值),同一參數每個行程只警告一次,預設false

funLog function <optional>
null

輸入警告出口函數,以(msg, { fn, reason, key })呼叫,未給則用console.warn,預設null

Returns:

回傳各元素累加後之陣列,輸入空陣列或非陣列時回傳空陣列

Type
Array

(static) arrAdd(…arguments, optopt) → {Array}

Description:
  • 各陣列內元素相加,可輸入n個同長度陣列,若需輸入之陣列長度不同則回傳空陣列

    各元素以isenum判定是否為有效數字(有限數字,或去頭尾空白後為十進位寫法之數字字串),有效者取其數值參與相加; 凡非有效數字(含標記字串'-'、'NP'、''、null、undefined、布林、NaN、Infinity、'Infinity'、'0x10'、'1e400'、包裝物件等),一律以基準值opt.base(預設0)代入計算,不報錯、不略過; 同位置元素皆非有效數字者,該位置結果為2倍opt.base(預設即0)。 空陣列為合法資料:所有輸入陣列皆為空陣列時空進空出,回傳空陣列,不報錯(如arrAdd([], [])回傳[])。 有元素的陣列各自至少要有1個有效數字,否則throw Error('invalid arrs[索引]: must contain a valid number'),訊息不帶輸入值。 陣列容器之處置不變:陣列參數少於2個、非陣列、長度不同(含一個為空陣列、另一個非空,如arrAdd([1], [])),回傳空陣列(先於有效數字之檢查)。 本函數為不定參數,最後一個參數若為一般物件(非陣列)則視為opt;最後一個參數若為undefined或null則視為未給opt(不當成陣列參數),如arrAdd(a, b, undefined)等同arrAdd(a, b)。

    Unit Test: Github

Source:
Example
let v1 = [1, 2, 3, 4]
let v2 = [0.1, 0.1, 0.1, 0.1]
let v3 = [11, 22, 33, 44]

console.log(arrAdd(v1, v2))
// => [ 1.1, 2.1, 3.1, 4.1 ]

console.log(arrAdd(v1, v2, v3))
// => [ 12.1, 24.1, 36.1, 48.1 ]

console.log(arrAdd([1, '2', ' 3 ', 4], [10, '-', null, Infinity]))
// => [ 11, 2, 3, 4 ] (非有效數字以基準值0代入)

console.log(arrAdd([1, '-'], [10, 20], { base: 5 }))
// => [ 11, 25 ] (非有效數字以基準值5代入)

console.log(arrAdd(['-', 'NP'], [1, 2]))
// => [ 1, 2 ]

console.log(arrAdd([], []))
// => [] (空陣列為合法資料,空進空出)

console.log(arrAdd([1], []))
// => [] (長度不同)

try {
    arrAdd(['-', 'NP'], [1, 2], [3, 4])
}
catch (err) {
    console.log(err.message)
}
// => invalid arrs[0]: must contain a valid number
Parameters:
Name Type Attributes Description
arguments Array <repeatable>

輸入n個陣列,需同長度,各陣列針對各位置元素進行相加總;元素為有效數字(數字或數字字串,定義見isenum)者取其數值,非有效數字者以opt.base代入;皆為空陣列則回傳空陣列,否則每個陣列各自至少1個有效數字,否則throw

opt Object <optional>

輸入最後一個參數為一般物件時視為設定物件,預設未給

Properties
Name Type Attributes Default Description
base Number | String <optional>
0

輸入非有效數字元素代入之基準值,需為有效數字(數字或數字字串,定義見isenum),非預期之輸入(非有效數字、Infinity、'0x10'、包裝物件等)視為未給而改用預設,不報錯,預設0

debug Boolean <optional>
false

輸入是否於opt.base為非預期之輸入而改用預設時輸出警告布林值,非布林視為false,警告為固定詞彙(不含傳入之值),同一參數每個行程只警告一次,預設false

funLog function <optional>
null

輸入警告出口函數,以(msg, { fn, reason, key })呼叫,未給則用console.warn,預設null

Returns:

回傳各元素相加後陣列,所有輸入陣列皆為空陣列時回傳空陣列,容器無法運算(陣列少於2個、非陣列、長度不同)時亦回傳空陣列

Type
Array

(static) arrAt(vall, istart, iendopt) → {Array}

Description:
  • 由vall陣列提取指定欄位(或欄位範圍)之資料 若istart與iend有效, 提取istart~iend欄位 若僅istart有效, 提取istart欄位

    vall非陣列(含類陣列物件)回傳[];陣列只有一個空元素(['']、[null]、[{}]、[[]])時照常取得該元素 istart為必須參數,須為有效整數(iseint,數字字串亦可,去頭尾空白後取值)且為索引(0~4294967294),無效回傳[];istart超出vall長度時回傳[] iend為opt類參數(預設null),須為有效整數且為索引,非預期之輸入(負數、小數、Infinity、'0x2'、非數字字串、包裝物件等)與小於istart者皆視為未給而只提取istart一筆,不報錯;iend超出vall長度時截至最後一個元素 空位取得undefined;元素不深拷貝

    Unit Test: Github

Source:
Example
console.log(arrAt([1, 2, 3, '4', 5, 'abc'], 1))
// => [ 2 ]

console.log(arrAt([1, 2, 3, '4', 5, 'abc'], 1, 4))
// => [ 2, 3, '4', 5 ]

console.log(arrAt([1, 2, 3, '4', 5, 'abc'], '1', '2'))
// => [ 2, 3 ]

console.log(arrAt([1, 2, 3, '4', 5, 'abc'], 1, Infinity))
// => [ 2 ]

console.log(arrAt([1, 2, 3, '4', 5, 'abc'], 3, 1))
// => [ '4' ] (iend小於istart視為未給)

console.log(arrAt([1, 2, 3, '4', 5, 'abc'], 4, 10))
// => [ 5, 'abc' ] (iend超出長度截至最後一個元素)

console.log(arrAt([null], 0))
// => [ null ]
Parameters:
Name Type Attributes Default Description
vall Array

輸入要被提取的任意資料陣列

istart Integer | String

輸入起始的欄位指標整數,必須參數(有效整數,0~4294967294,數字字串亦可),無效回傳[]

iend Integer | String <optional>
null

輸入結束的欄位指標整數,opt類參數(有效整數,0~4294967294,數字字串亦可),若不使用、非預期之輸入或小於istart則視為未給,等同於istart,超出長度則截至最後一個元素,預設null

Returns:

回傳提取的任意資料陣列

Type
Array

(static) arrDiff(arrOld, arrNew, optopt) → {Object}

Description:
  • 比對新舊陣列差異處

    arrOld為第1參數:非陣列(含未給、null、字串、物件等)回傳同形之空結果{ diff: [], dfs: [] },不拋錯(輸入參數檢測機制C7,第1參數型別不對回輸出型別之空結果),此時不檢查arrNew與opt。arrOld為陣列時arrNew為必須參數,須為陣列,非陣列throw Error('invalid arrNew: must be an array'),訊息不帶輸入值;空陣列為合法輸入,只有一邊為空者照常回傳差異結果,兩邊皆為空陣列時回傳{ diff: [], dfs: [] }(與正常輸出同形,無差異);opt內無效的鍵一律改用預設;opt.mode為'matrix'時各元素須為陣列,否則throw Error("invalid arrOld[i]: must be an array when opt.mode is 'matrix'")或Error("invalid arrNew[i]: must be an array when opt.mode is 'matrix'")(i為第一個非陣列元素之實際索引,arrOld整側先於arrNew整側),訊息不帶輸入值,亦不輸出輸入資料至console 以diff套件之diffArrays逐元素(一維)、逐列再逐格(矩陣)比對,不先把陣列串成文字,故值內含換行或任何字元皆不影響對齊;連續刪除與其後之新增依序配對為modify;矩陣模式之列以其各儲存格文字全同為同一列,modify之列再逐格比對(同一欄位且同一文字為同一格) 以元素(儲存格)之文字比對、不比型別(1與'1'、true與'true'、null與'null'視為相同):字串與有限數字為原文,布林為'true'或'false',null為'null',undefined與空位為'',NaN與±Infinity為字串'NaN'、'Infinity'、'-Infinity',物件與陣列為鍵排序後之JSON(鍵之順序不同視為相同),Date為ISO字串,函數視為null即'null',BigInt為String(v);dfs之vo、vn為此文字

    Unit Test: Github

Source:
Example
let r
let arrOld
let arrNew

if (true) {
    r = arrDiff([], [])
    console.log(r)
    // => { diff: [], dfs: [] }
}

if (true) {
    r = arrDiff('x', [])
    console.log(r)
    // => { diff: [], dfs: [] } (arrOld非陣列回傳空結果, 不拋錯)

    try {
        arrDiff([], null)
    }
    catch (err) {
        console.log(err.message)
    }
    // => invalid arrNew: must be an array

    try {
        arrDiff([1], [2], { mode: 'matrix' })
    }
    catch (err) {
        console.log(err.message)
    }
    // => invalid arrOld[0]: must be an array when opt.mode is 'matrix'
}

if (true) {
    arrOld = [-0.529408622, 0.839882385, 0.663059856, 0.49047221, 123, 0.395763265, 0.866151835]
    arrNew = [-0.529408622, 0.1839882385, 0.663059856, 0.49047221, 0.395763265, 45.6, 0.866151835]
    r = arrDiff(arrOld, arrNew) //因第[5](0.395763265)元素會往前到[4]去, diff會偵測到並視為前面刪除(123)而後面加入(45.6), 故解析後長度會由7變成8
    console.dir(r, { depth: null })
    // => {
    //   diff: [
    //     {
    //       count: 1,
    //       added: false,
    //       removed: false,
    //       value: [ '-0.529408622' ]
    //     },
    //     { count: 1, added: false, removed: true, value: [ '0.839882385' ] },
    //     {
    //       count: 1,
    //       added: true,
    //       removed: false,
    //       value: [ '0.1839882385' ]
    //     },
    //     {
    //       count: 2,
    //       added: false,
    //       removed: false,
    //       value: [ '0.663059856', '0.49047221' ]
    //     },
    //     { count: 1, added: false, removed: true, value: [ '123' ] },
    //     {
    //       count: 1,
    //       added: false,
    //       removed: false,
    //       value: [ '0.395763265' ]
    //     },
    //     { count: 1, added: true, removed: false, value: [ '45.6' ] },
    //     {
    //       count: 1,
    //       added: false,
    //       removed: false,
    //       value: [ '0.866151835' ]
    //     }
    //   ],
    //   dfs: [
    //     { p: '', k: 0, vo: '-0.529408622', vn: '' },
    //     { p: 'modify', k: 1, vo: '0.839882385', vn: '0.1839882385' },
    //     { p: '', k: 2, vo: '0.663059856', vn: '' },
    //     { p: '', k: 3, vo: '0.49047221', vn: '' },
    //     { p: 'remove', k: 4, vo: '123', vn: '' },
    //     { p: '', k: 5, vo: '0.395763265', vn: '' },
    //     { p: 'add', k: 6, vo: '45.6', vn: '' },
    //     { p: '', k: 7, vo: '0.866151835', vn: '' }
    //   ]
    // }
}

if (true) {
    arrOld = [
        [1, 0.974848293, 0.791303871, 0.716898185, 0.506002098, 0.137888903, 0.626724085],
        [2, -0.529408622, 0.839882385, 0.663059856, 0.49047221, 123, 0.395763265, 0.866151835],
        [3, -0.10320217, 0.475514539, 0.969205779, 0.711250309, 0.153847069, 0.410092395],
        [4, -0.121479865, 0.486179086, 0.481023842, 0.467410582, 0.42602231, 0.849701641],
        [5, 0.757346003, 0.697242433, 0.67532802, 0.174644416, 0.045652267, 0.397104668],
        [6, 0.663032731, 0.259252779, 0.566177431, 0.679637706, 0.377814487, 0.400248119],
        [7, 0.72721374, 0.263793391, 0.167895215, 0.794808602, 0.107070584, 0.011822872],
        [8, 0.247416664, 0.360426795, 0.014346373, 0.000469616, 0.4082693, 0.913806611],
        [9, 0.345880037, 0.167996664, 0.711054429, 0.363177921, 0.206849994, 0.636855344],
        [10, 0.576739457, 0.324665077, 0.973218005, 0.883927423, 0.176906125, 0.20087887],
        [11, 1.2],
        [12, 23.5],
        [13, 0.504421248, 0.984003751, 0.32549507, 0.987090751, 0.192745589, 0.735133561],
        [14, 0.273214614, 0.083431884, 0.565146092, 0.935388666, 0.637675154, 0.523815661],
    ]
    arrNew = [
        [1, 0.974848293, 0.791303871, 0.716898185, 0.506002098, 0.137888903, 0.626724085],
        [2, -0.529408622, 0.1839882385, 0.663059856, 0.49047221, 0.395763265, 45.6, 0.866151835],
        [3, -0.10320217, 0.475514539, 0.969205779, 0.711250309, 0.153847069, 0.410092395],
        [4, -0.121479865, 0.486179086, 0.481023842, 0.467410582, 0.42602231, 0.849701641],
        [5, 0.757346003, 0.697242433, 0.67532802, 0.174644416, 0.045652267, 0.397104668],
        [7, 0.72721374, 0.263793391, 0.167895215, 0.794808602, 0.107070584, 0.011822872],
        [8, 0.247416664, 0.360426795, 0.014346373, 0.000469616, 0.4082693, 0.913806611],
        [9, 0.345880037, 0.167996664, 0.711054429, 0.363173478, 0.636855344],
        [10, 0.576739457, 0.324665077, 0.973218005, 0.883927423, 0.176906125, 0.20087887],
        [13, 0.504421248, 0.984003751, 0.32549507, 0.987090751, 0.192745589, 0.735133561],
        [14, 0.273214614, 0.083431884, 0.565146092, 0.935388666, 0.637675154, 0.523815661],
        ['n1', 0.944492151, 0.89950443, 0.182709318, 0.892820757, 0.709746901, 0.097385354],
        ['n2', 0.769805921, 0.061355308, 0.314826137, 0.855857651, 0.653550539, 0.772500773],
        ['n3', 0.158739038, 0.085078711, 0.844664253, 0.21630142, 0.912931341, 0.735138313],
    ]
    r = arrDiff(arrOld, arrNew, { mode: 'matrix' })
    console.dir(r.diff, { depth: null })
    // => [
    //   {
    //     count: 1,
    //     added: false,
    //     removed: false,
    //     value: [
    //       [
    //         '1',
    //         '0.974848293',
    //         '0.791303871',
    //         '0.716898185',
    //         '0.506002098',
    //         '0.137888903',
    //         '0.626724085'
    //       ]
    //     ]
    //   },
    //   {
    //     count: 1,
    //     added: false,
    //     removed: true,
    //     value: [
    //       [
    //         '2',
    //         '-0.529408622',
    //         '0.839882385',
    //         '0.663059856',
    //         '0.49047221',
    //         '123',
    //         '0.395763265',
    //         '0.866151835'
    //       ]
    //     ]
    //   },
    //   {
    //     count: 1,
    //     added: true,
    //     removed: false,
    //     value: [
    //       [
    //         '2',
    //         '-0.529408622',
    //         '0.1839882385',
    //         '0.663059856',
    //         '0.49047221',
    //         '0.395763265',
    //         '45.6',
    //         '0.866151835'
    //       ]
    //     ]
    //   },
    //   {
    //     count: 3,
    //     added: false,
    //     removed: false,
    //     value: [
    //       [
    //         '3',
    //         '-0.10320217',
    //         '0.475514539',
    //         '0.969205779',
    //         '0.711250309',
    //         '0.153847069',
    //         '0.410092395'
    //       ],
    //       [
    //         '4',
    //         '-0.121479865',
    //         '0.486179086',
    //         '0.481023842',
    //         '0.467410582',
    //         '0.42602231',
    //         '0.849701641'
    //       ],
    //       [
    //         '5',
    //         '0.757346003',
    //         '0.697242433',
    //         '0.67532802',
    //         '0.174644416',
    //         '0.045652267',
    //         '0.397104668'
    //       ]
    //     ]
    //   },
    //   {
    //     count: 1,
    //     added: false,
    //     removed: true,
    //     value: [
    //       [
    //         '6',
    //         '0.663032731',
    //         '0.259252779',
    //         '0.566177431',
    //         '0.679637706',
    //         '0.377814487',
    //         '0.400248119'
    //       ]
    //     ]
    //   },
    //   {
    //     count: 2,
    //     added: false,
    //     removed: false,
    //     value: [
    //       [
    //         '7',
    //         '0.72721374',
    //         '0.263793391',
    //         '0.167895215',
    //         '0.794808602',
    //         '0.107070584',
    //         '0.011822872'
    //       ],
    //       [
    //         '8',
    //         '0.247416664',
    //         '0.360426795',
    //         '0.014346373',
    //         '0.000469616',
    //         '0.4082693',
    //         '0.913806611'
    //       ]
    //     ]
    //   },
    //   {
    //     count: 1,
    //     added: false,
    //     removed: true,
    //     value: [
    //       [
    //         '9',
    //         '0.345880037',
    //         '0.167996664',
    //         '0.711054429',
    //         '0.363177921',
    //         '0.206849994',
    //         '0.636855344'
    //       ]
    //     ]
    //   },
    //   {
    //     count: 1,
    //     added: true,
    //     removed: false,
    //     value: [
    //       [
    //         '9',
    //         '0.345880037',
    //         '0.167996664',
    //         '0.711054429',
    //         '0.363173478',
    //         '0.636855344'
    //       ]
    //     ]
    //   },
    //   {
    //     count: 1,
    //     added: false,
    //     removed: false,
    //     value: [
    //       [
    //         '10',
    //         '0.576739457',
    //         '0.324665077',
    //         '0.973218005',
    //         '0.883927423',
    //         '0.176906125',
    //         '0.20087887'
    //       ]
    //     ]
    //   },
    //   {
    //     count: 2,
    //     added: false,
    //     removed: true,
    //     value: [ [ '11', '1.2' ], [ '12', '23.5' ] ]
    //   },
    //   {
    //     count: 2,
    //     added: false,
    //     removed: false,
    //     value: [
    //       [
    //         '13',
    //         '0.504421248',
    //         '0.984003751',
    //         '0.32549507',
    //         '0.987090751',
    //         '0.192745589',
    //         '0.735133561'
    //       ],
    //       [
    //         '14',
    //         '0.273214614',
    //         '0.083431884',
    //         '0.565146092',
    //         '0.935388666',
    //         '0.637675154',
    //         '0.523815661'
    //       ]
    //     ]
    //   },
    //   {
    //     count: 3,
    //     added: true,
    //     removed: false,
    //     value: [
    //       [
    //         'n1',
    //         '0.944492151',
    //         '0.89950443',
    //         '0.182709318',
    //         '0.892820757',
    //         '0.709746901',
    //         '0.097385354'
    //       ],
    //       [
    //         'n2',
    //         '0.769805921',
    //         '0.061355308',
    //         '0.314826137',
    //         '0.855857651',
    //         '0.653550539',
    //         '0.772500773'
    //       ],
    //       [
    //         'n3',
    //         '0.158739038',
    //         '0.085078711',
    //         '0.844664253',
    //         '0.21630142',
    //         '0.912931341',
    //         '0.735138313'
    //       ]
    //     ]
    //   }
    // ]
    for (let i = 0; i < r.dfs.length; i++) {
        let df = r.dfs[i]
        console.log(i, 'df', df)
    }
    // => 0 df [
    //   { p: '', k: 0, vo: '1', vn: '' },
    //   { p: '', k: 1, vo: '0.974848293', vn: '' },
    //   { p: '', k: 2, vo: '0.791303871', vn: '' },
    //   { p: '', k: 3, vo: '0.716898185', vn: '' },
    //   { p: '', k: 4, vo: '0.506002098', vn: '' },
    //   { p: '', k: 5, vo: '0.137888903', vn: '' },
    //   { p: '', k: 6, vo: '0.626724085', vn: '' }
    // ]
    // 1 df [
    //   { p: '', k: 0, vo: '2', vn: '' },
    //   { p: '', k: 1, vo: '-0.529408622', vn: '' },
    //   { p: 'modify', k: 2, vo: '0.839882385', vn: '0.1839882385' },
    //   { p: '', k: 3, vo: '0.663059856', vn: '' },
    //   { p: '', k: 4, vo: '0.49047221', vn: '' },
    //   { p: 'modify', k: 5, vo: '123', vn: '0.395763265' },
    //   { p: 'modify', k: 6, vo: '0.395763265', vn: '45.6' },
    //   { p: '', k: 7, vo: '0.866151835', vn: '' }
    // ]
    // 2 df [
    //   { p: '', k: 0, vo: '3', vn: '' },
    //   { p: '', k: 1, vo: '-0.10320217', vn: '' },
    //   { p: '', k: 2, vo: '0.475514539', vn: '' },
    //   { p: '', k: 3, vo: '0.969205779', vn: '' },
    //   { p: '', k: 4, vo: '0.711250309', vn: '' },
    //   { p: '', k: 5, vo: '0.153847069', vn: '' },
    //   { p: '', k: 6, vo: '0.410092395', vn: '' }
    // ]
    // 3 df [
    //   { p: '', k: 0, vo: '4', vn: '' },
    //   { p: '', k: 1, vo: '-0.121479865', vn: '' },
    //   { p: '', k: 2, vo: '0.486179086', vn: '' },
    //   { p: '', k: 3, vo: '0.481023842', vn: '' },
    //   { p: '', k: 4, vo: '0.467410582', vn: '' },
    //   { p: '', k: 5, vo: '0.42602231', vn: '' },
    //   { p: '', k: 6, vo: '0.849701641', vn: '' }
    // ]
    // 4 df [
    //   { p: '', k: 0, vo: '5', vn: '' },
    //   { p: '', k: 1, vo: '0.757346003', vn: '' },
    //   { p: '', k: 2, vo: '0.697242433', vn: '' },
    //   { p: '', k: 3, vo: '0.67532802', vn: '' },
    //   { p: '', k: 4, vo: '0.174644416', vn: '' },
    //   { p: '', k: 5, vo: '0.045652267', vn: '' },
    //   { p: '', k: 6, vo: '0.397104668', vn: '' }
    // ]
    // 5 df [
    //   { p: 'remove', k: 0, vo: '6', vn: '' },
    //   { p: 'remove', k: 1, vo: '0.663032731', vn: '' },
    //   { p: 'remove', k: 2, vo: '0.259252779', vn: '' },
    //   { p: 'remove', k: 3, vo: '0.566177431', vn: '' },
    //   { p: 'remove', k: 4, vo: '0.679637706', vn: '' },
    //   { p: 'remove', k: 5, vo: '0.377814487', vn: '' },
    //   { p: 'remove', k: 6, vo: '0.400248119', vn: '' }
    // ]
    // 6 df [
    //   { p: '', k: 0, vo: '7', vn: '' },
    //   { p: '', k: 1, vo: '0.72721374', vn: '' },
    //   { p: '', k: 2, vo: '0.263793391', vn: '' },
    //   { p: '', k: 3, vo: '0.167895215', vn: '' },
    //   { p: '', k: 4, vo: '0.794808602', vn: '' },
    //   { p: '', k: 5, vo: '0.107070584', vn: '' },
    //   { p: '', k: 6, vo: '0.011822872', vn: '' }
    // ]
    // 7 df [
    //   { p: '', k: 0, vo: '8', vn: '' },
    //   { p: '', k: 1, vo: '0.247416664', vn: '' },
    //   { p: '', k: 2, vo: '0.360426795', vn: '' },
    //   { p: '', k: 3, vo: '0.014346373', vn: '' },
    //   { p: '', k: 4, vo: '0.000469616', vn: '' },
    //   { p: '', k: 5, vo: '0.4082693', vn: '' },
    //   { p: '', k: 6, vo: '0.913806611', vn: '' }
    // ]
    // 8 df [
    //   { p: '', k: 0, vo: '9', vn: '' },
    //   { p: '', k: 1, vo: '0.345880037', vn: '' },
    //   { p: '', k: 2, vo: '0.167996664', vn: '' },
    //   { p: '', k: 3, vo: '0.711054429', vn: '' },
    //   { p: 'modify', k: 4, vo: '0.363177921', vn: '0.363173478' },
    //   { p: 'modify', k: 5, vo: '0.206849994', vn: '0.636855344' },
    //   { p: 'remove', k: 6, vo: '0.636855344', vn: '' }
    // ]
    // 9 df [
    //   { p: '', k: 0, vo: '10', vn: '' },
    //   { p: '', k: 1, vo: '0.576739457', vn: '' },
    //   { p: '', k: 2, vo: '0.324665077', vn: '' },
    //   { p: '', k: 3, vo: '0.973218005', vn: '' },
    //   { p: '', k: 4, vo: '0.883927423', vn: '' },
    //   { p: '', k: 5, vo: '0.176906125', vn: '' },
    //   { p: '', k: 6, vo: '0.20087887', vn: '' }
    // ]
    // 10 df [
    //   { p: 'remove', k: 0, vo: '11', vn: '' },
    //   { p: 'remove', k: 1, vo: '1.2', vn: '' }
    // ]
    // 11 df [
    //   { p: 'remove', k: 0, vo: '12', vn: '' },
    //   { p: 'remove', k: 1, vo: '23.5', vn: '' }
    // ]
    // 12 df [
    //   { p: '', k: 0, vo: '13', vn: '' },
    //   { p: '', k: 1, vo: '0.504421248', vn: '' },
    //   { p: '', k: 2, vo: '0.984003751', vn: '' },
    //   { p: '', k: 3, vo: '0.32549507', vn: '' },
    //   { p: '', k: 4, vo: '0.987090751', vn: '' },
    //   { p: '', k: 5, vo: '0.192745589', vn: '' },
    //   { p: '', k: 6, vo: '0.735133561', vn: '' }
    // ]
    // 13 df [
    //   { p: '', k: 0, vo: '14', vn: '' },
    //   { p: '', k: 1, vo: '0.273214614', vn: '' },
    //   { p: '', k: 2, vo: '0.083431884', vn: '' },
    //   { p: '', k: 3, vo: '0.565146092', vn: '' },
    //   { p: '', k: 4, vo: '0.935388666', vn: '' },
    //   { p: '', k: 5, vo: '0.637675154', vn: '' },
    //   { p: '', k: 6, vo: '0.523815661', vn: '' }
    // ]
    // 14 df [
    //   { p: 'add', k: 0, vo: 'n1', vn: '' },
    //   { p: 'add', k: 1, vo: '0.944492151', vn: '' },
    //   { p: 'add', k: 2, vo: '0.89950443', vn: '' },
    //   { p: 'add', k: 3, vo: '0.182709318', vn: '' },
    //   { p: 'add', k: 4, vo: '0.892820757', vn: '' },
    //   { p: 'add', k: 5, vo: '0.709746901', vn: '' },
    //   { p: 'add', k: 6, vo: '0.097385354', vn: '' }
    // ]
    // 15 df [
    //   { p: 'add', k: 0, vo: 'n2', vn: '' },
    //   { p: 'add', k: 1, vo: '0.769805921', vn: '' },
    //   { p: 'add', k: 2, vo: '0.061355308', vn: '' },
    //   { p: 'add', k: 3, vo: '0.314826137', vn: '' },
    //   { p: 'add', k: 4, vo: '0.855857651', vn: '' },
    //   { p: 'add', k: 5, vo: '0.653550539', vn: '' },
    //   { p: 'add', k: 6, vo: '0.772500773', vn: '' }
    // ]
    // 16 df [
    //   { p: 'add', k: 0, vo: 'n3', vn: '' },
    //   { p: 'add', k: 1, vo: '0.158739038', vn: '' },
    //   { p: 'add', k: 2, vo: '0.085078711', vn: '' },
    //   { p: 'add', k: 3, vo: '0.844664253', vn: '' },
    //   { p: 'add', k: 4, vo: '0.21630142', vn: '' },
    //   { p: 'add', k: 5, vo: '0.912931341', vn: '' },
    //   { p: 'add', k: 6, vo: '0.735138313', vn: '' }
    // ]
}
Parameters:
Name Type Attributes Default Description
arrOld Array

輸入原始數據陣列,非陣列回傳{ diff: [], dfs: [] },[]為合法輸入

arrNew Array

輸入更新數據陣列,必須參數,非陣列throw Error,[]為合法輸入;arrOld非陣列時不檢查

opt Object <optional>
{}

輸入設定物件,預設{}

Properties
Name Type Attributes Default Description
mode String <optional>
'array'

輸入數據維度字串,可選為'array'與'matrix',預設'array'

Throws:

arrOld為陣列而arrNew非陣列時throw Error('invalid arrNew: must be an array');opt.mode為'matrix'且有元素非陣列時throw Error("invalid arrOld[i]: must be an array when opt.mode is 'matrix'")或Error("invalid arrNew[i]: must be an array when opt.mode is 'matrix'"),i為第一個非陣列元素之實際索引;訊息皆不帶輸入值

Type
Error
Returns:

回傳比對結果物件{ diff, dfs }:diff為底層比對結果陣列(各段為{ count, added, removed, value },value為該段之元素陣列,一維為各元素之比對文字,矩陣為各列之儲存格比對文字陣列);dfs於一維為各元素之比對結果陣列[{ p, k, vo, vn }],於矩陣為各列之各儲存格比對結果陣列,p為''(不變)、'remove'、'add'或'modify';arrOld與arrNew皆為[]時回傳{ diff: [], dfs: [] }

Type
Object

(static) arrFilterByENum(arr) → {Array}

Description:
  • 過濾陣列內元素僅保留有效數字,並且自動轉數值

    判定用isenum(有效數字: 有限數字,或去頭尾空白後為十進位寫法之數字字串,可帶科學記號),取值為去頭尾空白後Number(…),其後只用轉換值。 與arrFilterByNum(基於isnum)之差異: Infinity、-Infinity、'Infinity'、'0x10'、'0b11'、'1e400'、'1e-400'(下溢)、包裝物件(new Number(1))、 空字串與純空白字串、'-'、'NP'等標記字串、null、undefined、NaN、布林、BigInt、物件、陣列等皆不保留。 與arrFilterByPnum(基於ispnum,僅保留正數)之差異: 不限正數,負數與0亦保留。 arr須為陣列,非陣列(含未給、null、字串、物件等)回傳空陣列[],不拋錯(輸入參數檢測機制C7,第1參數型別不對回輸出型別之空結果);空陣列為合法資料,回傳空陣列[],亦不因無有效數字而報錯;元素順序與重複皆保留;不改動輸入陣列。

    Unit Test: Github

Source:
Example
let arr

arr = ['abc', '-2.2', '-1.1', -1.1, -1, -0.5, 0, '0', 0.5, 1, 1.1, '1.1', '2.2', 'xyz']
console.log(arrFilterByENum(arr))
// => [ -2.2, -1.1, -1.1, -1, -0.5, 0, 0, 0.5, 1, 1.1, 1.1, 2.2 ]

arr = [' 12 ', '1.2e-5', '-', 'NP', '', Infinity, '0x10', null, true, new Number(3), 5]
console.log(arrFilterByENum(arr))
// => [ 12, 0.000012, 5 ]

console.log(arrFilterByENum([]))
// => []

console.log(arrFilterByENum('abc'))
// => [] (非陣列回傳空結果, 不拋錯)
Parameters:
Name Type Description
arr Array

輸入原始陣列,須為陣列(空陣列合法,回傳[]),非陣列回傳[]

Returns:

回傳新陣列,元素皆為Number;無有效數字(含空陣列)或arr非陣列時為空陣列[]

Type
Array

(static) arrFilterByKeywords(arr, keywords) → {Array}

Description:
  • 對arr陣列內各字串進行關鍵字計算,計算是否含有關鍵字與程度,多關鍵字用空白區隔,必要關鍵字可於字首添加「+」,不要關鍵字可於字首添加「-」

    規則(使用者2026-11-14裁定): 結果筆數恆等於arr之長度(只有arr非陣列或為空陣列[]時回傳[]);arr之元素非字串(空位、null、undefined、數字、NaN、布林、函數、Symbol、物件、陣列等)者該筆為{ hasKeyword: false, weight: 0 },String包裝物件亦非字串而同為{ hasKeyword: false, weight: 0 }(判斷函數只收原始值,修前視同字串); keywords為字串時以半形空白或全形空白(U+3000)分隔出各關鍵字,為陣列時各元素為一個關鍵字(關鍵字內可含空白);陣列內之數字(與布林)以其字串形式當作一般關鍵字比對(不解析+、-前綴),null、undefined、物件、陣列、函數、Symbol等元素略過; 空白關鍵字(含只有+或-之前綴)先剔除,重複之關鍵字去重後再計算;keywords無效(''、null、數字、[]、['']、[null]、[{}]等)或剔除後無任何關鍵字時,回傳與arr同筆數且全為{ hasKeyword: false, weight: 0 }; 不要關鍵字(-x):含任一不要關鍵字者不命中;必要關鍵字(+a):須含全部必要關鍵字才命中;其餘依一般關鍵字判斷: 有一般關鍵字時,權重為所含之一般關鍵字之權重和,第k個(由0起算)一般關鍵字之權重為(1 - k / n) ** 2,n為一般關鍵字數(n、k只計一般關鍵字),有必要關鍵字者含全部必要關鍵字即命中(權重可為0),無必要關鍵字者含任一一般關鍵字才命中; 無一般關鍵字時(只有必要或不要關鍵字),通過上列條件者命中且權重為1; 比對區分大小寫(不分大小寫者由呼叫端先轉換arr與keywords)

    Unit Test: Github

Source:
Example
let arr = [
    'abc def xyz',
    '測試abc中文mnop',
    'Instead of creating yet another opinionated application',
    'Node.js module which can be integrated into a larger application',
]
let kws = null
let r = null

kws = 'abc'
r = arrFilterByKeywords(arr, kws)
console.log(r)
// => [
//     { hasKeyword: true, weight: 1 },
//     { hasKeyword: true, weight: 1 },
//     { hasKeyword: false, weight: 0 },
//     { hasKeyword: false, weight: 0 }
// ]

kws = 'def 中文'
r = arrFilterByKeywords(arr, kws)
console.log(r)
// => [
//     { hasKeyword: true, weight: 1 },
//     { hasKeyword: true, weight: 0.25 },
//     { hasKeyword: false, weight: 0 },
//     { hasKeyword: false, weight: 0 }
// ]

kws = 'def 中文 mnop'
r = arrFilterByKeywords(arr, kws)
console.log(r)
// => [
//     { hasKeyword: true, weight: 1 },
//     { hasKeyword: true, weight: 0.5555555555555557 },
//     { hasKeyword: false, weight: 0 },
//     { hasKeyword: false, weight: 0 }
// ]

kws = 'def +yet' //含必要關鍵字yet者命中, 權重只依一般關鍵字def(不含def得0)
r = arrFilterByKeywords(arr, kws)
console.log(r)
// => [
//     { hasKeyword: false, weight: 0 },
//     { hasKeyword: false, weight: 0 },
//     { hasKeyword: true, weight: 0 },
//     { hasKeyword: false, weight: 0 }
// ]

kws = 'def of module -yet' //含yet者不命中, 其餘依一般關鍵字def、of、module(n為3)判斷
r = arrFilterByKeywords(arr, kws)
console.log(r)
// => [
//     { hasKeyword: true, weight: 1 },
//     { hasKeyword: false, weight: 0 },
//     { hasKeyword: false, weight: 0 },
//     { hasKeyword: true, weight: 0.11111111111111113 }
// ]

kws = '-yet' //只有不要關鍵字時, 不含者命中且權重為1
r = arrFilterByKeywords(arr, kws)
console.log(r)
// => [
//     { hasKeyword: true, weight: 1 },
//     { hasKeyword: true, weight: 1 },
//     { hasKeyword: false, weight: 0 },
//     { hasKeyword: true, weight: 1 }
// ]

kws = '+abc +中文' //須含全部必要關鍵字
r = arrFilterByKeywords(arr, kws)
console.log(r)
// => [
//     { hasKeyword: false, weight: 0 },
//     { hasKeyword: true, weight: 1 },
//     { hasKeyword: false, weight: 0 },
//     { hasKeyword: false, weight: 0 }
// ]

kws = 'abc' + String.fromCharCode(0x3000) + 'def' //全形空白(U+3000)亦為分隔符
r = arrFilterByKeywords(arr, kws)
console.log(r)
// => [
//     { hasKeyword: true, weight: 1.25 },
//     { hasKeyword: true, weight: 1 },
//     { hasKeyword: false, weight: 0 },
//     { hasKeyword: false, weight: 0 }
// ]

kws = 'abc abc' //重複之關鍵字去重
r = arrFilterByKeywords(arr, kws)
console.log(r)
// => [
//     { hasKeyword: true, weight: 1 },
//     { hasKeyword: true, weight: 1 },
//     { hasKeyword: false, weight: 0 },
//     { hasKeyword: false, weight: 0 }
// ]

kws = '+'
r = arrFilterByKeywords(arr, kws)
console.log(r)
// => [
//     { hasKeyword: false, weight: 0 },
//     { hasKeyword: false, weight: 0 },
//     { hasKeyword: false, weight: 0 },
//     { hasKeyword: false, weight: 0 }
// ]

kws = 'def +'
r = arrFilterByKeywords(arr, kws)
console.log(r)
// => [
//     { hasKeyword: true, weight: 1 },
//     { hasKeyword: false, weight: 0 },
//     { hasKeyword: false, weight: 0 },
//     { hasKeyword: false, weight: 0 }
// ]

kws = ['can be', 'def'] //陣列之各元素為一個關鍵字(可含空白)
r = arrFilterByKeywords(arr, kws)
console.log(r)
// => [
//     { hasKeyword: true, weight: 0.25 },
//     { hasKeyword: false, weight: 0 },
//     { hasKeyword: false, weight: 0 },
//     { hasKeyword: true, weight: 1 }
// ]

kws = ['', 'abc'] //空白關鍵字先剔除再計權重
r = arrFilterByKeywords(arr, kws)
console.log(r)
// => [
//     { hasKeyword: true, weight: 1 },
//     { hasKeyword: true, weight: 1 },
//     { hasKeyword: false, weight: 0 },
//     { hasKeyword: false, weight: 0 }
// ]

kws = ['-abc']
r = arrFilterByKeywords(arr, kws)
console.log(r)
// => [
//     { hasKeyword: false, weight: 0 },
//     { hasKeyword: false, weight: 0 },
//     { hasKeyword: true, weight: 1 },
//     { hasKeyword: true, weight: 1 }
// ]

kws = '' //關鍵字無效, 回傳與arr同筆數且全不命中
r = arrFilterByKeywords(arr, kws)
console.log(r)
// => [
//     { hasKeyword: false, weight: 0 },
//     { hasKeyword: false, weight: 0 },
//     { hasKeyword: false, weight: 0 },
//     { hasKeyword: false, weight: 0 }
// ]

r = arrFilterByKeywords(['abc', null, 1, ['abc']], 'abc') //非字串元素不匹配, 結果筆數恆等於arr之長度
console.log(r)
// => [
//     { hasKeyword: true, weight: 1 },
//     { hasKeyword: false, weight: 0 },
//     { hasKeyword: false, weight: 0 },
//     { hasKeyword: false, weight: 0 }
// ]
Parameters:
Name Type Description
arr Array

輸入要被尋找的字串陣列

keywords String | Array

輸入要尋找的關鍵字字串或陣列

Returns:

回傳結果物件陣列,陣列內各物件包含hasKeyword與weight欄位,其中hasKeyword代表有無關鍵字為布林值,weight代表權重為浮點數,其值可大於1

Type
Array

(static) arrFilterByNum(arr) → {Array}

Description:
  • 過濾陣列內元素僅保留數字,並且自動轉數值

    Unit Test: Github

Source:
Example
let arr

arr = ['abc', '-2.2', '-1.1', -1.1, -1, -0.5, 0, '0', 0.5, 1, 1.1, '1.1', '2.2', 'xyz']
console.log(arrFilterByNum(arr))
// => [ -2.2, -1.1, -1.1, -1, -0.5, 0, 0, 0.5, 1, 1.1, 1.1, 2.2 ]

arr = ['-2.2', '-1.1', -1.1, -1, -0.5, 0, '0']
console.log(arrFilterByNum(arr))
// => [ -2.2, -1.1, -1.1, -1, -0.5, 0, 0 ]
Parameters:
Name Type Description
arr Array

輸入原始陣列

Returns:

回傳新陣列

Type
Array

(static) arrFilterByPnum(arr) → {Array}

Description:
  • 過濾陣列內元素僅保留正數(不含0),並且自動轉數值

    Unit Test: Github

Source:
Example
let arr

arr = ['abc', '-2.2', '-1.1', -1.1, -1, -0.5, 0, '0', 0.5, 1, 1.1, '1.1', '2.2', 'xyz']
console.log(arrFilterByPnum(arr))
// => [ 0.5, 1, 1.1, 1.1, 2.2 ]

arr = ['-2.2', '-1.1', -1.1, -1, -0.5, 0, '0']
console.log(arrFilterByPnum(arr))
// => []
Parameters:
Name Type Description
arr Array

輸入原始陣列

Returns:

回傳新陣列

Type
Array

(static) arrFilterByPnumAndToLog(arr) → {Array}

Description:
  • 過濾陣列內元素僅保留正數(不含0),並且自動轉數值,再轉log10(Math.log)

    Unit Test: Github

Source:
Example
let arr

arr = ['abc', '-2.2', '-1.1', -1.1, -1, -0.5, 0, '0', 0.5, 1, 1.1, '1.1', '2.2', 'xyz']
console.log(arrFilterByPnumAndToLog(arr))
// => [
//   -0.6931471805599453,
//   0,
//   0.09531017980432493,
//   0.09531017980432493,
//   0.7884573603642703
// ]

arr = ['-2.2', '-1.1', -1.1, -1, -0.5, 0, '0']
console.log(arrFilterByPnumAndToLog(arr))
// => []
Parameters:
Name Type Description
arr Array

輸入原始陣列

Returns:

回傳新陣列

Type
Array

(static) arrFind(vall, vfind) → {Array}

Description:
  • 由vall陣列找尋vfind內各元素之第1位置

    Unit Test: Github

Source:
Example
console.log(arrFind([1, 2, 3, '4', 5, 'abc'], 2))
// => [ 1 ]

console.log(arrFind([1, 2, 3, '4', 5, 'abc'], 12))
// => [ -1 ]

console.log(arrFind([1, 2, 3, '4', 5, 'abc'], [2]))
// => [ 1 ]

console.log(arrFind([1, 2, 3, '4', 5, 'abc'], ['4', 2]))
// => [ 3, 1 ]

console.log(arrFind([1, true, 2, 3, '4', true, 5, 'abc'], true))
// => [ 1 ]

console.log(arrFind([1, true, 2, 3, '4', true, 5, 'abc'], [true]))
// => [ 1 ]

console.log(arrFind([1, 2, { x: 'xyz' }, 3, '4', 5, 'abc'], { x: 'xyz' }))
// => [ 2 ]

console.log(arrFind([1, 2, { x: 'xyz' }, 3, '4', 5, 'abc'], [{ x: 'xyz' }]))
// => [ 2 ]

console.log(arrFind([1, 2, { x: 'xyz' }, 3, '4', 5, 'abc'], ['4', { x: 'xyz' }]))
// => [ 4, 2 ]

console.log(arrFind([1, 2, { x: 'xyz' }, 3, '4', 5, 'abc'], [7, { x: 'xyz' }]))
// => [-1, 2]
Parameters:
Name Type Description
vall String | Number | Object | Boolean | Array

輸入要被尋找的任意資料陣列

vfind String | Number | Object | Boolean | Array

輸入要尋找的任意資料陣列

Returns:

回傳所找到各元素第1位置之陣列

Type
Array

(static) arrGroupByMaxmin(arr, maxmins, optopt) → {Array}

Description:
  • 依照指定最大最小值物件陣列切分陣列

    Unit Test: Github

Source:
Example
let arr1 = [1.1, 2.2, 3.3, 4.4, 5.5, 6.6]
let mm1 = [
    {
        min: 0,
        max: 2,
    },
    {
        min: 2,
        max: 5,
    },
]
console.log(arrGroupByMaxmin(arr1, mm1))
// => [
//   { min: 0, max: 2, items: [ 1.1 ] },
//   { min: 2, max: 5, items: [ 2.2, 3.3, 4.4 ] }
// ]

let arr2 = [1.1, 2.2, 3.3, 4.4, 5.5, 6.6]
let mm2 = [
    {
        min: 0,
        max: 2,
    },
    {
        min: 2.5,
        max: 5,
    },
]
console.log(arrGroupByMaxmin(arr2, mm2))
// => [
//   { min: 0, max: 2, items: [ 1.1 ] },
//   { min: 2.5, max: 5, items: [ 3.3, 4.4 ] }
// ]

let arr3 = [1.1, 2.2, 3.3, 4.4, 5.5, 6.6]
let mm3 = [
    {
        min: -1e20,
        max: 2,
    },
    {
        min: 2.5,
        max: 5,
    },
    {
        min: 6,
        max: 1e20,
    },
]
console.log(arrGroupByMaxmin(arr3, mm3))
// => [
//   { min: -100000000000000000000, max: 2, items: [ 1.1 ] },
//   { min: 2.5, max: 5, items: [ 3.3, 4.4 ] },
//   { min: 6, max: 100000000000000000000, items: [ 6.6 ] }
// ]

let arr4 = [
    {
        name: 'a',
        value: 1.1,
    },
    {
        name: 'b',
        value: 2.2,
    },
    {
        name: 'c',
        value: 3.3,
    },
    {
        name: 'd',
        value: 4.4,
    },
    {
        name: 'e',
        value: 5.5,
    },
    {
        name: 'f',
        value: 6.6,
    },
]
let mm4 = [
    {
        min: 0,
        max: 2,
    },
    {
        min: 2,
        max: 5,
    },
]
console.log(JSON.stringify(arrGroupByMaxmin(arr4, mm4), null, 2))
// => [
//   {
//     "min": 0,
//     "max": 2,
//     "items": [
//       {
//         "name": "a",
//         "value": 1.1
//       }
//     ]
//   },
//   {
//     "min": 2,
//     "max": 5,
//     "items": [
//       {
//         "name": "b",
//         "value": 2.2
//       },
//       {
//         "name": "c",
//         "value": 3.3
//       },
//       {
//         "name": "d",
//         "value": 4.4
//       }
//     ]
//   }
// ]

let arr5 = [1.1, 2.2, 3.3, 4.4, 5.5, 6.6]
let mm5 = [
    {
        rmin: 0,
        rmax: 2,
    },
    {
        rmin: 2,
        rmax: 5,
    },
]
console.log(arrGroupByMaxmin(arr5, mm5, { keyMin: 'rmin', keyMax: 'rmax' }))
// => [
//   { rmin: 0, rmax: 2, items: [ 1.1 ] },
//   { rmin: 2, rmax: 5, items: [ 2.2, 3.3, 4.4 ] }
// ]

let arr6 = [
    {
        name: 'a',
        data: 1.1,
    },
    {
        name: 'b',
        data: 2.2,
    },
    {
        name: 'c',
        data: 3.3,
    },
    {
        name: 'd',
        data: 4.4,
    },
    {
        name: 'e',
        data: 5.5,
    },
    {
        name: 'f',
        data: 6.6,
    },
]
let mm6 = [
    {
        min: 0,
        max: 2,
    },
    {
        min: 2,
        max: 5,
    },
]
console.log(JSON.stringify(arrGroupByMaxmin(arr6, mm6, { keyValue: 'data' }), null, 2))
// => [
//   {
//     "min": 0,
//     "max": 2,
//     "items": [
//       {
//         "name": "a",
//         "data": 1.1
//       }
//     ]
//   },
//   {
//     "min": 2,
//     "max": 5,
//     "items": [
//       {
//         "name": "b",
//         "data": 2.2
//       },
//       {
//         "name": "c",
//         "data": 3.3
//       },
//       {
//         "name": "d",
//         "data": 4.4
//       }
//     ]
//   }
// ]

let arr7 = [1.1, 2.2, 3.3, 4.4, 5.5, 6.6]
let mm7 = [
    {
        min: 0,
        max: 2,
    },
    {
        min: 2,
        max: 5,
    },
]
console.log(arrGroupByMaxmin(arr7, mm7, { keyItems: 'result' }))
// => [
//   { min: 0, max: 2, result: [ 1.1 ] },
//   { min: 2, max: 5, result: [ 2.2, 3.3, 4.4 ] }
// ]

let arr8 = [1.1, 2.2, 3.3, 4.4, 5.5, 6.6]
let mm8 = [
    {
        min: 1.1,
        minType: '>',
        max: 2.2,
        maxType: '<=',
    },
    {
        min: 2.2,
        minType: '>=',
        max: 5.5,
        maxType: '<',
    },
]
console.log(arrGroupByMaxmin(arr8, mm8))
// => [
//   {
//     min: 1.1,
//     minType: '>',
//     max: 2.2,
//     maxType: '<=',
//     items: [ 2.2 ]
//   },
//   {
//     min: 2.2,
//     minType: '>=',
//     max: 5.5,
//     maxType: '<',
//     items: [ 2.2, 3.3, 4.4 ]
//   }
// ]


let arr9 = [
    {
        name: 'a',
        value: 1.1,
    },
    {
        name: 'b',
        value: 2.2,
    },
    {
        name: 'c',
        value: 3.3,
    },
    {
        name: 'd',
        value: 4.4,
    },
    {
        name: 'e',
        value: 5.5,
    },
    {
        name: 'f',
        value: 6.6,
    },
]
let mm9 = [
    {
        min: 0,
        minType: '>=',
        max: 5,
        maxType: '<',
    },
    {
        min: 5,
        minType: '>=',
        max: 10,
        maxType: '<',
    },
]
console.log(JSON.stringify(arrGroupByMaxmin(arr9, mm9), null, 2))
// => [
//   {
//     "min": 0,
//     "minType": ">=",
//     "max": 5,
//     "maxType": "<",
//     "items": [
//       {
//         "name": "a",
//         "value": 1.1
//       },
//       {
//         "name": "b",
//         "value": 2.2
//       },
//       {
//         "name": "c",
//         "value": 3.3
//       },
//       {
//         "name": "d",
//         "value": 4.4
//       }
//     ]
//   },
//   {
//     "min": 5,
//     "minType": ">=",
//     "max": 10,
//     "maxType": "<",
//     "items": [
//       {
//         "name": "e",
//         "value": 5.5
//       },
//       {
//         "name": "f",
//         "value": 6.6
//       }
//     ]
//   }
// ]


let arr10 = [
    {
        name: 'a',
        data: 1.1,
    },
    {
        name: 'b',
        data: 2.2,
    },
    {
        name: 'c',
        data: 3.3,
    },
    {
        name: 'd',
        data: 4.4,
    },
    {
        name: 'e',
        data: 5.5,
    },
    {
        name: 'f',
        data: 6.6,
    },
]
let mm10 = [
    {
        min: 0,
        minType: '>=',
        max: 5,
        maxType: '<',
    },
    {
        min: 5,
        minType: '>=',
        max: 10,
        maxType: '<',
    },
]
console.log(JSON.stringify(arrGroupByMaxmin(arr10, mm10, { keyValue: 'data' }), null, 2))
// => [
//   {
//     "min": 0,
//     "minType": ">=",
//     "max": 5,
//     "maxType": "<",
//     "items": [
//       {
//         "name": "a",
//         "data": 1.1
//       },
//       {
//         "name": "b",
//         "data": 2.2
//       },
//       {
//         "name": "c",
//         "data": 3.3
//       },
//       {
//         "name": "d",
//         "data": 4.4
//       }
//     ]
//   },
//   {
//     "min": 5,
//     "minType": ">=",
//     "max": 10,
//     "maxType": "<",
//     "items": [
//       {
//         "name": "e",
//         "data": 5.5
//       },
//       {
//         "name": "f",
//         "data": 6.6
//       }
//     ]
//   }
// ]
Parameters:
Name Type Attributes Default Description
arr Array

輸入要被切割的陣列,元素本身或其keyValue欄位須為有效數字(有限數字或十進位數字字串,去頭尾空白後取值;Infinity、'Infinity'、'0x10'、包裝物件、null、非數字字串皆非有效數字),非有效數字之元素略過不分組;非陣列或空陣列回傳[];單一空元素之陣列([null]、['']、[{}])視為一個元素(非有效數字而略過不分組),回傳各組(皆無items),不被當成空陣列

maxmins Array

輸入要切分的最大最小值物件陣列,每個元素需為物件,至少得要包含keyMax與keyMin欄位,其值須為有效數字(同上,數字字串亦可);maxmins屬設定,上下限無效(未給、null、Infinity、'0x10'、包裝物件、非數字字串等)即throw Error(invalid maxmins[索引].鍵: must be a valid number,訊息不帶輸入值),且不論arr內容;欲表示「無上限或無下限」請自行給適當之有限極值(如1e20、-1e20);maxmins非陣列或空陣列回傳[];單一空元素之陣列([null]、['']、[{}])視為一個元素,缺上下限而throw(同[null, null]),不被當成空陣列

opt Object <optional>
{}

輸入設定物件

Properties
Name Type Attributes Default Description
keyMax String <optional>
'max'

輸入maxmins內各元素中,儲存最大值欄位字串,預設'max'

keyMin String <optional>
'min'

輸入maxmins內各元素中,儲存最小值欄位字串,預設'min'

keyValue String <optional>
'value'

輸入arr內各元素中,若為物件,則儲存欲判斷數值之欄位字串,預設'value'

keyItems String <optional>
'items'

輸入回傳maxmins物件陣列中,儲存所屬arr元素之欄位字串,預設'items'

Returns:

回傳切割後的陣列

Type
Array

(static) arrHas(vtar, vhas) → {Boolean}

Description:
  • 判斷任一字串陣列vtar內元素,是否「等於」任一字串陣列vhas內元素

    Unit Test: Github

Source:
Example
console.log(arrHas([1, 2, 3, '4', 5, 'abc'], 2))
// => true

console.log(arrHas([1, 2, 3, '4', 5, 'abc'], 6))
// => false

console.log(arrHas([1, 2, 3, '4', 5, 'abc'], [2]))
// => true

console.log(arrHas([1, 2, 3, '4', 5, 'abc'], [6]))
// => false

console.log(arrHas([1, 2, 3, '4', 5, 'abc'], ['4', 2]))
// => true

console.log(arrHas([1, 2, 3, '4', 5, 'abc'], ['7', 6]))
// => false

console.log(arrHas([1, true, 2, 3, '4', true, 5, 'abc'], true))
// => true

console.log(arrHas([1, true, 2, 3, '4', true, 5, 'abc'], false))
// => false

console.log(arrHas([1, true, 2, 3, '4', true, 5, 'abc'], [true]))
// => true

console.log(arrHas([1, true, 2, 3, '4', true, 5, 'abc'], [false]))
// => false

console.log(arrHas([1, 2, { x: 'xyz' }, 3, '4', 5, 'abc'], { x: 'xyz' }))
// => true

console.log(arrHas([1, 2, { x: 'xyz' }, 3, '4', 5, 'abc'], { x: 'opqr' }))
// => false

console.log(arrHas([1, 2, { x: 'xyz' }, 3, '4', 5, 'abc'], [{ x: 'xyz' }]))
// => true

console.log(arrHas([1, 2, { x: 'xyz' }, 3, '4', 5, 'abc'], [{ x: 'opqr' }]))
// => false

console.log(arrHas([1, 2, { x: 'xyz' }, 3, '4', 5, 'abc'], ['4', { x: 'xyz' }]))
// => true

console.log(arrHas([1, 2, { x: 'xyz' }, 3, '4', 5, 'abc'], ['7', { x: 'opqr' }]))
// => false
Parameters:
Name Type Description
vtar String | Number | Object | Boolean | Array

輸入被查找的字串陣列或字串

vhas String | Number | Object | Boolean | Array

輸入查找字串陣列或字串

Returns:

回傳判斷布林值

Type
Boolean

(static) arrInsert(arr, ind, items) → {Array}

Description:
  • 於陣列arr內指定位置ind插入新陣列items

    ind為必須參數,須為有效整數(iseint,數字字串亦可,去頭尾空白後取值)且為索引(0~4294967294),並須不大於arr長度,無效(含負數、小數、Infinity、'0x1'、包裝物件、超過長度)回傳空陣列[],不回傳原陣列,不報錯(使用者2026-11-12,dspec〈輸入參數之檢測機制〉§11 Q1-c:非數值之結構運算之主參數與次參數無效皆回輸出型別之空值)

    Unit Test: Github

Source:
Example
let arr = [1, 2.5, '123']
let r

r = arrInsert([], 0, 'abc')
console.log(r)
// => [ 'abc' ]

r = arrInsert(arr, 0, 'abc')
console.log(r)
// => [ 'abc', 1, 2.5, '123' ]

r = arrInsert(arr, 1, 'abc')
console.log(r)
// => [ 1, 'abc', 2.5, '123' ]

r = arrInsert(arr, 3, 'abc')
console.log(r)
// => [ 1, 2.5, '123', 'abc' ]

r = arrInsert(arr, 4, 'abc')
console.log(r)
// => [] (ind大於arr長度, 回傳空陣列)

r = arrInsert(arr, 'x', 'abc')
console.log(r)
// => [] (ind無效, 回傳空陣列)

r = arrInsert(arr, 1, null)
console.log(r)
// => [ 1, null, 2.5, '123' ]

r = arrInsert(arr, 1, ['abc', null, 'xyz'])
console.log(r)
// => [ 1, 'abc', null, 'xyz', 2.5, '123' ]
Parameters:
Name Type Description
arr Array

輸入原始陣列,非陣列回傳空陣列[]

ind Integer | String

輸入插入指標,必須參數(有效整數,0~4294967294,數字字串亦可),無效或大於arr長度回傳空陣列[]

items String | Number | Object | Boolean | Array

輸入欲插入的資料或陣列,必須參數,非陣列資料都會自動轉陣列再插入(null亦為資料),未給(undefined)回傳空陣列[]

Returns:

回傳新陣列

Type
Array

(static) arrLookupByMaxmin(arr, maxmins, optopt) → {Array}

Description:
  • 依照指定最大最小值物件陣列,查找陣列內各元素之所屬值

    Unit Test: Github

Source:
Example
let arr1 = [
    {
        name: 'a',
        value: 1.1,
    },
    {
        name: 'b',
        value: 2.2,
    },
    {
        name: 'c',
        value: 3.3,
    },
    {
        name: 'd',
        value: 4.4,
    },
    {
        name: 'e',
        value: 5.5,
    },
    {
        name: 'f',
        value: 6.6,
    },
]
let mm1 = [
    {
        min: 0,
        max: 2,
    },
    {
        min: 2,
        max: 5,
    },
]
console.log(JSON.stringify(arrLookupByMaxmin(arr1, mm1), null, 2))
// => [
//   {
//     "name": "a",
//     "value": 1.1,
//     "items": [
//       {
//         "min": 0,
//         "max": 2
//       }
//     ]
//   },
//   {
//     "name": "b",
//     "value": 2.2,
//     "items": [
//       {
//         "min": 2,
//         "max": 5
//       }
//     ]
//   },
//   {
//     "name": "c",
//     "value": 3.3,
//     "items": [
//       {
//         "min": 2,
//         "max": 5
//       }
//     ]
//   },
//   {
//     "name": "d",
//     "value": 4.4,
//     "items": [
//       {
//         "min": 2,
//         "max": 5
//       }
//     ]
//   },
//   {
//     "name": "e",
//     "value": 5.5
//   },
//   {
//     "name": "f",
//     "value": 6.6
//   }
// ]

let arr2 = [
    {
        name: 'a',
        value: 1.1,
    },
    {
        name: 'b',
        value: 2.2,
    },
    {
        name: 'c',
        value: 3.3,
    },
    {
        name: 'd',
        value: 4.4,
    },
    {
        name: 'e',
        value: 5.5,
    },
    {
        name: 'f',
        value: 6.6,
    },
]
let mm2 = [
    {
        rmin: 0,
        rmax: 2,
    },
    {
        rmin: 2,
        rmax: 5,
    },
]
console.log(JSON.stringify(arrLookupByMaxmin(arr2, mm2, { keyMin: 'rmin', keyMax: 'rmax' }), null, 2))
// => [
//   {
//     "name": "a",
//     "value": 1.1,
//     "items": [
//       {
//         "rmin": 0,
//         "rmax": 2
//       }
//     ]
//   },
//   {
//     "name": "b",
//     "value": 2.2,
//     "items": [
//       {
//         "rmin": 2,
//         "rmax": 5
//       }
//     ]
//   },
//   {
//     "name": "c",
//     "value": 3.3,
//     "items": [
//       {
//         "rmin": 2,
//         "rmax": 5
//       }
//     ]
//   },
//   {
//     "name": "d",
//     "value": 4.4,
//     "items": [
//       {
//         "rmin": 2,
//         "rmax": 5
//       }
//     ]
//   },
//   {
//     "name": "e",
//     "value": 5.5
//   },
//   {
//     "name": "f",
//     "value": 6.6
//   }
// ]

let arr3 = [
    {
        name: 'a',
        data: 1.1,
    },
    {
        name: 'b',
        data: 2.2,
    },
    {
        name: 'c',
        data: 3.3,
    },
    {
        name: 'd',
        data: 4.4,
    },
    {
        name: 'e',
        data: 5.5,
    },
    {
        name: 'f',
        data: 6.6,
    },
]
let mm3 = [
    {
        min: 0,
        max: 2,
    },
    {
        min: 2,
        max: 5,
    },
]
console.log(JSON.stringify(arrLookupByMaxmin(arr3, mm3, { keyValue: 'data' }), null, 2))
// => [
//   {
//     "name": "a",
//     "data": 1.1,
//     "items": [
//       {
//         "min": 0,
//         "max": 2
//       }
//     ]
//   },
//   {
//     "name": "b",
//     "data": 2.2,
//     "items": [
//       {
//         "min": 2,
//         "max": 5
//       }
//     ]
//   },
//   {
//     "name": "c",
//     "data": 3.3,
//     "items": [
//       {
//         "min": 2,
//         "max": 5
//       }
//     ]
//   },
//   {
//     "name": "d",
//     "data": 4.4,
//     "items": [
//       {
//         "min": 2,
//         "max": 5
//       }
//     ]
//   },
//   {
//     "name": "e",
//     "data": 5.5
//   },
//   {
//     "name": "f",
//     "data": 6.6
//   }
// ]

let arr4 = [
    {
        name: 'a',
        value: 1.1,
    },
    {
        name: 'b',
        value: 2.2,
    },
    {
        name: 'c',
        value: 3.3,
    },
    {
        name: 'd',
        value: 4.4,
    },
    {
        name: 'e',
        value: 5.5,
    },
    {
        name: 'f',
        value: 6.6,
    },
]
let mm4 = [
    {
        min: 0,
        max: 2,
    },
    {
        min: 2,
        max: 5,
    },
]
console.log(JSON.stringify(arrLookupByMaxmin(arr4, mm4, { keyItems: 'res' }), null, 2))
// => [
//   {
//     "name": "a",
//     "value": 1.1,
//     "res": [
//       {
//         "min": 0,
//         "max": 2
//       }
//     ]
//   },
//   {
//     "name": "b",
//     "value": 2.2,
//     "res": [
//       {
//         "min": 2,
//         "max": 5
//       }
//     ]
//   },
//   {
//     "name": "c",
//     "value": 3.3,
//     "res": [
//       {
//         "min": 2,
//         "max": 5
//       }
//     ]
//   },
//   {
//     "name": "d",
//     "value": 4.4,
//     "res": [
//       {
//         "min": 2,
//         "max": 5
//       }
//     ]
//   },
//   {
//     "name": "e",
//     "value": 5.5
//   },
//   {
//     "name": "f",
//     "value": 6.6
//   }
// ]

let arr5 = [
    {
        name: 'a',
        value: 1.1,
    },
    {
        name: 'b',
        value: 2.2,
    },
    {
        name: 'c',
        value: 3.3,
    },
    {
        name: 'd',
        value: 4.4,
    },
    {
        name: 'e',
        value: 5.5,
    },
    {
        name: 'f',
        value: 6.6,
    },
]
let mm5 = [
    {
        name: 'x1',
        min: 0,
        max: 2,
    },
    {
        name: 'x2',
        min: 2,
        max: 5,
    },
]
console.log(JSON.stringify(arrLookupByMaxmin(arr5, mm5, {
    keyItems: 'res',
    beforeAddResult: (m) => {
        return m.name
    }
}), null, 2))
// => [
//   {
//     "name": "a",
//     "value": 1.1,
//     "res": [
//       "x1"
//     ]
//   },
//   {
//     "name": "b",
//     "value": 2.2,
//     "res": [
//       "x2"
//     ]
//   },
//   {
//     "name": "c",
//     "value": 3.3,
//     "res": [
//       "x2"
//     ]
//   },
//   {
//     "name": "d",
//     "value": 4.4,
//     "res": [
//       "x2"
//     ]
//   },
//   {
//     "name": "e",
//     "value": 5.5
//   },
//   {
//     "name": "f",
//     "value": 6.6
//   }
// ]

let arr6 = [
    {
        name: 'a',
        value: 1.1,
    },
    {
        name: 'b',
        value: 2.2,
    },
    {
        name: 'c',
        value: 3.3,
    },
    {
        name: 'd',
        value: 4.4,
    },
    {
        name: 'e',
        value: 5.5,
    },
    {
        name: 'f',
        value: 6.6,
    },
]
let mm6 = [
    {
        min: 1.1,
        minType: '>',
        max: 2.2,
        maxType: '<=',
    },
    {
        min: 2.2,
        minType: '>=',
        max: 5.5,
        maxType: '<',
    },
]
console.log(JSON.stringify(arrLookupByMaxmin(arr6, mm6), null, 2))
// => [
//   {
//     "name": "a",
//     "value": 1.1
//   },
//   {
//     "name": "b",
//     "value": 2.2,
//     "items": [
//       {
//         "min": 1.1,
//         "minType": ">",
//         "max": 2.2,
//         "maxType": "<="
//       },
//       {
//         "min": 2.2,
//         "minType": ">=",
//         "max": 5.5,
//         "maxType": "<"
//       }
//     ]
//   },
//   {
//     "name": "c",
//     "value": 3.3,
//     "items": [
//       {
//         "min": 2.2,
//         "minType": ">=",
//         "max": 5.5,
//         "maxType": "<"
//       }
//     ]
//   },
//   {
//     "name": "d",
//     "value": 4.4,
//     "items": [
//       {
//         "min": 2.2,
//         "minType": ">=",
//         "max": 5.5,
//         "maxType": "<"
//       }
//     ]
//   },
//   {
//     "name": "e",
//     "value": 5.5
//   },
//   {
//     "name": "f",
//     "value": 6.6
//   }
// ]
Parameters:
Name Type Attributes Default Description
arr Array

輸入要被切割的陣列,需為物件陣列,否則無法添加查找結果;各元素之keyValue欄位須為有效數字(有限數字或十進位數字字串,去頭尾空白後取值;Infinity、'Infinity'、'0x10'、包裝物件、null、非數字字串皆非有效數字),非有效數字之元素略過不查找(不添加keyItems);非陣列、空陣列或首元素非有效物件(含單一空元素之陣列[null]、['']、[{}])回傳[],結果與多個空元素([null, null])相同,非因被當成空陣列

maxmins Array

輸入要切分的最大最小值物件陣列,每個元素需為物件,至少得要包含keyMax與keyMin欄位,其值須為有效數字(同上,數字字串亦可);maxmins屬設定,上下限無效(未給、null、Infinity、'0x10'、包裝物件、非數字字串等)即throw Error(invalid maxmins[索引].鍵: must be a valid number,訊息不帶輸入值),且不論arr內容;欲表示「無上限或無下限」請自行給適當之有限極值(如1e20、-1e20);maxmins非陣列或空陣列回傳[];單一空元素之陣列([null]、['']、[{}])視為一個元素,缺上下限而throw(同[null, null]),不被當成空陣列

opt Object <optional>
{}

輸入設定物件

Properties
Name Type Attributes Default Description
keyMax String <optional>
'max'

輸入maxmins內各元素中,儲存最大值欄位字串,預設'max'

keyMin String <optional>
'min'

輸入maxmins內各元素中,儲存最小值欄位字串,預設'min'

keyValue String <optional>
'value'

輸入arr內各元素中,若為物件,則儲存欲判斷數值之欄位字串,預設'value'

keyItems String <optional>
'items'

輸入回傳arr物件陣列中,儲存所屬maxmins元素之欄位字串,預設'items'

beforeAddResult function <optional>
null

輸入儲存至arr物件陣列前的處理函數,預設null

Returns:

回傳切割後的陣列

Type
Array

(static) arrMax(vall, optopt) → {Number|Object}

Description:
  • 找尋陣列內元素最大值

    只取有效數字(isenum: 有限數字,或去頭尾空白後為十進位寫法之數字字串)比較,其餘元素(含標記字串'-'、'NP'、''、null、undefined、布林、NaN、Infinity、'Infinity'、'0x10'、'1e400'、包裝物件等)略過不參與; vall內沒有任何有效數字(含空陣列)時throw Error('invalid vall: must contain a valid number'),vall不是陣列時throw Error('invalid vall: must be an array'),訊息不帶值。

    Unit Test: Github

Source:
Example
let r

r = arrMax([100000, 1, 30, 4, 21])
console.log(r)
// => 100000

r = arrMax([1, 30, 4, 21, 100000])
console.log(r)
// => 100000

r = arrMax([1, 30, 4, 100000, 21])
console.log(r)
// => 100000

r = arrMax([1, 30, 4, 100000, 21], { returnIndex: true })
console.log(r)
// => 3

try {
    arrMax(['March', 'Jan', 'Feb', 'Dec'])
}
catch (err) {
    console.log(err.message)
}
// => invalid vall: must contain a valid number

r = arrMax(['1', '30', '  4  ', '100000', '21'])
console.log(r)
// => 100000

r = arrMax(['1', '30', '  4  ', '100000', 21])
console.log(r)
// => 100000

r = arrMax(['a1', 'b30', '  4  ', '100000', 21])
console.log(r)
// => 100000

r = arrMax(
    [{ s: 'March', i: 1 }, { s: 'Jan', i: 4 }, { s: 'Feb', i: 100000 }, { s: 'Dec', i: 30 }, { s: 'Nov', i: 'a25' }],
    { compareKey: 'i' }
)
console.log(r)
// => { s: 'Feb', i: 100000 }

try {
    arrMax(
        [{ s: 'March', i: 1 }, { s: 'Jan', i: 4 }, { s: 'Feb', i: 100000 }, { s: 'Dec', i: 30 }, { s: 'Nov', i: 'a25' }],
        { compareKey: 's' }
    )
}
catch (err) {
    console.log(err.message)
}
// => invalid vall: must contain a valid number

r = arrMax([5, Infinity, '0x10', '-', null, 3])
console.log(r)
// => 5 (Infinity與'0x10'不是有效數字, 略過)

r = arrMax(
    [{ s: 'March', i: 1 }, { s: 'Jan', i: 4 }, { s: 'Feb', i: 100000 }, { s: 'Dec', i: 30 }, { s: 'Nov', i: 'a25' }],
    { compareKey: 'i', returnIndex: true }
)
console.log(r)
// => 2
Parameters:
Name Type Attributes Default Description
vall Array

輸入原始陣列,需含至少一個有效數字(定義見isenum,不收Infinity與'0x10'等),否則throw

opt Object <optional>
{}

輸入設定物件,預設{}

Properties
Name Type Attributes Default Description
returnIndex Boolean <optional>
false

輸入是否回傳排序指標陣列布林值,預設false

compareKey String <optional>
null

輸入當vall為物件陣列時,指定取compareKey欄位出來排序,compareKey需為有效字串,預設null

Returns:

回傳最大值數字或判斷具有最大值之物件,沒有任何有效數字時throw

Type
Number | Object

(static) arrMin(vall, optopt) → {Number|Object}

Description:
  • 找尋陣列內元素最小值

    只取有效數字(isenum: 有限數字,或去頭尾空白後為十進位寫法之數字字串)比較,其餘元素(含標記字串'-'、'NP'、''、null、undefined、布林、NaN、Infinity、'Infinity'、'0x10'、'1e400'、包裝物件等)略過不參與; vall內沒有任何有效數字(含空陣列)時throw Error('invalid vall: must contain a valid number'),vall不是陣列時throw Error('invalid vall: must be an array'),訊息不帶值。

    Unit Test: Github

Source:
Example
let r

r = arrMin([100000, 1, 30, 4, 21])
console.log(r)
// => 1

r = arrMin([1, 30, 4, 21, 100000])
console.log(r)
// => 1

r = arrMin([1, 30, 4, 100000, 21])
console.log(r)
// => 1

r = arrMin([1, 30, 4, 100000, 21], { returnIndex: true })
console.log(r)
// => 0

try {
    arrMin(['March', 'Jan', 'Feb', 'Dec'])
}
catch (err) {
    console.log(err.message)
}
// => invalid vall: must contain a valid number

r = arrMin(['1', '30', '  4  ', '100000', '21'])
console.log(r)
// => 1

r = arrMin(['1', '30', '  4  ', '100000', 21])
console.log(r)
// => 1

r = arrMin(['a1', 'b30', '  4  ', '100000', 21])
console.log(r)
// => 4

r = arrMin(
    [{ s: 'March', i: 1 }, { s: 'Jan', i: 4 }, { s: 'Feb', i: 100000 }, { s: 'Dec', i: 30 }, { s: 'Nov', i: 'a25' }],
    { compareKey: 'i' }
)
console.log(r)
// => { s: 'March', i: 1 }

try {
    arrMin(
        [{ s: 'March', i: 1 }, { s: 'Jan', i: 4 }, { s: 'Feb', i: 100000 }, { s: 'Dec', i: 30 }, { s: 'Nov', i: 'a25' }],
        { compareKey: 's' }
    )
}
catch (err) {
    console.log(err.message)
}
// => invalid vall: must contain a valid number

r = arrMin([5, -Infinity, '0x10', '-', null, 3])
console.log(r)
// => 3 (-Infinity與'0x10'不是有效數字, 略過)

r = arrMin(
    [{ s: 'March', i: 1 }, { s: 'Jan', i: 4 }, { s: 'Feb', i: 100000 }, { s: 'Dec', i: 30 }, { s: 'Nov', i: 'a25' }],
    { compareKey: 'i', returnIndex: true }
)
console.log(r)
// => 0
Parameters:
Name Type Attributes Default Description
vall Array

輸入原始陣列,需含至少一個有效數字(定義見isenum,不收Infinity與'0x10'等),否則throw

opt Object <optional>
{}

輸入設定物件,預設{}

Properties
Name Type Attributes Default Description
returnIndex Boolean <optional>
false

輸入是否回傳排序指標陣列布林值,預設false

compareKey String <optional>
null

輸入當vall為物件陣列時,指定取compareKey欄位出來排序,compareKey需為有效字串,預設null

Returns:

回傳最小值數字或判斷具有最小值之物件,沒有任何有效數字時throw

Type
Number | Object

(static) arrMulti(…arguments, optopt) → {Array}

Description:
  • 各陣列同位置元素相乘

    各元素以isenum判定是否為有效數字(有限數字,或去頭尾空白後為十進位寫法之數字字串),有效者取其數值參與相乘; 凡非有效數字(含標記字串'-'、'NP'、''、null、undefined、布林、NaN、Infinity、'Infinity'、'0x10'、'1e400'、包裝物件等),一律以基準值opt.base(預設1)代入計算,不報錯、不略過; 同位置元素皆非有效數字者,該位置結果為opt.base的平方(預設即1)。 空陣列為合法資料:所有輸入陣列皆為空陣列時空進空出,回傳空陣列,不報錯(如arrMulti([], [])回傳[])。 有元素的陣列各自至少要有1個有效數字,否則throw Error('invalid arrs[索引]: must contain a valid number'),訊息不帶輸入值。 陣列容器之處置不變:陣列參數少於2個、非陣列、長度不同(含一個為空陣列、另一個非空,如arrMulti([1], [])),回傳空陣列(先於有效數字之檢查)。 本函數為不定參數,最後一個參數若為一般物件(非陣列)則視為opt;最後一個參數若為undefined或null則視為未給opt(不當成陣列參數),如arrMulti(a, b, undefined)等同arrMulti(a, b)。

    Unit Test: Github

Source:
Example
let v1 = [1, 2, 3, 4]
let v2 = [0.1, 0.1, 0.1, 0.1]
let v3 = [11, 22, 33, 44]

console.log(arrMulti(v1, v2))
// => [ 0.1, 0.2, 0.30000000000000004, 0.4 ]

console.log(arrMulti(v1, v2, v3))
// => [ 1.1, 4.4, 9.900000000000002, 17.6 ]

console.log(arrMulti([2, '3', ' 4 ', 5], [10, '-', null, Infinity]))
// => [ 20, 3, 4, 5 ] (非有效數字以基準值1代入)

console.log(arrMulti([2, '-'], [10, 20], { base: 0 }))
// => [ 20, 0 ] (非有效數字以基準值0代入)

console.log(arrMulti([], []))
// => [] (空陣列為合法資料,空進空出)

console.log(arrMulti([1], []))
// => [] (長度不同)
Parameters:
Name Type Attributes Description
arguments Array <repeatable>

輸入n個陣列,需同長度,各陣列針對各位置元素進行相乘;元素為有效數字(數字或數字字串,定義見isenum)者取其數值,非有效數字者以opt.base代入;皆為空陣列則回傳空陣列,否則每個陣列各自至少1個有效數字,否則throw

opt Object <optional>

輸入最後一個參數為一般物件時視為設定物件,預設未給

Properties
Name Type Attributes Default Description
base Number | String <optional>
1

輸入非有效數字元素代入之基準值,需為有效數字(數字或數字字串,定義見isenum),非預期之輸入(非有效數字、Infinity、'0x10'、包裝物件等)視為未給而改用預設,不報錯,預設1

debug Boolean <optional>
false

輸入是否於opt.base為非預期之輸入而改用預設時輸出警告布林值,非布林視為false,警告為固定詞彙(不含傳入之值),同一參數每個行程只警告一次,預設false

funLog function <optional>
null

輸入警告出口函數,以(msg, { fn, reason, key })呼叫,未給則用console.warn,預設null

Returns:

回傳各元素相乘後陣列,所有輸入陣列皆為空陣列時回傳空陣列,容器無法運算(陣列少於2個、非陣列、長度不同)時亦回傳空陣列

Type
Array

(static) arrNorm(vec, optopt) → {Number}

Description:
  • 陣列Norm值,代表由各元素平方值相加開根號

    內部以arrProduct(vec, vec)計算(傳入基準值base為opt.base,預設0): 元素以isenum判定是否為有效數字(有限數字,或去頭尾空白後為十進位寫法之數字字串),有效者取其數值; 凡非有效數字(含標記字串'-'、'NP'、''、null、undefined、布林、NaN、Infinity、'Infinity'、'0x10'、'1e400'、包裝物件等),一律以基準值opt.base(預設0)代入,故預設下不影響結果,不報錯。 輸入陣列至少要有1個有效數字(含空陣列,視為0個),否則throw Error('invalid vec: must contain a valid number'),訊息不帶輸入值。 輸入不是陣列時回傳null(容器之處置不變,先於有效數字之檢查);各元素平方和為0時亦回傳null(舊有行為不變)。

    Unit Test: Github

Source:
Example
console.log(arrNorm([1, 2, 3, 4]))
// => 5.477225575051661

console.log(arrNorm([0.1, 0.1, 0.1, 0.1]))
// => 0.2

console.log(arrNorm([11, 22, 33, 44]))
// => 60.249481325568276

console.log(arrNorm([3, '-', 4]))
// => 5 (非有效數字以基準值0代入)
Parameters:
Name Type Attributes Description
vec Array

輸入要被計算的陣列,元素為有效數字(數字或數字字串,定義見isenum)者取其數值,非有效數字者以opt.base代入;至少1個有效數字,否則throw

opt Object <optional>

輸入設定物件,預設未給

Properties
Name Type Attributes Default Description
base Number | String <optional>
0

輸入非有效數字元素代入之基準值,需為有效數字(數字或數字字串,定義見isenum),非預期之輸入(非有效數字、Infinity、'0x10'、包裝物件等)視為未給而改用預設,不報錯,預設0

debug Boolean <optional>
false

輸入是否於opt.base為非預期之輸入而改用預設時輸出警告布林值,非布林視為false,警告為固定詞彙(不含傳入之值),同一參數每個行程只警告一次,預設false

funLog function <optional>
null

輸入警告出口函數,以(msg, { fn, reason, key })呼叫,未給則用console.warn,預設null

Returns:

回傳Norm值,輸入非陣列或平方和為0時回傳null

Type
Number

(static) arrProduct(…arguments, optopt) → {Number}

Description:
  • 各陣列同位置元素相乘並加總

    內部以arrMulti逐位置相乘(傳入基準值base為opt.base,預設0)再加總: 元素以isenum判定是否為有效數字(有限數字,或去頭尾空白後為十進位寫法之數字字串),有效者取其數值參與相乘; 凡非有效數字(含標記字串'-'、'NP'、''、null、undefined、布林、NaN、Infinity、'Infinity'、'0x10'、'1e400'、包裝物件等),一律以基準值opt.base(預設0)代入,故預設下該位置之乘積為0、不影響總和,不報錯。 本函數由陣列算出單一數值,空陣列算不出數值:任一輸入陣列為空陣列即throw Error('invalid arrs[索引]: must contain a valid number'),索引為第一個空陣列(如arrProduct([1], [])為arrs[1]、arrProduct([], [1])為arrs[0]),即使另一陣列長度不同亦然。 每個輸入陣列各自至少要有1個有效數字(含空陣列,皆視為0個),否則throw Error('invalid arrs[索引]: must contain a valid number'),訊息不帶輸入值。 陣列容器之處置不變:陣列參數少於2個、非陣列、長度不同(陣列皆非空者),回傳null(先於有效數字之檢查,但後於空陣列之檢查)。 本函數為不定參數,最後一個參數若為一般物件(非陣列)則視為opt;最後一個參數若為undefined或null則視為未給opt(不當成陣列參數),如arrProduct(a, b, undefined)等同arrProduct(a, b)。

    Unit Test: Github

Source:
Example
let v1 = [1, 2, 3, 4]
let v2 = [0.1, 0.1, 0.1, 0.1]
let v3 = [11, 22, 33, 44]

console.log(arrProduct(v1, v2))
// => 1

console.log(arrProduct(v1, v2, v3))
// => 33

console.log(arrProduct([1, 2, 3], [4, '-', 6]))
// => 22 (非有效數字以基準值0代入,該位置乘積為0)

console.log(arrProduct([1, 2, 3], [4, '-', 6], { base: 1 }))
// => 24 (非有效數字以基準值1代入,該位置乘積為2)

try {
    arrProduct([1], [])
}
catch (err) {
    console.log(err.message)
}
// => invalid arrs[1]: must contain a valid number (空陣列算不出數值)
Parameters:
Name Type Attributes Description
arguments Array <repeatable>

輸入n個陣列,需同長度,各陣列針對各位置元素進行相乘後加總;元素為有效數字(數字或數字字串,定義見isenum)者取其數值,非有效數字者以opt.base代入;任一陣列為空陣列則throw,每個陣列各自至少1個有效數字,否則throw

opt Object <optional>

輸入最後一個參數為一般物件時視為設定物件,預設未給

Properties
Name Type Attributes Default Description
base Number | String <optional>
0

輸入非有效數字元素代入之基準值,需為有效數字(數字或數字字串,定義見isenum),非預期之輸入(非有效數字、Infinity、'0x10'、包裝物件等)視為未給而改用預設,不報錯,預設0

debug Boolean <optional>
false

輸入是否於opt.base為非預期之輸入而改用預設時輸出警告布林值,非布林視為false,警告為固定詞彙(不含傳入之值),同一參數每個行程只警告一次,預設false

funLog function <optional>
null

輸入警告出口函數,以(msg, { fn, reason, key })呼叫,未給則用console.warn,預設null

Returns:

回傳各位置元素相乘後之加總,容器無法運算(陣列少於2個、長度不同等)時回傳null

Type
Number

(static) arrPull(vall, vpull) → {Array}

Description:
  • 針對陣列移除元素或陣列內全部元素

    Unit Test: Github

Source:
Example
console.log(arrPull([1, 2, 3], null))
// => [] (vpull無效, 回傳空陣列)

console.log(arrPull([1, 2, 3], []))
// => [ 1, 2, 3 ] (無可移除)

console.log(arrPull([1, 2, 3, 4, 5, 'abc'], [1, 4]))
// => [ 2, 3, 5, 'abc' ]

console.log(arrPull([1, 2, 3, '4', 5, 'abc'], [1, 4]))
// => [ 2, 3, '4', 5, 'abc' ]

console.log(arrPull([1, 2, 3, '4', 5, 'abc'], [6, 7]))
// => [ 1, 2, 3, '4', 5, 'abc' ]

console.log(arrPull([1, null, 2, '', 3], [null, '']))
// => [ 1, 2, 3 ] (單一空元素視為一個待移除值)

console.log(arrPull([null], [1]))
// => [ null ] (單一空元素視為一個元素, 不被當成空陣列)
Parameters:
Name Type Description
vall Array

輸入原始陣列,非陣列回傳空陣列[];單一空元素之陣列([null]、['']、[{}])視為一個元素,照常處理而保留(不被當成空陣列)

vpull Array | Object | Number | String | Boolean

輸入要被移除的元素或陣列,必須參數,單值(物件、數字、字串、布林,含''與{})自動轉陣列,其餘非陣列(undefined、null、NaN、函數等)為無效而回傳空陣列[],不回傳原陣列;空陣列代表無可移除,回傳原陣列之複本;單一空元素之陣列([null]、[''])視為一個待移除值,會移除vall內之null與''(以SameValueZero比對,{}為新物件故無法以值移除);單值''亦同(移除vall內之'')

Returns:

回傳移除後陣列(新陣列,不改動原陣列)

Type
Array

(static) arrPullAt(vall, vpull) → {Array}

Description:
  • 針對陣列移除指定位置或陣列的指定位置

    vpull為必須參數:單值時須為有效整數(iseint,數字字串亦可,去頭尾空白後取值)且為索引(0~4294967294),無效(含負數、小數、Infinity、'0x1'、包裝物件、null、undefined等)回傳空陣列[],不回傳原陣列(使用者2026-11-12,dspec〈輸入參數之檢測機制〉§11 Q1-c:非數值之結構運算之次參數無效回輸出型別之空值); 為陣列時,其中有效索引者照常移除,無效索引(非數字、負數、小數、Infinity、'0x1'等)者略過,不會被當成索引0而誤刪;空陣列代表無可移除,回傳原陣列之複本

    Unit Test: Github

Source:
Example
console.log(arrPullAt([1, 2, 3, 4, 5, 'abc'], [0, 2]))
// => [ 2, 4, 5, 'abc' ]

console.log(arrPullAt([1, 2, 3, '4', 5, 'abc'], [1, 3]))
// => [ 1, 3, 5, 'abc' ]

console.log(arrPullAt([1, 2, 3, '4', 5, 'abc'], [4, 7]))
// => [ 1, 2, 3, '4', 'abc' ]

console.log(arrPullAt([1, 2, 3], ['x', 1]))
// => [ 1, 3 ] (無效索引'x'略過,不會被當成索引0而誤刪)

console.log(arrPullAt([1, 2, 3], 'x'))
// => [] (單值vpull無效, 回傳空陣列)
Parameters:
Name Type Description
vall Array

輸入原始陣列,非陣列回傳空陣列[];單一空元素之陣列([null]、['']、[{}])視為一個元素,照常處理而保留(不被當成空陣列)

vpull Array | Integer | String

輸入要被移除的指定位置或陣列的指定位置,必須參數(有效整數,0~4294967294,數字字串亦可),單值無效回傳空陣列[],陣列中之無效索引略過

Returns:

回傳移除後陣列(新陣列,不改動原陣列)

Type
Array

(static) arrReduce(vall, fun, optopt) → {Number|Object}

Description:
  • 找尋陣列內元素指定值

    Unit Test: Github

Source:
Example
let r

r = arrReduce([100000, 1, 30, 4, 21], (vTemp, vNow) => {
    if (vTemp === null) {
        return vNow
    }
    return Math.min(vTemp, vNow)
})
console.log(r)
// => 1

r = arrReduce([1, 30, 4, 21, 100000], (vTemp, vNow) => {
    if (vTemp === null) {
        return vNow
    }
    return Math.max(vTemp, vNow)
})
console.log(r)
// => 100000

r = arrReduce([1, 30, 4, 100000, 21], (vTemp, vNow) => {
    if (vTemp === null) {
        return vNow
    }
    return Math.max(vTemp, vNow)
}, { returnIndex: true })
console.log(r)
// => 3

r = arrReduce(
    [{ s: 'March', i: 1 }, { s: 'Jan', i: 4 }, { s: 'Feb', i: 100000 }, { s: 'Dec', i: 30 }, { s: 'Nov', i: 25, }],
    (vTemp, vNow) => {
        if (vTemp === null) {
            return vNow.i
        }
        return Math.min(vTemp, vNow.i)
    },
)
console.log(r)
// => 1

r = arrReduce(
    [{ s: 'March', i: 1 }, { s: 'Jan', i: 4 }, { s: 'Feb', i: 100000 }, { s: 'Dec', i: 30 }, { s: 'Nov', i: 25, }],
    (vTemp, vNow) => {
        if (vTemp === null) {
            return vNow
        }
        return vTemp.i < vNow.i ? vNow : vTemp //max
    },
)
console.log(r)
// => { s: 'Feb', i: 100000 }

r = arrReduce(
    [{ s: 'March', i: 1 }, { s: 'Jan', i: 4 }, { s: 'Feb', i: 100000 }, { s: 'Dec', i: 30 }, { s: 'Nov', i: 25, }],
    (vTemp, vNow) => {
        if (vTemp === null) {
            return vNow
        }
        return vTemp.i < vNow.i ? vNow : vTemp //max
    },
    { returnIndex: true }
)
console.log(r)
// => 2
Parameters:
Name Type Attributes Default Description
vall Array

輸入原始陣列,須為陣列,非陣列回傳null;空陣列回傳null(無元素可彙總);單一空元素之陣列([null]、['']、[{}])視為一個元素,會對該元素呼叫fun(不被當成空陣列)

fun function

輸入處理與比對函數,輸入參數為全域暫存值與現在提取值,函數比對完須回傳新的全域暫存值;非函數回傳null

opt Object <optional>
{}

輸入設定物件,預設{}

Properties
Name Type Attributes Default Description
returnIndex Boolean <optional>
false

輸入是否回傳排序指標陣列布林值,預設false

Returns:

回傳指定值數字或判斷具有指定值之物件

Type
Number | Object

(static) arrReverse(vall) → {Array}

Description:
  • 反序排列陣列

    vall須為陣列,非陣列(含未給、null、字串、物件等)回傳空陣列[],不拋錯(輸入參數檢測機制C7,第1參數型別不對回輸出型別之空結果);空陣列為合法資料,回傳空陣列[];單一空元素之陣列([null]、['']、[{}]、[[]]、[undefined])視為一個元素,照常反序而保留(回傳深拷貝後之同內容新陣列)。回傳深拷貝後反序之新陣列,不改動輸入陣列。

    Unit Test: Github

Source:
Example
console.log(arrReverse([1, 2, 3, 4, 5, 'abc']))
// => [ 'abc', 5, 4, 3, 2, 1 ]

console.log(arrReverse([1, 2, 3, '4', 5, 'abc']))
// => [ 'abc', 5, '4', 3, 2, 1 ]

console.log(arrReverse([]))
// => []

console.log(arrReverse([null]))
// => [ null ] (單一空元素視為一個元素, 不被當成空陣列)

console.log(arrReverse('abc'))
// => [] (非陣列回傳空結果, 不拋錯)
Parameters:
Name Type Description
vall Array

輸入原始陣列,須為陣列(空陣列合法,回傳[]),非陣列回傳[];[null]、['']、[{}]視為一個元素而保留

Returns:

回傳反序後之新陣列;vall非陣列或為空陣列時回傳[]

Type
Array

(static) arrSep(arr, opt) → {Array}

Description:
  • 依照指定數量切分陣列

    arr須為陣列,非陣列(含未給、null、字串、物件等)回傳空陣列[],不拋錯(輸入參數檢測機制C7,第1參數型別不對回輸出型別之空結果),此時不檢查opt。opt為必須參數且與arr有無資料無關:須為設定物件(含空物件{}),非物件(含未給、null、整數、字串、陣列等)throw Error('invalid opt: must be an object with numCount or numGroup');舊式整數寫法arrSep(arr, 3)已移除(自有套件不做舊版相容),請改用{ numCount: 3 }。設定物件之numCount(每組個數上限)與numGroup(組數)為二擇一必給,各須為有效整數(iseint,數字字串亦可,去頭尾空白後取值)且為1~4294967295(個數),兩者皆無效(含未給、空物件{})則同樣throw Error('invalid opt: must be an object with numCount or numGroup'),兩者皆有效時採numCount;訊息皆不帶輸入值。檢測順序為arr、opt。arr為空陣列(opt有效)時為合法資料,回傳[];單一空元素之陣列([null]、['']、[{}]、[[]]、[undefined])視為一個元素,照常切分而保留

    Unit Test: Github

Source:
Example
let arr = ['a', 123, 'xyz', 5.678, null, 'd', [], { x: 'x1', y: 'y1' }]

console.log(arrSep(arr, { numCount: 2 }))
// => [
//   [ 'a', 123 ],
//   [ 'xyz', 5.678 ],
//   [ null, 'd' ],
//   [ [], { x: 'x1', y: 'y1' } ]
// ]

console.log(arrSep(arr, { numCount: 3 }))
// => [
//   [ 'a', 123, 'xyz' ],
//   [ 5.678, null, 'd' ],
//   [ [], { x: 'x1', y: 'y1' } ]
// ]

console.log(arrSep([1, 2, 3, 4, 5], { numGroup: 2 }))
// => [ [ 1, 3, 5 ], [ 2, 4 ] ]

console.log(arrSep([], { numCount: 2 }))
// => []

console.log(arrSep([null], { numCount: 2 }))
// => [ [ null ] ] (單一空元素視為一個元素, 不被當成空陣列)

console.log(arrSep('abc', { numCount: 2 }))
// => [] (arr非陣列回傳空結果, 不拋錯)

try {
    arrSep(arr, 3)
}
catch (err) {
    console.log(err.message)
}
// => invalid opt: must be an object with numCount or numGroup

try {
    arrSep(arr, { numCount: 0 })
}
catch (err) {
    console.log(err.message)
}
// => invalid opt: must be an object with numCount or numGroup
Parameters:
Name Type Description
arr Array

輸入要被切割的陣列,須為陣列(空陣列合法,回傳[]),非陣列回傳[];[null]、['']、[{}]視為一個元素而保留

opt Object

輸入設定物件,必須參數(arr為有效陣列時才檢查),須含鍵'numCount'或'numGroup'(二擇一必給)而對應值皆為正整數(有效整數,1~4294967295,數字字串亦可,Infinity、0、小數、'0x10'、包裝物件等為無效),numCount代表每個切割後群組內所擁有的元素數量上限,numGroup代表欲切割成幾個群組數量;非物件或兩鍵皆無效throw

Properties
Name Type Description
numCount Integer | String

輸入每個切割後群組內所擁有的元素數量上限,與opt.numGroup二擇一必給,兩者皆有效時採用numCount

numGroup Integer | String

輸入欲切割成幾個群組之數量,與opt.numCount二擇一必給,numCount無效時才採用

Throws:

arr為陣列而opt非物件時throw Error('invalid opt: must be an object with numCount or numGroup');opt為物件而numCount與numGroup皆無效(含{})時同樣throw Error('invalid opt: must be an object with numCount or numGroup');訊息皆不帶輸入值

Type
Error
Returns:

回傳切割後的陣列;arr非陣列或為空陣列時回傳[]

Type
Array

(static) arrSort(vall, optopt) → {Array}

Description:
  • 排序vall陣列,可針對純數字、純字串、含固定開頭字元的數字字串、物件陣列進行排列

    排序規則(同Excel之升冪):數字與數字字串依數值排序排在最前;其他字串其次,若皆可剔除開頭結尾非數字字元而得數字(例如'abc1')則依其數值排序,否則依字串排序;無法轉數字或無法解析者(空字串、純空白字串、null、undefined、NaN、布林、物件、陣列等)無法排序,一律放最末並維持原順序

    localeCompare為true時數字與字串一併以localeCompare(numeric)排序,無法解析者仍放最末;vall全為物件時取compareKey欄位之值套用相同規則,無此欄位者放最末

    Unit Test: Github

Source:
Example
let r

r = arrSort([1, 30, 4, 21, 100000])
console.log(r)
// => [ 1, 4, 21, 30, 100000 ]

r = arrSort([1, 30, 4, 21, 100000], { returnIndex: true })
console.log(r)
// => [ 0, 2, 3, 1, 4 ]

r = arrSort(['March', 'Jan', 'Feb', 'Dec'])
console.log(r)
// => [ 'Dec', 'Feb', 'Jan', 'March' ]

r = arrSort(['1', '30', '  4  ', '21', '100000'])
console.log(r)
// => [ '1', '  4  ', '21', '30', '100000' ]

r = arrSort(['1', '30', '  4  ', 21, '100000'])
console.log(r)
// => [ '1', '  4  ', 21, '30', '100000' ]

r = arrSort([1, 2, 'abc', 5, 3, '4'])
console.log(r)
// => [ 1, 2, 3, '4', 5, 'abc' ]

r = arrSort([10, '', 9, 'N/A', ' ', null, 100])
console.log(r)
// => [ 9, 10, 100, 'N/A', '', ' ', null ]

r = arrSort(['abc1', 'abc30', 'abc4', 'abc21', 'abc100000'])
console.log(r)
// => [ 'abc1', 'abc4', 'abc21', 'abc30', 'abc100000' ]

r = arrSort(['1a', '30c', '  4 abc ', 'xyz', '21d', '100000xy'])
console.log(r)
// => [ '  4 abc ', '100000xy', '1a', '21d', '30c', 'xyz' ]

r = arrSort(
    [{ s: 'March', i: 1 }, { s: 'Jan', i: 4 }, { s: 'Feb', i: 100000 }, { s: 'Dec', i: 30 }],
    { compareKey: 'i' }
)
console.log(r)
// => [
//   { s: 'March', i: 1 },
//   { s: 'Jan', i: 4 },
//   { s: 'Dec', i: 30 },
//   { s: 'Feb', i: 100000 }
// ]

r = arrSort(
    [{ s: 'March', i: 1 }, { s: 'Jan', i: 4 }, { s: 'Feb', i: 100000 }, { s: 'Dec', i: 30 }],
    { compareKey: 's' }
)
console.log(r)
// => [
//   { s: 'Dec', i: 30 },
//   { s: 'Feb', i: 100000 },
//   { s: 'Jan', i: 4 },
//   { s: 'March', i: 1 }
// ]

r = arrSort(
    [{ s: 'abc1', i: 1, }, { s: 'abc', i: -1, }, { s: 'abc30', i: 4, }, { s: 'abc4', i: 100000, }, { s: 'abc100000', i: 30, }],
    { compareKey: 's' }
)
console.log(r)
// => [
//   { s: 'abc', i: -1 },
//   { s: 'abc1', i: 1 },
//   { s: 'abc100000', i: 30 },
//   { s: 'abc30', i: 4 },
//   { s: 'abc4', i: 100000 }
// ]

r = arrSort(
    [{ s: 'abc1', i: 1, }, { s: 'abc', i: -1, }, { s: 'abc30', i: 4, }, { s: 'abc4', i: 100000, }, { s: 'abc100000', i: 30, }],
    { compareKey: 's', localeCompare: true }
)
console.log(r)
// => [
//   { s: 'abc', i: -1 },
//   { s: 'abc1', i: 1 },
//   { s: 'abc4', i: 100000 },
//   { s: 'abc30', i: 4 },
//   { s: 'abc100000', i: 30 }
// ]

r = arrSort(
    [{ s: '中文1', i: 1, }, { s: '中文', i: -1, }, { s: '中文30', i: 4, }, { s: '中文4', i: 100000, }, { s: '中文100000', i: 30, }],
    { compareKey: 's', localeCompare: true }
)
console.log(r)
// => [
//   { s: '中文', i: -1 },
//   { s: '中文1', i: 1 },
//   { s: '中文4', i: 100000 },
//   { s: '中文30', i: 4 },
//   { s: '中文100000', i: 30 }
// ]

r = arrSort(
    [{ s: 'xyz.txt', i: 100, }, { s: 'abc1.txt', i: 1, }, { s: 'abc.txt', i: -1, }, { s: 'abc', i: -2, }, { s: 'abc30.txt', i: 4, }, { s: 'abc4.txt', i: 100000, }, { s: 'abc100000.txt', i: 30, }],
    { compareKey: 's', localeCompare: true }
)
console.log(r)
// => [
//   { s: 'abc', i: -2 },
//   { s: 'abc.txt', i: -1 },
//   { s: 'abc1.txt', i: 1 },
//   { s: 'abc4.txt', i: 100000 },
//   { s: 'abc30.txt', i: 4 },
//   { s: 'abc100000.txt', i: 30 },
//   { s: 'xyz.txt', i: 100 }
// ]
Parameters:
Name Type Attributes Default Description
vall Array

輸入要被提取的任意資料陣列,非陣列或空陣列回傳[];單一空元素之陣列([null]、['']、[{}])視為一個元素而保留(回傳該陣列,returnIndex為true時回傳[0]),不被當成空陣列

opt Object <optional>
{}

輸入設定物件,預設{}

Properties
Name Type Attributes Default Description
localeCompare Boolean <optional>
false

輸入是否使用localeCompare排序布林值,預設false

returnIndex Boolean <optional>
false

輸入是否回傳排序指標陣列布林值,預設false

compareKey String <optional>
null

輸入當vall為物件陣列時,指定取compareKey欄位出來排序,compareKey需為有效字串,預設null

Returns:

回傳排序後陣列或指標陣列

Type
Array

(static) asind(v) → {Number}

Description:
  • 輸入浮點數計算asin角度值

    v須為有效數字(isenum: 有限數字,或去頭尾空白後為十進位寫法之數字字串),其餘(Infinity、'Infinity'、'0x10'、'1e400'、'-'、''、null、包裝物件等)回傳null;v超出-1~1(定義域外)時依Math.asin回傳NaN。

    Unit Test: Github

Source:
Example
console.log(asind(0))
// => 0

console.log(asind(0.5))
// => 30.000000000000004

console.log(asind(0.7071067811865475))
// => 44.99999999999999

console.log(asind(0.8660254037844386))
// => 59.99999999999999

console.log(asind(1))
// => 90

console.log(asind(-0.5))
// => -30.000000000000004

console.log(asind(-0.7071067811865475))
// => -44.99999999999999

console.log(asind(-0.8660254037844386))
// => -59.99999999999999

console.log(asind(-1))
// => -90

console.log(asind(Infinity))
// => null

console.log(asind('0x10'))
// => null
Parameters:
Name Type Description
v Number | String

輸入數值,需為有效數字(數字或數字字串,定義見isenum,不收Infinity與'0x10'等),非有效數字時回傳null

Returns:

回傳asin角度值,v非有效數字時回傳null

Type
Number

(static) atan2d(x, y) → {Number}

Description:
  • 輸入浮點數x,y計算atan2角度值

    x與y須皆為有效數字(isenum: 有限數字,或去頭尾空白後為十進位寫法之數字字串),任一不是(Infinity、'Infinity'、'0x10'、'1e400'、'-'、''、null、包裝物件等)回傳null; 不再接受Infinity與-Infinity(舊版atan2d(1, Infinity)為90),需要極限值者請自行以90、-90代入。

    Unit Test: Github

Source:
Example
console.log(atan2d(1, 0))
// => 0

console.log(atan2d(1, 0.5))
// => 26.56505117707799

console.log(atan2d(1, 0.7071067811865475))
// => 35.264389682754654

console.log(atan2d(1, 0.8660254037844386))
// => 40.89339464913091

console.log(atan2d(1, 1))
// => 45

console.log(atan2d(1, 1.7320508075688767))
// => 59.99999999999999

console.log(atan2d(1, Infinity))
// => null (非有效數字;舊版為90)

console.log(atan2d(1, -0.5))
// => -26.56505117707799

console.log(atan2d(1, -0.7071067811865475))
// => -35.264389682754654

console.log(atan2d(1, -0.8660254037844386))
// => -40.89339464913091

console.log(atan2d(1, -1))
// => -45

console.log(atan2d(1, -1.7320508075688767))
// => -59.99999999999999

console.log(atan2d(1, -Infinity))
// => null (非有效數字;舊版為-90)

console.log(atan2d('0x10', 1))
// => null
Parameters:
Name Type Description
x Number | String

輸入點x座標,需為有效數字(數字或數字字串,定義見isenum,不收Infinity與'0x10'等),非有效數字時回傳null

y Number | String

輸入點y座標,需為有效數字(數字或數字字串,定義見isenum,不收Infinity與'0x10'等),非有效數字時回傳null

Returns:

回傳atan2角度值,x或y非有效數字時回傳null

Type
Number

(static) atand(v) → {Number}

Description:
  • 輸入浮點數計算atan角度值

    v須為有效數字(isenum: 有限數字,或去頭尾空白後為十進位寫法之數字字串),其餘(Infinity、'Infinity'、'0x10'、'1e400'、'-'、''、null、包裝物件等)回傳null; 不再接受Infinity與-Infinity(舊版atand(Infinity)為90),需要極限值者請自行以90、-90代入。

    Unit Test: Github

Source:
Example
console.log(atand(0))
// => 0

console.log(atand(0.5))
// => 26.56505117707799

console.log(atand(0.7071067811865475))
// => 35.264389682754654

console.log(atand(0.8660254037844386))
// => 40.89339464913091

console.log(atand(1))
// => 45

console.log(atand(1.7320508075688767))
// => 59.99999999999999

console.log(atand(Infinity))
// => null (非有效數字;舊版為90)

console.log(atand(-0.5))
// => -26.56505117707799

console.log(atand(-0.7071067811865475))
// => -35.264389682754654

console.log(atand(-0.8660254037844386))
// => -40.89339464913091

console.log(atand(-1))
// => -45

console.log(atand(-1.7320508075688767))
// => -59.99999999999999

console.log(atand(-Infinity))
// => null (非有效數字;舊版為-90)

console.log(atand('0x10'))
// => null
Parameters:
Name Type Description
v Number | String

輸入數值,需為有效數字(數字或數字字串,定義見isenum,不收Infinity與'0x10'等),非有效數字時回傳null

Returns:

回傳atan角度值,v非有效數字時回傳null

Type
Number

(static) attstr(optopt) → {Object}

Description:
  • 屬性字串處理

    各方法之輸入無效時回傳輸出型別之空值,不拋錯、不回原值(使用者2026-11-12,dspec〈輸入參數之檢測機制〉§11 Q1-c):parse之composItems非有效字串回傳[];join之arrItems非有效陣列回傳'';remove之composItems非有效字串、或removeItemOrId非字串回傳'',removeItemOrId為空字串代表無可移除而回傳原字串;add之composItems1或composItems2非字串回傳'',空字串為合法輸入(代表無屬性)

    Unit Test: Github

Source:
Example
let c
let c1
let c2
let r

let at = attstr({ uniqItems: true })

//parse
console.log('parse')

c = 'abc123'
r = at.parse(c)
console.log(r)
// => [ 'abc123' ]

c = 'abc123;abc123'
r = at.parse(c)
console.log(r)
// => [ 'abc123' ]

c = 'abc123;def456'
r = at.parse(c)
console.log(r)
// => [ 'abc123', 'def456' ]

c = 'abc@123'
r = at.parse(c)
console.log(r)
// => [ { item: 'abc@123', table: 'abc', id: '123' } ]

c = 'abc@123;abc@123'
r = at.parse(c)
console.log(r)
// => [ { item: 'abc@123', table: 'abc', id: '123' } ]

c = 'abc@123;def@456'
r = at.parse(c)
console.log(r)
// => [
//   { item: 'abc@123', table: 'abc', id: '123' },
//   { item: 'def@456', table: 'def', id: '456' }
// ]

c = ''
r = at.parse(c)
console.log(r)
// => []

//join
console.log('join')

c = ['abc123']
r = at.join(c)
console.log(r)
// => 'abc123'

c = ['abc123', 'def456']
r = at.join(c)
console.log(r)
// => 'abc123;def456'

c = ['abc@123']
r = at.join(c)
console.log(r)
// => 'abc@123'

c = ['abc@123', 'def@456']
r = at.join(c)
console.log(r)
// => 'abc@123;def@456'

c = [{ table: 'abc', id: '123' }, { table: 'def', id: '456' }]
r = at.join(c)
console.log(r)
// => 'abc@123;def@456'

c = []
r = at.join(c)
console.log(r)
// => ''

//add
console.log('add')

c1 = 'abc123'
c2 = 'def456'
r = at.add(c1, c2)
console.log(r)
// => abc123;def456

c1 = 'abc123'
c2 = 'def456;ghi789'
r = at.add(c1, c2)
console.log(r)
// => abc123;def456;ghi789

c1 = 'abc123'
c2 = 'abc123'
r = at.add(c1, c2)
console.log(r)
// => abc123

c1 = 'abc123'
c2 = 'abc123;def456'
r = at.add(c1, c2)
console.log(r)
// => abc123;def456

c1 = 'abc123;ghi789'
c2 = 'abc123;def456'
r = at.add(c1, c2)
console.log(r)
// => abc123;ghi789;def456

c1 = ''
c2 = 'abc123'
r = at.add(c1, c2)
console.log(r)
// => abc123

c1 = ''
c2 = 'abc123;def456'
r = at.add(c1, c2)
console.log(r)
// => abc123;def456

c1 = 'abc@123'
c2 = 'def@456'
r = at.add(c1, c2)
console.log(r)
// => abc@123;def@456

c1 = 'abc@123'
c2 = 'def@456;ghi@789'
r = at.add(c1, c2)
console.log(r)
// => abc@123;def@456;ghi@789

c1 = 'abc@123;ghi@789'
c2 = 'abc@123;def@456'
r = at.add(c1, c2)
console.log(r)
// => abc@123;ghi@789;def@456

c1 = ''
c2 = 'abc@123'
r = at.add(c1, c2)
console.log(r)
// => abc@123

c1 = ''
c2 = 'abc@123;def@456'
r = at.add(c1, c2)
console.log(r)
// => abc@123;def@456

//remove
console.log('remove')

c1 = 'abc123'
c2 = 'abc123'
r = at.remove(c1, c2)
console.log(r)
// => ''

c1 = 'abc123;def456'
c2 = 'abc123'
r = at.remove(c1, c2)
console.log(r)
// => def456

c1 = 'abc123'
c2 = 'def456'
r = at.remove(c1, c2)
console.log(r)
// => abc123

c1 = 'abc123'
c2 = 'ghi789;jkl012'
r = at.remove(c1, c2)
console.log(r)
// => abc123

c1 = 'abc123'
c2 = 'abc123;jkl012'
r = at.remove(c1, c2)
console.log(r)
// => ''

c1 = 'abc123;def456'
c2 = 'ghi789;jkl012'
r = at.remove(c1, c2)
console.log(r)
// => abc123;def456

c1 = 'abc123;def456'
c2 = 'def456;jkl012'
r = at.remove(c1, c2)
console.log(r)
// => abc123

c1 = ''
c2 = 'ghi789'
r = at.remove(c1, c2)
console.log(r)
// => ''

c1 = ''
c2 = 'ghi789;jkl012'
r = at.remove(c1, c2)
console.log(r)
// => ''

c1 = 'abc@123'
c2 = 'abc@123'
r = at.remove(c1, c2)
console.log(r)
// => ''

c1 = 'abc@123;def@456'
c2 = 'abc@123'
r = at.remove(c1, c2)
console.log(r)
// => def@456

c1 = 'abc@123'
c2 = 'def@456'
r = at.remove(c1, c2)
console.log(r)
// => abc@123

c1 = 'abc@123'
c2 = 'ghi@789;jkl@012'
r = at.remove(c1, c2)
console.log(r)
// => abc@123

c1 = 'abc@123'
c2 = 'abc@123;jkl@012'
r = at.remove(c1, c2)
console.log(r)
// => ''

c1 = 'abc@123;def@456'
c2 = 'ghi@789;jkl@012'
r = at.remove(c1, c2)
console.log(r)
// => abc@123;def@456

c1 = 'abc@123;def@456'
c2 = 'def@456;jkl@012'
r = at.remove(c1, c2)
console.log(r)
// => abc@123

c1 = ''
c2 = 'ghi@789'
r = at.remove(c1, c2)
console.log(r)
// => ''

c1 = ''
c2 = 'ghi@789;jkl@012'
r = at.remove(c1, c2)
console.log(r)
// => ''

let at2 = attstr({ uniqItems: true, dlmItem: ',', dlmSep: '|' })

c = 'x1|abc@123|def@456,x2|ghi@789'
r = at2.parse(c)
console.log(r)
// => [
//   { item: 'x1|abc@123|def@456', table: 'x1', id: ['abc@123','def@456'] },
//   { item: 'x2|ghi@789', table: 'x2', id: 'ghi@789' }
// ]

let at3 = attstr({ uniqItems: true, dlmItem: ',', dlmSep: '|', keyTable: 'name', keyId: 'emails' })

c = 'x1|abc@123|def@456,x2|ghi@789'
r = at3.parse(c)
console.log(r)
// => [
//   { item: 'x1|abc@123|def@456', name: 'x1', emails: ['abc@123','def@456'] },
//   { item: 'x2|ghi@789', name: 'x2', emails: 'ghi@789' }
// ]

let at4 = attstr({ uniqItems: false })

c = ['abc@123', 'abc@123', 'def@456']
r = at4.join(c)
console.log(r)
// => 'abc@123;abc@123;def@456'

c = [{ table: 'abc', id: '123' }, { table: 'def', id: '456' }, { table: 'def', id: '456' }]
r = at4.join(c)
console.log(r)
// => 'abc@123;def@456;def@456'


c1 = 'abc123;ghi789'
c2 = 'abc123;def456'
r = at4.add(c1, c2)
console.log(r)
// => abc123;ghi789;abc123;def456

c1 = 'abc@123;ghi@789'
c2 = 'abc@123;def@456'
r = at4.add(c1, c2)
console.log(r)
// => abc@123;ghi@789;abc@123;def@456
Parameters:
Name Type Attributes Default Description
opt Object <optional>
{}

輸入設定物件,預設{}

Properties
Name Type Attributes Default Description
uniqItems Boolean <optional>
false

輸入是否對屬性項目去重之布林值,非布林視為false,預設false

dlmItem String <optional>
';'

輸入屬性項目間之分隔字串,須為非空字串才採用,預設';'

dlmSep String <optional>
'@'

輸入單一屬性項目內表名與識別值間之分隔字串,須為非空字串才採用,預設'@'

keyTable String <optional>
'table'

輸入2p模式之屬性物件中存放表名之鍵名字串,須為非空字串才採用,預設'table'

keyId String <optional>
'id'

輸入2p模式之屬性物件中存放識別值之鍵名字串,須為非空字串才採用,預設'id'

mode String <optional>
'auto'

輸入預設處理模式字串,'1p'為屬性項目視為單一字串,'2p'為屬性項目由表名與識別值組成,非'1p'與'2p'者視為'auto';'auto'時parse依輸入字串、add依任一輸入字串、remove依removeItemOrId是否含dlmSep判定,join依首項是否同時含keyTable與keyId鍵判定;parse、join、remove、add各自可於最後一個參數opt.mode逐次覆寫,預設'auto'

Returns:

回傳attstr物件,提供parse、join、remove、add共4種處理函數

Type
Object

(static) b642obj(b64, optopt) → {*}

Description:
  • base64字串轉任意資料

    Unit Test: Github

Source:
Example
console.log(b642obj('eyJhIjoxfQ=='))
// => { a: 1 }

console.log(b642obj(NaN, { returnWithStateAndMsg: true }))
// => { state: 'error', msg: 'invalid b64: must be a string' }
Parameters:
Name Type Attributes Default Description
b64 String

輸入base64字串

opt Object <optional>
{}

輸入設定物件,預設{}

Properties
Name Type Attributes Default Description
returnWithStateAndMsg Boolean <optional>
false

輸入是否回傳含狀態與訊息物件布林值,若為true則回傳{ state, msg }物件,state為'success'或'error',msg於success時為回傳結果、於error時為錯誤訊息字串,預設false

Returns:

回傳任意物件,輸入非字串或解析失敗時回傳空物件;若opt.returnWithStateAndMsg為true則回傳{ state, msg }物件 失敗之辨識:預設模式於本函數所偵測之失敗(輸入無效或轉換失敗)時不拋錯而回傳空物件{},而空物件{}亦為合法輸入之結果(如b642obj('e30=')(即'{}'之base64)),故不可由回傳值判斷成敗;須辨識失敗時請設opt.returnWithStateAndMsg為true,以回傳之state === 'error'判定(只涵蓋本函數所偵測之失敗,msg為錯誤訊息)

Type
*

(static) b642str(b64, optopt) → {String|Object}

Description:
  • base64字串轉一般字串

    Unit Test: Github

Source:
Example
console.log(b642str('dGVzdOS4reaWhw=='))
// => 'test中文'
Parameters:
Name Type Attributes Default Description
b64 String

輸入base64字串

opt Object <optional>
{}

輸入設定物件,預設{}

Properties
Name Type Attributes Default Description
returnWithStateAndMsg Boolean <optional>
false

輸入是否回傳含狀態與訊息物件布林值,若為true則回傳{ state, msg }物件,state為'success'或'error',msg於success時為回傳結果、於error時為錯誤訊息字串,預設false

Returns:

回傳一般字串,輸入非有效字串或解碼失敗時回傳空字串;若opt.returnWithStateAndMsg為true則回傳{ state, msg }物件 失敗之辨識:預設模式於本函數所偵測之失敗(輸入無效或轉換失敗)時不拋錯而回傳空字串'';須可靠辨識失敗時請設opt.returnWithStateAndMsg為true,以回傳之state === 'error'判定(只涵蓋本函數所偵測之失敗,msg為錯誤訊息);注意:本函數不驗證base64格式,非base64字元於解碼時被略過,格式不合之輸入仍可能以success回傳解碼結果

Type
String | Object

(static) b642u16arr(b64, optopt) → {Uint16Array|Object}

Description:
  • base64字串轉Uint16Array

    以逐位元組(little-endian)方式解碼,為u16arr2b64之反向;不可經u8arr2u16arr轉換,該函數為逐元素轉換無法還原大於255之元素

    Unit Test: Github

Source:
Example
console.log(b642u16arr('CwBPAAYA'))
// => new Uint16Array([11, 79, 6])
Parameters:
Name Type Attributes Default Description
b64 String

輸入base64字串

opt Object <optional>
{}

輸入設定物件,預設{}

Properties
Name Type Attributes Default Description
returnWithStateAndMsg Boolean <optional>
false

輸入是否回傳含狀態與訊息物件布林值,若為true則回傳{ state, msg }物件,state為'success'或'error',msg於success時為回傳結果、於error時為錯誤訊息字串,預設false

Returns:

回傳Uint16Array,輸入非字串或解出之位元組長度非偶數(無法組成Uint16Array)時回傳空Uint16Array;若opt.returnWithStateAndMsg為true則回傳{ state, msg }物件 失敗之辨識:預設模式於本函數所偵測之失敗(輸入無效或轉換失敗)時不拋錯而回傳空Uint16Array(長度0),而空Uint16Array(長度0)亦為合法輸入之結果(如b642u16arr('')),故不可由回傳值判斷成敗;須辨識失敗時請設opt.returnWithStateAndMsg為true,以回傳之state === 'error'判定(只涵蓋本函數所偵測之失敗,msg為錯誤訊息)

Type
Uint16Array | Object

(static) b642u8arr(b64, optopt) → {Uint8Array|Object}

Description:
  • base64字串轉Uint8Array

    Unit Test: Github

Source:
Example
console.log(b642u8arr('AQItAA=='))
// => new Uint8Array([1, 2.3, '45', 'abc'])
Parameters:
Name Type Attributes Default Description
b64 String

輸入base64字串

opt Object <optional>
{}

輸入設定物件,預設{}

Properties
Name Type Attributes Default Description
returnWithStateAndMsg Boolean <optional>
false

輸入是否回傳含狀態與訊息物件布林值,若為true則回傳{ state, msg }物件,state為'success'或'error',msg於success時為回傳結果、於error時為錯誤訊息字串,預設false

Returns:

回傳Uint8Array,輸入非字串或非合法base64時回傳空Uint8Array;若opt.returnWithStateAndMsg為true則回傳{ state, msg }物件 失敗之辨識:預設模式於本函數所偵測之失敗(輸入無效或轉換失敗)時不拋錯而回傳空Uint8Array(長度0),而空Uint8Array(長度0)亦為合法輸入之結果(如b642u8arr('')),故不可由回傳值判斷成敗;須辨識失敗時請設opt.returnWithStateAndMsg為true,以回傳之state === 'error'判定(只涵蓋本函數所偵測之失敗,msg為錯誤訊息)

Type
Uint8Array | Object

(static) binstr(s, keys, modeopt) → {Boolean}

Description:
  • 判斷字串s是否「任一出現於、全部包含於」字串陣列keys內元素

    Unit Test: Github

Source:
Example
console.log(binstr('1.25abc', 'ab'))
// => true
Parameters:
Name Type Attributes Default Description
s String

輸入要判斷的字串

keys Array | String

輸入字串陣列或字串,須為非空字串,或內含元素皆為非空字串之非空陣列,否則回傳false;單一空元素之陣列([null]、['']、[{}])視為一個無效元素(非有效字串)而回傳false,與[null, null]相同,不被當成空陣列

mode String <optional>
'anyone'

輸入模式字串,可選'anyone'與'all',其他值(含null、數字、布林、物件、陣列、包裝物件、不在可選集合之字串)視為未給而改用預設'anyone',不報錯,預設為'anyone'

Returns:

回傳判斷布林值

Type
Boolean

(static) blob2ab(bb) → {Promise}

Description:
  • 前端Blob或input檔案物件轉ArrayBuffer資料陣列

    Unit Test: Github

Source:
Example
need test in browser

let bb = new Blob([new Uint8Array([66, 97, 115])])
blob2ab(b)
    .then(function(ab){
        console.log(ab)
        // => ArrayBuffer(3) {
        //     [[Int8Array]]: Int8Array(3) [66, 97, 115]
        //     [[Uint8Array]]: Uint8Array(3) [66, 97, 115]
        //     byteLength: 3
        // }
    })
Parameters:
Name Type Description
bb Blob | File

輸入Blob或File

Returns:

回傳Promise,resolve回傳Blob或File的ArrayBuffer資料陣列,reject回傳錯誤訊息

Type
Promise

(static) blob2b64(bb) → {Promise}

Description:
  • 前端Blob或input檔案物件轉Base64字串

    Unit Test: Github

Source:
Example
need test in browser

let b64 = 'YWJj5ris6Kmm'
let u8a = b642u8arr(b64)
let bb = new Blob([u8a])
blob2b64(bb)
    .then(function(b64Out){
        console.log(b64Out)
        // => data:application/octet-stream;base64,YWJj5ris6Kmm
    })
Parameters:
Name Type Description
bb Blob | File

輸入Blob或File

Returns:

回傳Promise,resolve回傳Blob或File的Base64字串,reject回傳錯誤訊息

Type
Promise

(static) blob2str(bb) → {Promise}

Description:
  • 前端Blob或input檔案物件轉字串

    Unit Test: Github

Source:
Example
need test in browser

let strIn = 'abc測試'
let b64 = str2b64(strIn)
let u8a = b642u8arr(b64)
let bb = new Blob([u8a])
blob2str(bb)
    .then(function(strOut){
        console.log(strOut)
        // => abc測試
    })
Parameters:
Name Type Description
bb Blob | File

輸入Blob或File

Returns:

回傳Promise,resolve回傳Blob或File的字串,reject回傳錯誤訊息

Type
Promise

(static) blob2u8arr(bb) → {Promise}

Description:
  • 前端Blob或input檔案物件轉Uint8Array資料陣列

    Unit Test: Github

Source:
Example
need test in browser

let u8aIn = new Uint8Array([97, 98, 99, 230, 184, 172, 232, 169, 166])
let bb = new Blob([u8aIn])
blob2u8arr(bb)
    .then(function(u8aOut){
        console.log(u8aOut)
        // => Uint8Array(9) [97, 98, 99, 230, 184, 172, 232, 169, 166]
    })
Parameters:
Name Type Description
bb Blob | File

輸入Blob或File

Returns:

回傳Promise,resolve回傳Blob或File的Uint8Array資料陣列,reject回傳錯誤訊息

Type
Promise

(static) blobs2b64s(bbs) → {Promise}

Description:
  • 前端Blob或input檔案物件陣列,逐一轉為各檔案之Base64資料

    Unit Test: Github

Source:
Example
need test in browser

let b64 = 'YWJj5ris6Kmm'
let u8a = b642u8arr(b64)
let bb = new Blob([u8a])
let bbs = [bb]
blobs2b64s(bbs)
    .then(function(b64){
        console.log(b64)
        // => ["data:application/octet-stream;base64,YWJj5ris6Kmm"]
    })
Parameters:
Name Type Description
bbs Blob | File

輸入Blob或File陣列

Returns:

回傳Promise,resolve回傳各Blob或File的Base64資料,reject回傳錯誤訊息

Type
Promise

(static) blobs2u8arrs(bbs) → {Promise}

Description:
  • 前端Blob或input檔案物件陣列,逐一轉為各檔案之Uint8Array資料陣列

    Unit Test: Github

Source:
Example
need test in browser

let u8a = new Uint8Array([97, 98, 99, 230, 184, 172, 232, 169, 166])
let bb = new Blob([u8a])
let bbs = [bb]
blobs2u8arrs(bbs)
    .then(function(u8as){
        console.log(u8as)
        // => [Uint8Array(9)]
        //      0: Uint8Array(9) [97, 98, 99, 230, 184, 172, 232, 169, 166]
        //      length: 1
    })
Parameters:
Name Type Description
bbs Blob | File

輸入Blob或File陣列

Returns:

回傳Promise,resolve回傳各Blob或File的Uint8Array資料陣列,reject回傳錯誤訊息

Type
Promise

(static) bodyLog(…arguments)

Description:
  • 前端顯示log訊息,預設插入至body

    歸DOM類(C18):無document(非瀏覽器環境)或取不到body元素時不動作、不拋錯、不輸出console,回傳undefined

    Unit Test: Github

Source:
Example
bodyLog('show訊息')
// => 由html顯示'show訊息'

bodyLog('a', 123, { x: 1 })
// => 由html顯示'a, 123, {"x":1}'
Parameters:
Name Type Attributes Description
arguments * <repeatable>

輸入不定個數之任意資料(以arguments讀取,各項經o2j轉成字串後以', '串接,再經htmlEncode跳脫後顯示),未給任何引數時仍顯示一行空log

(static) browserView(data, type)

Description:
  • 前端瀏覽器以分頁開啟指定數據如文字、圖片、影片、pdf等

    以data與type建立Blob、經URL.createObjectURL取得同源之Blob網址後以window.open開新分頁顯示,開啟後延遲60秒以URL.revokeObjectURL釋放該網址(理由: 新分頁載入Blob網址為非同步,立即釋放可能使新分頁載入失敗;不釋放則Blob佔用記憶體至本頁關閉。已載入之分頁內容不受釋放影響,但釋放後於該分頁重新整理、或內建檢視器(如PDF檢視器)之另存或下載可能失敗)。釋放為盡力而為: 執行環境無URL.revokeObjectURL或其拋錯時忽略(不影響已開啟之分頁),該網址佔用至本頁關閉。

    失敗一律同步拋出Error(訊息不含輸入值、不外洩內部錯誤):

    1. 輸入檢查先於建立Blob與開分頁: data須為原始字串(可為空字串)、Blob(含File)、ArrayBuffer或ArrayBuffer之檢視(如Uint8Array、DataView),以內部槽判定(不採可偽裝之Symbol.toStringTag、不呼叫輸入之方法或存取器),包裝物件new String、SharedArrayBuffer與以其為底之檢視、已分離(detached)之ArrayBuffer與以其為底之檢視皆無效(無法建立Blob),否則拋出Error('invalid data: must be a string, Blob, ArrayBuffer or ArrayBufferView');
    2. type須為非空之原始字串(包裝物件new String無效),否則拋出Error('invalid type: must be a non-empty string');
    3. 環境檢查亦先於建立Blob: 無window或document(如nodejs、Web Worker)拋出Error('window and document are required'),無Blob拋出Error('Blob is not supported'),無URL.createObjectURL(如IE11以前)拋出Error('URL.createObjectURL is not supported'); 通過上列檢查之data仍無法建立Blob者(執行環境特有之限制)亦拋出Error('invalid data: must be a string, Blob, ArrayBuffer or ArrayBufferView'),不外洩原生錯誤;
    4. 建立Blob後之執行期失敗: URL.createObjectURL拋錯拋出Error('can not create object URL');window.open拋錯拋出Error('can not open window'),window.open回傳null(被瀏覽器之彈出視窗攔截)拋出Error('window.open was blocked'),此二者發生於開分頁之嘗試,拋出前先立即釋放已建立之Blob網址。window.open須於使用者操作之事件(如click)中呼叫,否則可能被瀏覽器攔截。

    安全注意: 可夾帶腳本之類型(text/html、image/svg+xml、application/xhtml+xml、text/xml、application/xml等)以同源Blob開啟時,其內含之腳本以本系統之來源(origin)執行,可存取本系統之Cookie、localStorage與同源API,且新分頁之window.opener指向本頁(以window.open開啟,真Chromium實測,與openLink之新分頁opener為null不同)。type由呼叫端決定,本函數不檢查data內容亦不限制type;不得以未經檢查之使用者上傳資料搭配上述類型呼叫(展示使用者上傳之資料時,請只允許text/plain、application/pdf、image/png等不執行腳本之類型,或先經檢查與清理)。

    Unit Test: Github

Source:
Example
need test in browser

let text = 'abc'
browserView(text, 'text/plain')

let u8a = new Uint8Array([66, 97, 115])
browserView(u8a, 'application/pdf')
Parameters:
Name Type Description
data String | Blob | ArrayBuffer | Uint8Array

輸入數據,可為原始字串、Blob、ArrayBuffer或ArrayBuffer之檢視(如Uint8Array),共享或已分離之緩衝區無效

type String

輸入數據MIME Type原始字串,例如'application/pdf'或'text/plain'等,詳見[https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types],可夾帶腳本之類型見上方安全注意

Throws:

data或type無效、或無法開啟分頁時拋出Error,見上方說明

Type
Error

(static) browserViewFromBlob(bb, type)

Description:
  • 前端瀏覽器以分頁開啟blob數據如文字、圖片、影片、pdf等

    交由browserView開啟(開啟、延遲釋放、失敗與可夾帶腳本之類型之安全注意見browserView;type由呼叫端決定,不得以未經檢查之使用者上傳資料搭配text/html、image/svg+xml等可夾帶腳本之類型呼叫)。 bb須為Blob(含File與其子類;以內部槽判定,不採可偽裝之Symbol.toStringTag),否則同步拋出Error('invalid bb: must be a Blob');type須為非空之原始字串,否則同步拋出Error('invalid type: must be a non-empty string');皆不開分頁。無法開啟分頁時拋出之Error同browserView。

    Unit Test: Github

Source:
Example
need test in browser

let u8a = new Uint8Array([66, 97, 115])
let bb = new Blob([u8a])
browserViewFromBlob(bb, 'application/pdf')
Parameters:
Name Type Description
bb Blob

輸入blob數據

type String

輸入數據MIME Type字串,例如'application/pdf'或'text/plain'等,詳見[https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types]

Throws:

bb非Blob、type非非空字串、或無法開啟分頁時拋出Error

Type
Error

(static) browserViewFromText(text)

Description:
  • 前端瀏覽器以分頁開啟文字資料

    以type為'text/plain'交由browserView開啟(開啟、延遲釋放與失敗之說明見browserView)。 text須為原始字串(可為空字串;包裝物件new String無效,規格§3.4 S2),否則同步拋出Error('invalid text: must be a string')且不開分頁;無法開啟分頁時拋出之Error同browserView。

    Unit Test: Github

Source:
Example
need test in browser

let text = 'abc'
browserViewFromText(text)
Parameters:
Name Type Description
text String

輸入文字字串

Throws:

text非字串、或無法開啟分頁時拋出Error

Type
Error

(static) browserViewFromU8arr(u8a, type)

Description:
  • 前端瀏覽器以分頁開啟Uint8Array數據如文字、圖片、影片、pdf等

    交由browserView開啟(開啟、延遲釋放、失敗與可夾帶腳本之類型之安全注意見browserView;type由呼叫端決定,不得以未經檢查之使用者上傳資料搭配text/html、image/svg+xml等可夾帶腳本之類型呼叫)。 u8a須為Uint8Array(以內部槽判定,不採可偽裝之Symbol.toStringTag;底層為SharedArrayBuffer或已分離之緩衝區者無法建立Blob,亦無效),否則同步拋出Error('invalid u8a: must be a Uint8Array');type須為非空之原始字串,否則同步拋出Error('invalid type: must be a non-empty string');皆不開分頁。無法開啟分頁時拋出之Error同browserView。

    Unit Test: Github

Source:
Example
need test in browser

let u8a = new Uint8Array([66, 97, 115])
browserViewFromU8arr(u8a, 'application/pdf')
Parameters:
Name Type Description
u8a Uint8Array

輸入Uint8Array數據

type String

輸入數據MIME Type字串,例如'application/pdf'或'text/plain'等,詳見[https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types]

Throws:

u8a非Uint8Array、type非非空字串、或無法開啟分頁時拋出Error

Type
Error

(static) bs2u8arr(str, optopt) → {Uint8Array|Object}

Description:
  • BinaryString轉Uint8Array,BinaryString為UTF-16編碼

    Unit Test: Github

Source:
Example
console.log(bs2u8arr('abc'))
// => new Uint8Array([97, 98, 99])
Parameters:
Name Type Attributes Default Description
str String

輸入BinaryString字串

opt Object <optional>
{}

輸入設定物件,預設{}

Properties
Name Type Attributes Default Description
returnWithStateAndMsg Boolean <optional>
false

輸入是否回傳含狀態與訊息物件布林值,若為true則回傳{ state, msg }物件,state為'success'或'error',msg於success時為回傳結果、於error時為錯誤訊息字串,預設false

Returns:

回傳Uint8Array資料,輸入非有效字串時回傳空Uint8Array;若opt.returnWithStateAndMsg為true則回傳{ state, msg }物件 失敗之辨識:預設模式於本函數所偵測之失敗(輸入無效或轉換失敗)時不拋錯而回傳空Uint8Array(長度0);須可靠辨識失敗時請設opt.returnWithStateAndMsg為true,以回傳之state === 'error'判定(只涵蓋本函數所偵測之失敗,msg為錯誤訊息)

Type
Uint8Array | Object

(static) bufRead(buffer, offset, isBE, mLen, nBytes) → {Number}

Description:
  • 讀取Uint8Array(Nodejs,Browser)或Buffer(Nodejs)資料

    全部參數皆為必須參數,數值參數須為有效整數(iseint,數字字串亦可,去頭尾空白後取值);offset須為索引(0~4294967294),mLen與nBytes須為個數(1~4294967295),且須滿足offset+nBytes不大於buffer長度、mLen小於nBytes8-1(至少留1位元給指數)且不大於52(JS數值尾數位數,超過者讀回失真)、指數位元數eLen(nBytes8-mLen-1)不大於30(內部以32位元整數位移運算,31以上位移溢位而數值失真),否則(含越界、負數、Infinity、小數)回傳null;標準浮點數為(mLen 23, nBytes 4)與(mLen 52, nBytes 8)

    Fork: buffer_ieee754

    Unit Test: Github

Source:
Example
let offset = 0
let isBE = true
let mLen = 52
let nBytes = 8
let b = new Uint8Array([66, 117, 16, 240, 246, 48, 64, 0]) //1447656645380
let j = bufRead(b, offset, isBE, mLen, nBytes)
console.log(j)
// => 1447656645380
Parameters:
Name Type Description
buffer Uint8Array | Buffer

輸入Uint8Array(Nodejs,Browser)或Buffer(Nodejs)資料

offset Integer | String

輸入平移整數,須為有效整數且為索引(0~4294967294,數字字串亦可),且offset+nBytes不大於buffer長度,否則回傳null

isBE Boolean

輸入是否為大端序Big-Endian

mLen Integer | String

輸入有效位數整數,須為有效整數且為1~52(數字字串亦可),且小於nBytes8-1、使指數位元數nBytes8-mLen-1不大於30,否則回傳null

nBytes Integer | String

輸入使用位元組整數,須為有效整數且為1~4294967295(數字字串亦可),且使指數位元數nBytes*8-mLen-1不大於30,否則回傳null

Returns:

回傳數字,輸入無效回傳null

Type
Number

(static) bufReadDbl(buffer, offsetopt, isBEopt, mLenopt, nBytesopt) → {Number}

Description:
  • 讀取Uint8Array(Nodejs,Browser)或Buffer(Nodejs)內的浮點數資料 參數規則同bufRead:offset、mLen、nBytes須為有效整數且須滿足offset+nBytes不大於buffer長度、mLen不大於52、指數位元數nBytes*8-mLen-1介於1至30,否則回傳null

    Unit Test: Github

Source:
Example
let b = new Uint8Array([66, 117, 16, 240, 246, 48, 64, 0]) //1447656645380
let j = bufReadDbl(b)
console.log(j)
// => 1447656645380
Parameters:
Name Type Attributes Default Description
buffer Uint8Array | Buffer

輸入Uint8Array(Nodejs,Browser)或Buffer(Nodejs)資料

offset Integer | String <optional>
0

輸入平移整數,預設0

isBE Boolean <optional>
true

輸入是否為大端序Big-Endian,預設true

mLen Integer | String <optional>
52

輸入有效位數整數,預設52

nBytes Integer | String <optional>
8

輸入使用位元組整數,預設8

Returns:

回傳數字,輸入無效回傳null

Type
Number

(static) bufWrite(value, buffer, offset, isBE, mLen, nBytes) → {Boolean|null}

Description:
  • 寫入Uint8Array(Nodejs,Browser)或Buffer(Nodejs)資料

    value為資料值,照IEEE754原樣編碼:型別為number者(含±Infinity、NaN、-0)寫出正確之位元樣式(與Node之Buffer.writeFloatLE/writeDoubleLE一致,NaN為quiet NaN);字串只收十進位有效數字(isenum,去頭尾空白後取值),'0x10'、'Infinity'、'NaN'、''等不收;其餘型別(布林、null、包裝物件、BigInt等)不收 其餘參數皆為必須參數,數值參數須為有效整數(iseint,數字字串亦可,去頭尾空白後取值);offset須為索引(0~4294967294),mLen與nBytes須為個數(1~4294967295),且須滿足offset+nBytes不大於buffer長度、mLen小於nBytes8-1(至少留1位元給指數)且不大於52(JS數值尾數位數,超過者無法精確編碼)、指數位元數eLen(nBytes8-mLen-1)不大於30(內部以32位元整數位移運算,31以上位移溢位而數值失真),標準浮點數為(mLen 23, nBytes 4)與(mLen 52, nBytes 8) 成功回傳true,任一輸入無效回傳null且不寫入buffer

    Fork: buffer_ieee754

    Unit Test: Github

Source:
Example
let offset = 0
let isBE = true
let mLen = 52
let nBytes = 8

let i = 1447656645380 //new Uint8Array([66, 117, 16, 240, 246, 48, 64, 0])
let b = Buffer.alloc(8)
let r = bufWrite(i, b, offset, isBE, mLen, nBytes)
console.log(r)
// => true
console.log(b)
// >= <Buffer 42 75 10 f0 f6 30 40 00>
console.log(new Uint8Array(b))
// => Uint8Array [66, 117, 16, 240, 246, 48, 64, 0]

bufWrite(Infinity, b, offset, isBE, mLen, nBytes)
console.log(b)
// >= <Buffer 7f f0 00 00 00 00 00 00>

r = bufWrite('0x10', b, offset, isBE, mLen, nBytes)
console.log(r)
// => null
Parameters:
Name Type Description
value Number | String

輸入要寫入之數字,number型別照IEEE754原樣編碼(含±Infinity、NaN),字串只收十進位有效數字

buffer Uint8Array | Buffer

輸入被寫入的Uint8Array(Nodejs,Browser)或Buffer(Nodejs)資料

offset Integer | String

輸入平移整數,須為有效整數且為索引(0~4294967294,數字字串亦可),且offset+nBytes不大於buffer長度,否則回傳null

isBE Boolean

輸入是否為大端序Big-Endian

mLen Integer | String

輸入有效位數整數,須為有效整數且為1~52(數字字串亦可),且小於nBytes8-1、使指數位元數nBytes8-mLen-1不大於30,否則回傳null

nBytes Integer | String

輸入使用位元組整數,須為有效整數且為1~4294967295(數字字串亦可),且使指數位元數nBytes*8-mLen-1不大於30,否則回傳null

Returns:

回傳寫入成功為true,輸入無效為null

Type
Boolean | null

(static) bufWriteDbl(value, buffer, offsetopt, isBEopt, mLenopt, nBytesopt) → {Boolean|null}

Description:
  • 寫入Uint8Array(Nodejs,Browser)或Buffer(Nodejs)內的浮點數資料,需先依照nBytes宣告Uint8Array或Buffer空間 參數規則同bufWrite:value照IEEE754原樣編碼(含±Infinity、NaN,字串只收十進位有效數字),offset、mLen、nBytes須為有效整數且須滿足offset+nBytes不大於buffer長度、mLen不大於52、指數位元數nBytes*8-mLen-1介於1至30;成功回傳true,任一輸入無效回傳null且不寫入

    Unit Test: Github

Source:
Example
let i = 1447656645380 //new Uint8Array([66, 117, 16, 240, 246, 48, 64, 0])
let b = Buffer.alloc(8)
bufWriteDbl(i, b)
// => true
console.log(b)
// >= <Buffer 42 75 10 f0 f6 30 40 00>
console.log(new Uint8Array(b))
// => Uint8Array [66, 117, 16, 240, 246, 48, 64, 0]
Parameters:
Name Type Attributes Default Description
value Number | String

輸入要寫入之數字,number型別照IEEE754原樣編碼(含±Infinity、NaN),字串只收十進位有效數字

buffer Uint8Array | Buffer

輸入Uint8Array(Nodejs,Browser)或Buffer(Nodejs)資料

offset Integer | String <optional>
0

輸入平移整數,預設0

isBE Boolean <optional>
true

輸入是否為大端序Big-Endian,預設true

mLen Integer | String <optional>
52

輸入有效位數整數,預設52

nBytes Integer | String <optional>
8

輸入使用位元組整數,預設8

Returns:

回傳寫入成功為true,輸入無效為null

Type
Boolean | null

(static) cache(optopt) → {Object}

Description:
  • 非同步函數快取,通過指定key代表函數與其輸入、代為執行與快取。快取可設定失效時間,超過失效時間則重新執行與再更新快取

    Unit Test: Github

Source:
Example
async function topAsync() {

    function test1() {
        return new Promise((resolve, reject) => {
            let ms = []

            let oc = cache()

            // oc.on('message', function(msg) {
            //     console.log('message', msg)
            // })
            // oc.on('error', function(msg) {
            //     console.log('error', msg)
            // })

            let i = 0
            let j = 0
            function fun(v1, v2) {
                i++
                console.log('call fun, count=' + i)
                ms.push('call fun, count=' + i)
                return new Promise(function(resolve, reject) {
                    setTimeout(function() {
                        j++
                        ms.push(v1 + '|' + v2 + ', count=' + j)
                        resolve(v1 + '|' + v2 + ', count=' + j)
                    }, 300)
                })
            }

            oc.set('fun', { fun, inputs: ['inp1', 'inp2'], timeExpired: 1200 }) //快取1200ms, 但第1次執行就需要300ms, 故執行完畢後只會再保留800ms
            setTimeout(function() {
                //第1次呼叫(1ms), 此時沒有快取只能執行取值, 執行300ms後回應, 會取得第1次結果(count=1)
                oc.get('fun')
                    .then(function(msg) {
                        console.log('fun 1st', msg)
                        ms.push('fun 1st', msg)
                    })
                    .catch(function(err) {
                        console.log('fun 1st error', err)
                        ms.push('fun 1st error', String(err))
                    })
            }, 1)
            setTimeout(function() {
                //第2次呼叫(50ms), 此時第1次呼叫還沒完成(要到300ms), 故get會共用執行中的promise等待, 於第1次執行完畢(300ms)時一併取得第1次結果(count=1)
                oc.get('fun')
                    .then(function(msg) {
                        console.log('fun 2nd', msg)
                        ms.push('fun 2nd', msg)
                    })
                    .catch(function(err) {
                        console.log('fun 2nd error', err)
                        ms.push('fun 2nd error', String(err))
                    })
            }, 50)
            setTimeout(function() {
                //第3次呼叫(250ms), 此時第1次呼叫還沒完成(要到300ms), 同第2次呼叫共用執行中的promise等待, 於300ms時一併取得第1次結果(count=1)
                oc.get('fun')
                    .then(function(msg) {
                        console.log('fun 3rd', msg)
                        ms.push('fun 3rd', msg)
                    })
                    .catch(function(err) {
                        console.log('fun 3rd error', err)
                        ms.push('fun 3rd error', String(err))
                    })
            }, 250)
            setTimeout(function() {
                //第4次呼叫(500ms), 此時第1次呼叫已結束(300ms), 且第1次快取(count=1)未過期(要到1200ms), 故get可拿到第1次計算的快取(count=1)
                oc.get('fun')
                    .then(function(msg) {
                        console.log('fun 4th', msg)
                        ms.push('fun 4th', msg)
                    })
                    .catch(function(err) {
                        console.log('fun 4th error', err)
                        ms.push('fun 4th error', String(err))
                    })
            }, 500)
            setTimeout(function() {
                //第5次呼叫(1300ms), 此時第1次快取(count=1)已過期(1200ms), 故重新執行取值(1300~1600ms執行, 2500ms過期), 於1600ms取得第2次結果(count=2)
                oc.get('fun')
                    .then(function(msg) {
                        console.log('fun 5th', msg)
                        ms.push('fun 5th', msg)
                    })
                    .catch(function(err) {
                        console.log('fun 5th error', err)
                        ms.push('fun 5th error', String(err))
                    })
            }, 1300)
            setTimeout(function() {
                //第6次呼叫(1600ms), 此時第2次執行剛好結束(1600ms), 若尚未結束則共用執行中的promise等待, 若已結束則直接拿快取, 皆會取得第2次結果(count=2)
                oc.get('fun')
                    .then(function(msg) {
                        console.log('fun 6th', msg)
                        ms.push('fun 6th', msg)
                    })
                    .catch(function(err) {
                        console.log('fun 6th error', err)
                        ms.push('fun 6th error', String(err))
                    })
            }, 1600)

            setTimeout(function() {
                resolve(ms)
            }, 2400)

        })
    }
    console.log('test1')
    let r1 = await test1()
    console.log(JSON.stringify(r1))
    // test1
    // call fun, count=1
    // fun 1st inp1|inp2, count=1
    // fun 2nd inp1|inp2, count=1
    // fun 3rd inp1|inp2, count=1
    // fun 4th inp1|inp2, count=1
    // call fun, count=2
    // fun 5th inp1|inp2, count=2
    // fun 6th inp1|inp2, count=2
    // ["call fun, count=1","inp1|inp2, count=1","fun 1st","inp1|inp2, count=1","fun 2nd","inp1|inp2, count=1","fun 3rd","inp1|inp2, count=1","fun 4th","inp1|inp2, count=1","call fun, count=2","inp1|inp2, count=2","fun 5th","inp1|inp2, count=2","fun 6th","inp1|inp2, count=2"]

    function test2() {
        return new Promise((resolve, reject) => {
            let ms = []

            let oc = cache()

            // oc.on('message', function(msg) {
            //     console.log('message', msg)
            // })
            // oc.on('error', function(msg) {
            //     console.log('error', msg)
            // })

            let i = 0
            let j = 0
            function fun(v1, v2) {
                i++
                console.log('call fun, count=' + i)
                ms.push('call fun, count=' + i)
                return new Promise(function(resolve, reject) {
                    setTimeout(function() {
                        j++
                        ms.push(v1 + '|' + v2 + ', count=' + j)
                        resolve(v1 + '|' + v2 + ', count=' + j)
                    }, 300)
                })
            }

            //首次getProxy即註冊並執行取值(0~300ms), 快取1200ms, 但第1次執行就需要300ms, 故執行完畢後只會再保留800ms
            //因useCacheWhenError預設false, 函數執行失敗時get與getProxy會reject, 故此種不取值之呼叫仍須接catch, 否則會產生unhandled rejection
            oc.getProxy('fun', { fun, inputs: ['inp1', 'inp2'], timeExpired: 1200 })
                .catch(function(err) {
                    console.log('getProxy error', err)
                })
            setTimeout(function() {
                //第1次呼叫(1ms), 此時首次getProxy執行中, 會共用執行中的promise等待, 於300ms取得第1次結果(count=1)
                oc.getProxy('fun', { fun, inputs: ['inp1', 'inp2'], timeExpired: 1200 })
                    .then(function(msg) {
                        console.log('fun 1st', msg)
                        ms.push('fun 1st', msg)
                    })
                    .catch(function(err) {
                        console.log('fun 1st error', err)
                        ms.push('fun 1st error', String(err))
                    })
            }, 1)
            setTimeout(function() {
                //第2次呼叫(100ms), 此時執行中, 同第1次呼叫共用執行中的promise等待, 於300ms取得第1次結果(count=1)
                oc.getProxy('fun', { fun, inputs: ['inp1', 'inp2'], timeExpired: 1200 })
                    .then(function(msg) {
                        console.log('fun 2nd', msg)
                        ms.push('fun 2nd', msg)
                    })
                    .catch(function(err) {
                        console.log('fun 2nd error', err)
                        ms.push('fun 2nd error', String(err))
                    })
            }, 100)
            setTimeout(function() {
                //第3次呼叫(500ms), 此時已有快取, 直接取得第1次結果(count=1)
                oc.getProxy('fun', { fun, inputs: ['inp1', 'inp2'], timeExpired: 1200 })
                    .then(function(msg) {
                        console.log('fun 3rd', msg)
                        ms.push('fun 3rd', msg)
                    })
                    .catch(function(err) {
                        console.log('fun 3rd error', err)
                        ms.push('fun 3rd error', String(err))
                    })
            }, 500)
            setTimeout(function() {
                //第4次呼叫(1300ms), 此時第1次快取(count=1)已失效(1200ms), 會重新呼叫函數取值(1300~1600ms), 取得第2次結果(count=2)
                oc.getProxy('fun', { fun, inputs: ['inp1', 'inp2'], timeExpired: 1200 })
                    .then(function(msg) {
                        console.log('fun 4th', msg)
                        ms.push('fun 4th', msg)
                    })
                    .catch(function(err) {
                        console.log('fun 4th error', err)
                        ms.push('fun 4th error', String(err))
                    })
            }, 1300)

            setTimeout(function() {
                resolve(ms)
            }, 1700)

        })
    }
    console.log('test2')
    let r2 = await test2()
    console.log(JSON.stringify(r2))
    // test2
    // call fun, count=1
    // fun 1st inp1|inp2, count=1
    // fun 2nd inp1|inp2, count=1
    // fun 3rd inp1|inp2, count=1
    // call fun, count=2
    // fun 4th inp1|inp2, count=2
    // ["call fun, count=1","inp1|inp2, count=1","fun 1st","inp1|inp2, count=1","fun 2nd","inp1|inp2, count=1","fun 3rd","inp1|inp2, count=1","call fun, count=2","inp1|inp2, count=2","fun 4th","inp1|inp2, count=2"]

    function test3() {
        return new Promise((resolve, reject) => {
            let ms = []

            let oc = cache()

            // oc.on('message', function(msg) {
            //     console.log('message', msg)
            // })
            // oc.on('error', function(msg) {
            //     console.log('error', msg)
            // })

            let i = 0
            let j = 0
            function fun(v1, v2) {
                i++
                console.log('call fun, count=' + i)
                ms.push('call fun, count=' + i)
                return new Promise(function(resolve, reject) {
                    setTimeout(function() {
                        j++
                        ms.push(v1 + '|' + v2 + ', count=' + j)
                        resolve(v1 + '|' + v2 + ', count=' + j)
                    }, 300)
                })
            }

            //首次getProxy即註冊並執行取值(0~300ms), 快取1500ms, 但第1次執行就需要300ms, 故執行完畢後只會再保留1200ms
            //因useCacheWhenError預設false, 函數執行失敗時get與getProxy會reject, 故此種不取值之呼叫仍須接catch, 否則會產生unhandled rejection
            oc.getProxy('fun', { fun, inputs: ['inp1', 'inp2'], timeExpired: 1500 })
                .catch(function(err) {
                    console.log('getProxy error', err)
                })
            setTimeout(function() {
                //第1次呼叫(延遲1ms), 此時首次getProxy執行中, 會共用執行中的promise等待, 於300ms取得第1次結果(count=1)
                oc.getProxy('fun', { fun, inputs: ['inp1', 'inp2'], timeExpired: 1500 })
                    .then(function(msg) {
                        console.log('fun 1st', msg)
                        ms.push('fun 1st', msg)
                    })
                    .catch(function(err) {
                        console.log('fun 1st error', err)
                        ms.push('fun 1st error', String(err))
                    })
            }, 1)
            setTimeout(function() {
                //第2次呼叫(延遲200ms), 此時執行中, 同第1次呼叫共用執行中的promise等待, 於300ms取得第1次結果(count=1), 早於被強制更新(1100ms)
                oc.getProxy('fun', { fun, inputs: ['inp1', 'inp2'], timeExpired: 1500 })
                    .then(function(msg) {
                        console.log('fun 2nd', msg)
                        ms.push('fun 2nd', msg)
                    })
                    .catch(function(err) {
                        console.log('fun 2nd error', err)
                        ms.push('fun 2nd error', String(err))
                    })
            }, 200)
            setTimeout(function() {
                //第3次呼叫(500ms), 此時已有快取, 直接取得第1次結果(count=1)
                oc.getProxy('fun', { fun, inputs: ['inp1', 'inp2'], timeExpired: 1500 })
                    .then(function(msg) {
                        console.log('fun 3rd', msg)
                        ms.push('fun 3rd', msg)
                    })
                    .catch(function(err) {
                        console.log('fun 3rd error', err)
                        ms.push('fun 3rd error', String(err))
                    })
            }, 500)
            setTimeout(function() {
                //更新快取值(延遲1100ms), 快取值為abc, 快取時間也被更新至此時, 故會重新計算1500ms才會失效
                oc.update('fun', 'abc')
                console.log('fun update', 'abc')
                ms.push('fun update', 'abc')
            }, 1100)
            setTimeout(function() {
                //第4次呼叫(延遲1300ms), 此時會取得被強制更新之快取值(abc), 快取還剩1300ms才失效(也就是在2600ms失效)
                oc.getProxy('fun', { fun, inputs: ['inp1', 'inp2'], timeExpired: 1500 })
                    .then(function(msg) {
                        console.log('fun 4th', msg)
                        ms.push('fun 4th', msg)
                    })
                    .catch(function(err) {
                        console.log('fun 4th error', err)
                        ms.push('fun 4th error', String(err))
                    })
            }, 1300)
            setTimeout(function() {
                //第5次呼叫(延遲2700ms), 此時被強制更新之快取值(abc)已失效, 會重新呼叫函數取值, 取得第2次結果(count=2)
                oc.getProxy('fun', { fun, inputs: ['inp1', 'inp2'], timeExpired: 1500 })
                    .then(function(msg) {
                        console.log('fun 5th', msg)
                        ms.push('fun 5th', msg)
                    })
                    .catch(function(err) {
                        console.log('fun 5th error', err)
                        ms.push('fun 5th error', String(err))
                    })
            }, 2700)

            setTimeout(function() {
                resolve(ms)
            }, 3100)

        })
    }
    console.log('test3')
    let r3 = await test3()
    console.log(JSON.stringify(r3))
    // test3
    // call fun, count=1
    // fun 1st inp1|inp2, count=1
    // fun 2nd inp1|inp2, count=1
    // fun 3rd inp1|inp2, count=1
    // fun update abc
    // fun 4th abc
    // call fun, count=2
    // fun 5th inp1|inp2, count=2
    // ["call fun, count=1","inp1|inp2, count=1","fun 1st","inp1|inp2, count=1","fun 2nd","inp1|inp2, count=1","fun 3rd","inp1|inp2, count=1","fun update","abc","fun 4th","abc","call fun, count=2","inp1|inp2, count=2","fun 5th","inp1|inp2, count=2"]

    async function test4() {
        //執行中clear與update: clear於執行中呼叫仍有效(執行中之呼叫取得本次結果, 下次get重新執行); update於執行中呼叫以update之值為準, 不被執行結果覆寫
        let oc = cache()

        let n = 0
        let fun = () => {
            n++
            return new Promise(function(resolve, reject) {
                setTimeout(function() {
                    resolve('count=' + n)
                }, 100)
            })
        }

        //clear於執行中
        oc.set('clear', { fun, inputs: [], timeExpired: 30000 })
        let pm1 = oc.get('clear')
        await new Promise((resolve) => setTimeout(resolve, 10))
        oc.clear('clear')
        let v1 = await pm1 //執行中之呼叫取得本次結果(count=1)
        let v2 = await oc.get('clear') //clear有效, 重新執行(count=2)
        let v3 = await oc.get('clear') //快取(count=2)

        //update於執行中
        n = 0
        oc.set('update', { fun, inputs: [], timeExpired: 30000 })
        let pm2 = oc.get('update')
        await new Promise((resolve) => setTimeout(resolve, 10))
        oc.update('update', 'abc')
        let v4 = await pm2 //以update之值為準(abc)
        let v5 = await oc.get('update') //快取(abc), 不重新執行

        return { v1, v2, v3, v4, v5, n }
    }
    console.log('test4')
    let r4 = await test4()
    console.log(JSON.stringify(r4))
    // test4
    // {"v1":"count=1","v2":"count=2","v3":"count=2","v4":"abc","v5":"abc","n":1}

    async function test5() {
        //timeFrom: 預設'start'自fun開始起算, 'end'自fun結束起算; fun耗時200ms, timeExpired 220ms, 結束後再隔120ms取值: 'start'時已過期(320>220)重新執行, 'end'時未過期(120<220)取快取
        let oc = cache()

        let n = 0
        let fun = () => {
            n++
            return new Promise(function(resolve, reject) {
                setTimeout(function() {
                    resolve('count=' + n)
                }, 200)
            })
        }

        oc.set('start', { fun, inputs: [], timeExpired: 220 }) //預設timeFrom='start'
        let v1 = await oc.get('start')
        await new Promise((resolve) => setTimeout(resolve, 120))
        let v2 = await oc.get('start')

        n = 0
        oc.set('end', { fun, inputs: [], timeExpired: 220, timeFrom: 'end' })
        let v3 = await oc.get('end')
        await new Promise((resolve) => setTimeout(resolve, 120))
        let v4 = await oc.get('end')

        return { v1, v2, v3, v4 }
    }
    console.log('test5')
    let r5 = await test5()
    console.log(JSON.stringify(r5))
    // test5
    // {"v1":"count=1","v2":"count=2","v3":"count=1","v4":"count=1"}

    async function test6() {
        //useCacheWhenError: 預設false則失敗不寫入快取, 錯誤拋給執行者與等待中之併發呼叫, 下次get重新執行; 設true則失敗仍寫入快取(值為undefined)並保留整個timeExpired, 呼叫端取得undefined而非收到錯誤; 兩者error事件皆發出
        let oc = cache()

        let errs = []
        oc.on('error', function(msg) {
            errs.push(msg.key + ':' + msg.msg.message)
        })

        let n = 0
        let fun = () => {
            n++
            return new Promise(function(resolve, reject) {
                setTimeout(function() {
                    if (n <= 2) {
                        reject(new Error('down' + n))
                    }
                    else {
                        resolve('up' + n)
                    }
                }, 50)
            })
        }

        oc.set('fun', { fun, inputs: [], timeExpired: 30000 }) //預設useCacheWhenError=false

        //第1次執行失敗: 執行者與等待中之併發呼叫皆收到reject
        let pm1 = oc.get('fun').then((v) => 'ok:' + v).catch((e) => 'err:' + e.message)
        await new Promise((resolve) => setTimeout(resolve, 10))
        let pm2 = oc.get('fun').then((v) => 'ok:' + v).catch((e) => 'err:' + e.message)
        let r1 = await pm1
        let r2 = await pm2

        //第2次執行仍失敗(失敗不寫入快取故重新執行)
        let r3 = await oc.get('fun').then((v) => 'ok:' + v).catch((e) => 'err:' + e.message)

        //第3次執行成功並快取
        let r4 = await oc.get('fun').then((v) => 'ok:' + v).catch((e) => 'err:' + e.message)
        let r5 = await oc.get('fun').then((v) => 'ok:' + v).catch((e) => 'err:' + e.message)

        //useCacheWhenError=true時, 失敗不拋錯而是取得undefined, 且快取整個timeExpired故不重新執行
        let m = 0
        let funErr = async () => {
            m++
            throw new Error('always down')
        }
        oc.set('funErr', { fun: funErr, inputs: [], timeExpired: 30000, useCacheWhenError: true })
        let c1 = await oc.get('funErr').then((v) => 'ok:' + v).catch((e) => 'err:' + e.message)
        let c2 = await oc.get('funErr').then((v) => 'ok:' + v).catch((e) => 'err:' + e.message)

        await new Promise((resolve) => setTimeout(resolve, 50)) //error事件以timer脫勾發送, 稍待

        return { rs: [r1, r2, r3, r4, r5], n, cs: [c1, c2], m, errs }
    }
    console.log('test6')
    let r6 = await test6()
    console.log(JSON.stringify(r6))
    // test6
    // {"rs":["err:down1","err:down1","err:down2","ok:up3","ok:up3"],"n":3,"cs":["ok:undefined","ok:undefined"],"m":1,"errs":["fun:down1","fun:down2","funErr:always down"]}

    async function test7() {
        //useCloneDeep: 預設true回傳複製值, 呼叫端修改不影響快取; 設false則直接回傳快取內之值(為同一參照), 可省去大量數據之複製開銷, 但呼叫端須自行確保不修改
        let oc = cache()

        let fun = async () => {
            return { a: 1 }
        }

        //預設true
        oc.set('clone', { fun, inputs: [], timeExpired: 30000 })
        let v1 = await oc.get('clone')
        v1.a = 2 //修改所取得之值
        let v2 = await oc.get('clone') //快取未受影響

        //get傳入useCloneDeep=false
        oc.set('noclone', { fun, inputs: [], timeExpired: 30000 })
        let v3 = await oc.get('noclone', { useCloneDeep: false })
        let v4 = await oc.get('noclone', { useCloneDeep: false })

        //set時設定useCloneDeep=false, get未指定則沿用set之設定
        oc.set('setnoclone', { fun, inputs: [], timeExpired: 30000, useCloneDeep: false })
        let v5 = await oc.get('setnoclone')
        let v6 = await oc.get('setnoclone')

        //get之設定可覆寫set之設定
        let v7 = await oc.get('setnoclone', { useCloneDeep: true })

        return { v2, sameNoclone: v3 === v4, sameSetnoclone: v5 === v6, sameOverride: v5 === v7 }
    }
    console.log('test7')
    let r7 = await test7()
    console.log(JSON.stringify(r7))
    // test7
    // {"v2":{"a":1},"sameNoclone":true,"sameSetnoclone":true,"sameOverride":false}

}
topAsync().catch(() => {})
Parameters:
Name Type Attributes Default Description
opt Object <optional>
{}

輸入設定物件,預設{}

Properties
Name Type Attributes Default Description
onTrace function <optional>
null

輸入觀察回調函數,於內部邏輯事件發生當下同步呼叫(非計時器週期),傳入一個凍結之事件物件{ type, ... },供測試以事件(而非等待時間)同步與診斷,事件欄位只含呼叫端傳入之key(通常為字串)、字串、布林與數字,不含fun之輸入與回傳值;type為'set'時為set呼叫(含key、added為是否新增,key已存在而被忽略時為false),'get'時為get呼叫之判定(含key、n為本實例第幾次get呼叫、mode為'invalid'無效key,'wait'共用執行中之promise,'first'首次或clear後執行,'expired'因超過timeExpired而重新執行,'cache'使用快取,timeDiff為mode是'expired'或'cache'時距快取時間之毫秒數,其餘mode為null),'start'時為即將呼叫fun(含key、run為本實例第幾次執行),'end'時為該次fun執行結束(含key、run、ok為fun是否未失敗、stored為本次結果是否寫入快取,失敗而不寫入快取或執行中被update而不覆寫時為false)且早於該次執行之get settle,'update'、'clear'時為對應呼叫(含key、running為該key是否執行中),'remove'時為對應呼叫(含key);key無效時update、clear、remove不通知;回調不帶接收者呼叫,其拋錯與回傳值皆忽略,不影響快取,預設null

Returns:

回傳事件物件,可呼叫函數on、set、get、getProxy、clear、remove。on為監聽事件,需自行監聽message與error事件。set為加入待執行函數,函數結束回傳欲快取的值,set傳入參數依序為key與快取物件,key為唯一識別字串,可使用函數加上輸入參數作為key,因考慮輸入參數可能為大量數據會有效能問題,由開發者自行決定key,而快取物件需設定欄位fun為待執行的非同步函數(fun非函數時視為回傳undefined之空函數)、inputs為待執行函數fun的傳入參數組、timeExpired為過期時間正整數(1至9007199254740991,數字字串亦可),單位為毫秒ms,預設5000,非預期(0、負數、小數、Infinity、超過安全整數、'0x10'、包裝物件等)視為未給而改用預設5000,不報錯(Infinity不代表永不過期),opt.debug為true時另以固定詞彙警告(不含輸入值,同一行程只警告一次,出口為opt.funLog或console.warn)、timeFrom為快取時間之起算點,可選'start'或'end','start'為自函數開始執行時起算,'end'為自函數執行完畢時起算,預設'start'、useCacheWhenError為函數執行失敗時是否仍寫入快取,預設false,失敗不寫入快取,錯誤會拋給呼叫端(含等待中之併發呼叫)且下次get會重新執行(fun同步拋錯與其Promise被reject皆同),故呼叫端需自行catch,若設定true則失敗仍寫入快取,此時快取值為undefined並保留整個timeExpired,呼叫端不會收到錯誤而是取得undefined、useCloneDeep為取值時是否複製快取值後才回傳,預設true,因快取值若為物件則可能受外部調用而被修改到快取區的記憶體,若快取值為大量數據可設定false以節省複製開銷,但呼叫端須自行確保不修改所取得之值。get為依照key取得目前快取值,若該key之函數執行中則共用執行中之promise,待其執行完畢即一併取得結果,不另行輪詢;fun內(含同步階段)呼叫同key之get亦共用本次執行而不重複執行,惟fun若等待該get之結果則互相等待而永不settle(需逾時者以pmTimeout包裝),get傳入參數依序為key與設定物件,設定物件之欄位useCloneDeep可覆寫set時之設定,未指定時沿用set之設定。getProxy為合併set與get功能,直接set註冊待執行函數與取值,傳入參數同set,且會一併傳給get,回傳同get。update為強制更新key所屬快取值,同時也會更新該快取之時間至當前,視同函數已執行完成並寫入新值,故對已set但尚未執行過(或已clear)之key,其後get取得update之值而不執行函數(直至過期),於函數執行中呼叫時以update之值為準,不被執行結果覆寫;update之後才呼叫clear者,下次get仍重新執行。clear為清除key所屬快取的是否執行標記,使該快取視為需重新執行函數取值,於函數執行中呼叫亦有效,執行中之呼叫仍取得本次結果,下次get才重新執行。remove為直接清除key所屬快取,清除後用set重設。事件以timer脫勾派發且事件物件為原生EventEmitter(eventemitter3)。本模組於派發處以try攔截監聽器之同步拋錯,故其不會使行程崩潰,會改以error事件回報{ fun: 'listener', name, msg, args },無error監聽者則console.error;惟依EventEmitter規範,同一次派發中先拋錯之監聽器會中止該次派發,其後之監聽器不再被呼叫。async監聽器之reject不被攔截(規範上emit不觀察監聽器回傳值),須由監聽器自行處理,否則為unhandledRejection;故error事件同時承載本模組自身之錯誤(fun為'get'等且帶key)與監聽器錯誤(fun為'listener'且無key),監聽error時請先以fun欄位分流

Type
Object

(static) cacheBd(fun, optopt) → {Object}

Description:
  • 非同步函數快取,封裝指定非同步函數與再提供取用快取版

    get須定期或高執行率,getFromCache雖能自己自動調用,但僅第1次取得後數據就無法更新,此會導致一直取得舊數據

    Unit Test: Github

Source:
Example
let test1 = async () => {
    let ms = []

    let fun = async(p1, p2) => {
        await delay(300)
        return `${p1}:${p2}`
    }

    let bc = cacheBd(fun)
    let execFun = bc.get
    let execFunCache = bc.getFromCache

    let pm1 = execFunCache(123, 'abc') //pm1執行取得快取, 因無快取將持續等待
    pm1
        .then((res) => {
            // console.log('res', res)
            ms.push({ result: `pm1-${res}` })
        })

    let pm2 = execFun(4.56, 'def') //pm2執行原本函數與使用輸入, 會最先回傳, 且更新快取給等待或之後取得快取使用
    pm2
        .then((res) => {
            // console.log('res', res)
            ms.push({ result: `pm2-${res}` })
        })

    let pm3 = execFunCache(78.9, 'xyz') //pm3執行取得快取, 因已有快取將直接取得快取
    pm3
        .then((res) => {
            // console.log('res', res)
            ms.push({ result: `pm3-${res}` })
        })

    await Promise.all([pm1, pm2, pm3])
    // console.log('rs', rs)

    console.log('ms', ms)
    return ms
}
await test1()
// ms [
//   { result: 'pm2-4.56:def' },
//   { result: 'pm1-4.56:def' },
//   { result: 'pm3-4.56:def' }
// ]

let test2 = async () => {
    let ms = []

    let fun = async(p1, p2) => {
        await delay(300)
        return `${p1}:${p2}`
    }

    let bc = cacheBd(fun)
    let execFun = bc.get
    let execFunCache = bc.getFromCache

    setTimeout(() => {
        console.log('pm1 exec..')
        let pm1 = execFunCache(123, 'abc') //pm1執行取得快取, 因無快取將持續等待
        pm1
            .then((res) => {
                console.log('pm1 then', res)
                ms.push({ result: `pm1-${res}` })
            })
    }, 1)

    setTimeout(() => {
        console.log('pm2 exec..')
        let pm2 = execFun(4.56, 'def') //1000ms後, pm2執行原本函數與使用輸入, 會最先回傳, 且更新快取給等待或之後取得快取使用
        pm2
            .then((res) => {
                console.log('pm2 then', res)
                ms.push({ result: `pm2-${res}` })
            })
    }, 1000)

    setTimeout(() => {
        console.log('pm3 exec..')
        let pm3 = execFunCache(78.9, 'xyz') //pm3執行取得快取, 因已有快取將直接取得快取
        pm3
            .then((res) => {
                console.log('pm3 then', res)
                ms.push({ result: `pm3-${res}` })
            })
    }, 3000)

    await delay(5000)

    console.log('ms', ms)
    return ms
}
await test2()
// ms [
//   { result: 'pm2-4.56:def' },
//   { result: 'pm1-4.56:def' },
//   { result: 'pm3-4.56:def' }
// ]

let test3 = async () => {
    let ms = []

    let fun = async(p1, p2) => {
        await delay(300)
        return `${p1}:${p2}`
    }

    let bc = cacheBd(fun)
    let execFun = bc.get
    let execFunCache = bc.getFromCache

    setTimeout(() => {
        console.log('pm1 exec..')
        let pm1 = execFunCache(123, 'abc') //pm1執行取得快取, 因無快取將持續等待, 3000ms將執行get與自己的輸入, 並最先回傳
        pm1
            .then((res) => {
                console.log('pm1 then', res)
                ms.push({ result: `pm1-${res}` })
            })
    }, 1)

    setTimeout(() => {
        console.log('pm2 exec..')
        let pm2 = execFun(4.56, 'def') //3500ms後, pm2執行原本函數與使用輸入, 計算完畢則會覆蓋快取, 此快取將再給等待或之後取得快取使用
        pm2
            .then((res) => {
                console.log('pm2 then', res)
                ms.push({ result: `pm2-${res}` })
            })
    }, 3500)

    setTimeout(() => {
        console.log('pm3 exec..')
        let pm3 = execFunCache(78.9, 'xyz') //pm3執行取得快取, 因已有快取將直接取得快取
        pm3
            .then((res) => {
                console.log('pm3 then', res)
                ms.push({ result: `pm3-${res}` })
            })
    }, 4500)

    await delay(6500)

    console.log('ms', ms)
    return ms
}
await test3()
// ms [
//   { result: 'pm1-123:abc' },
//   { result: 'pm2-4.56:def' },
//   { result: 'pm3-4.56:def' }
// ]
Parameters:
Name Type Attributes Default Description
fun function

輸入非同步函數,必須參數,須為函數(async generator函數不算);非函數時於本函數呼叫當下同步拋出Error('invalid fun: must be a function'),先於任何副作用(不建立實例、不輸出opt.debug警告)

opt Object <optional>
{}

輸入設定物件,預設{}

Properties
Name Type Attributes Default Description
nMax Integer <optional>
200

輸入使用快取版之總嘗試次數,為正整數(1至4294967295,數字字串亦可),超過則報錯,預設200;非預期(0、負數、小數、Infinity、超過4294967295、'0x10'等)視為未給而改用預設200,不報錯(Infinity不代表無限次嘗試)

nTrigger Integer <optional>
3

輸入嘗試指定次數,為正整數(1至4294967295,數字字串亦可),若嘗試指定次數之後皆無快取則須自動執行get用以取得快取,預設3;非預期(0、負數、小數、Infinity、超過4294967295、'0x10'等)視為未給而改用預設3,不報錯

debug Boolean <optional>
false

輸入是否於opt.nMax或opt.nTrigger為非預期之輸入時輸出警告布林值,須為true才生效,警告為固定詞彙(不含輸入值),同一參數同一行程只警告一次,預設false

funLog function <optional>
null

輸入警告輸出函數,格式為(msg, { fn, reason, key })=>{},未給則用console.warn,預設null

onTrace function <optional>
null

輸入觀察回調函數,於內部邏輯事件發生當下同步呼叫(輪詢之等待本身不通知,其間隔由delay提供),傳入一個凍結之事件物件{ type, ... },供測試以事件(而非等待時間)同步與診斷,事件欄位只含數字與布林,不含fun之輸入與回傳值;type為'poll'時為getFromCache每次嘗試之判定(含call為本實例第幾次getFromCache呼叫、i為第幾次嘗試、cached為是否已有快取、running為執行中之get數、trigger為是否因此觸發get,須i大於nTrigger且無快取且無執行中之get),觸發時緊接著通知該次get,'get'時為get開始(含seq為本實例第幾次get,不論直接呼叫或由getFromCache觸發),'done'時為該次get結束(含seq、ok為fun是否未失敗、cached為其結果是否寫入快取,先啟動而後完成者不覆蓋後啟動者已寫入之快取時為false)且早於該次get之settle,'settle'時為getFromCache結束(含call、ok為是否取得快取,超過nMax而reject時為false)且早於其settle;回調不帶接收者呼叫,其拋錯與回傳值皆忽略,不影響快取,預設null

Returns:

回傳事件物件,可呼叫事件get、getFromCache,get為封裝後封裝原本非同步函數,getFromCache為提供取用快取版之非同步函數,若有快取則優先使用,若超過指定次數則自動執行get使能取得快取。getFromCache於嘗試nTrigger次之後,若尚無快取且無任何執行中之get(含直接呼叫者)才觸發get,觸發之get失敗時不向外報錯而續等,超過nMax次(每次間隔1000ms)仍無快取時reject Error('exceeded nMax[nMax]')。get為直接執行fun並回傳其自身之結果(失敗則reject其錯誤),不與執行中者共用;寫入快取依啟動先後,先啟動而後完成者之結果不覆蓋後啟動者已寫入之快取;fun成功回傳之任何值(含null與undefined)皆視為已有快取,是否已有快取不以回傳值判定。fun於建立時即已驗為函數(非函數同步拋錯),故不再有「get以TypeError被reject而getFromCache吞下其錯誤、輪詢至nMax才失敗」之情形

Type
Object

(static) cacheSt(optopt) → {Object}

Description:
  • 非同步狀態旗標快取,含TTL與互斥/同步原語,可用於在單一process內協調非同步動作之執行順序與資源獨占

    Unit Test: Github

Source:
Example
let test1 = async () => {
    let ms = []

    let cs = cacheSt({ timeExpire: 10000 })

    //案例: mutex取得與釋放
    let b1 = cs.checkWithSet('myLock') //第一次取得lock, 回true
    ms.push({ '1st checkWithSet': b1 })
    let b2 = cs.checkWithSet('myLock') //第二次嘗試, 已被占用回false
    ms.push({ '2nd checkWithSet': b2 })
    await cs.del('myLock')             //釋放lock
    let b3 = cs.checkWithSet('myLock') //釋放後可再取
    ms.push({ 'after del checkWithSet': b3 })

    cs.clear() //結束時停止TTL偵測timer
    console.log('ms', ms)
    return ms
}
await test1()
// ms [
//   { '1st checkWithSet': true },
//   { '2nd checkWithSet': false },
//   { 'after del checkWithSet': true }
// ]

let test2 = async () => {
    let ms = []

    let cs = cacheSt({ timeExpire: 10000 })

    //案例: 多key原子占用並執行函數, 結束自動釋放
    let r = await cs.setWithFree(['lockA', 'lockB'], async () => {
        ms.push({ inside: 'fn running' })
        return 'done'
    })
    ms.push({ result: r })
    ms.push({ 'lockA after': await cs.check('lockA') }) //已自動釋放
    ms.push({ 'lockB after': await cs.check('lockB') }) //已自動釋放

    cs.clear()
    console.log('ms', ms)
    return ms
}
await test2()
// ms [
//   { inside: 'fn running' },
//   { result: 'done' },
//   { 'lockA after': false },
//   { 'lockB after': false }
// ]

let test3 = async () => {
    let ms = []

    let cs = cacheSt({ timeExpire: 10000 })

    //案例: 等待key出現 (條件變數模式)
    setTimeout(() => {
        cs.set('ready', 'data-x')
    }, 200)

    await cs.waitExist('ready', { attemptNum: 30, timeInterval: 100 }) //3秒內等候ready出現
    let v = await cs.get('ready')
    ms.push({ 'after waitExist': v })

    cs.clear()
    console.log('ms', ms)
    return ms
}
await test3()
// ms [
//   { 'after waitExist': 'data-x' }
// ]
Parameters:
Name Type Attributes Default Description
opt Object <optional>
{}

輸入設定物件,預設{}

Properties
Name Type Attributes Default Description
timeExpire Integer <optional>
1800000

輸入TTL過期時間正整數(1至9007199254740991,數字字串亦可),單位為毫秒ms,key寫入超過此時間後將被內部偵測週期自動刪除,預設30分鐘(1800000ms);非預期(0、負數、小數、Infinity、超過安全整數、'0x10'等)視為未給而改用預設,不報錯(Infinity不代表永不過期);timeExpire只與時間差比較、不交給原生計時器,故不設2147483647之計時器上限

timeDetect Integer <optional>
2000

輸入TTL偵測週期正整數(1至2147483647,數字字串亦可),單位為毫秒ms,預設2000;非預期(0、負數、小數、Infinity、超過2147483647、'0x10'等)視為未給而改用預設,不報錯、不夾至上限

debug Boolean <optional>
false

輸入是否於opt.timeExpire、opt.timeDetect(以及waitExist、waitNotExist之optWait.attemptNum、optWait.timeInterval)為非預期之輸入時輸出警告布林值,須為true才生效,警告為固定詞彙(不含輸入值),同一參數同一行程只警告一次,預設false;waitExist與waitNotExist之debug與funLog取自其自身所傳之optWait

funLog function <optional>
null

輸入警告輸出函數,格式為(msg, { fn, reason, key })=>{},未給則用console.warn,預設null

onTrace function <optional>
null

輸入觀察回調函數,於TTL偵測週期內部事件發生當下同步呼叫,傳入一個凍結之事件物件{ type, ... },供測試以事件(而非等待時間)同步與診斷;僅涵蓋TTL偵測週期,不含set、get、check、checkWithSet、setWithFree、del之呼叫(其本身皆為同步完成,並已有同名事件可由on監聽),亦不含waitExist與waitNotExist之輪詢(其輪詢事件由waitFun之opt.onTrace提供,本函數不轉發,其開始與結束已有waitExist、waitNotExist事件可由on監聽);type為'expire'時為偵測到key已超過timeExpire而剛被刪除(含key、age為其寫入至本次偵測之毫秒數),'detect'時為每次偵測週期結束(含n為第幾次偵測、size為偵測前之key數、expired為本次刪除之key數);回調不帶接收者呼叫,其拋錯與回傳值皆忽略,不影響快取,clear後不再呼叫(含clear時正在進行之偵測週期之餘下部分),預設null

Returns:

回傳事件物件,內含上述對外方法可呼叫,亦提供on用於監聽各方法之事件。waitExist(key, optWait)與waitNotExist(key, optWait)之optWait.attemptNum為最大嘗試次數正整數(1至4294967295,預設30)、optWait.timeInterval為嘗試週期正整數(1至2147483647,單位ms,預設100),非預期(含Infinity、超出範圍、'0x10'等)視為未給而改用預設,不報錯(attemptNum為Infinity不代表無限次輪詢)。事件物件為原生EventEmitter(eventemitter3)。本模組於派發處以try攔截監聽器之同步拋錯,故其不會使行程崩潰,會改以error事件回報{ fun: 'listener', name, msg, args },無error監聽者則console.error;惟依EventEmitter規範,同一次派發中先拋錯之監聽器會中止該次派發,其後之監聽器不再被呼叫。async監聽器之reject不被攔截(規範上emit不觀察監聽器回傳值),須由監聽器自行處理,否則為unhandledRejection

Type
Object

(static) cbol(v) → {Boolean}

Description:
  • 布林值或字串轉布林值

    只把布林true、false與字串'true'、'false'轉為對應之布林值,字串先去頭尾空白且須全小寫;其餘輸入一律轉為false,包含數字(cbol(1)為false)、大小寫混用之字串('TRUE'、'True'、'tRuE'為false)、'y'、'yes'、'1'、陣列、物件、null與undefined(使用者2026-11-16定,dspec〈輸入參數之檢測機制〉§3.3 B2:布林與數字不互轉) 轉型函數照舊拆包: 包裝物件new Boolean(true)、new String('true')先取出原始值再轉換(判斷函數isbol、isestr只收原始值,轉型函數不受影響)

    Unit Test: Github

Source:
Example
console.log(cbol(true))
// => true

console.log(cbol(false))
// => false

console.log(cbol('true'))
// => true

console.log(cbol(' true '))
// => true (去頭尾空白)

console.log(cbol('false'))
// => false

console.log(cbol(1))
// => false (數字不轉為布林)

console.log(cbol(0))
// => false

console.log(cbol('tRuE'))
// => false (須全小寫)

console.log(cbol('TRUE'))
// => false (須全小寫)

console.log(cbol('abc'))
// => false

console.log(cbol(''))
// => false

console.log(cbol([]))
// => false

console.log(cbol({}))
// => false

console.log(cbol(null))
// => false

console.log(cbol(undefined))
// => false

console.log(cbol(new Boolean(true)))
// => true (轉型函數拆包, 回傳原始布林值)
Parameters:
Name Type Description
v *

輸入任意值

Returns:

回傳布林值,恆回傳原始布林值(輸入new Boolean時回傳其原始值而非包裝物件),無法轉換者回傳false

Type
Boolean

(static) cdbl(v) → {Number}

Description:
  • 數字或字串轉浮點數 若輸入非數字則回傳0 轉型函數照舊拆包: 包裝物件new Number(1)、new String('1')先取出原始值再轉換(判斷函數isnum只收原始值,轉型函數不受影響) 轉換結果恆為有限數(可用、可計算之數值): Infinity於數學上是數值(isnum為true)故屬可轉換者, 但非可計算之值, 故±Infinity(含'Infinity'、'1e400'等超出浮點範圍之字串)夾為±Number.MAX_VALUE(1.7976931348623157e+308), 不回Infinity亦不回0 要排除Infinity者(如計算類參數), 先以isenum(有效數字)或iseint(有效整數)判斷, 不要以cdbl之結果判斷

    Unit Test: Github

Source:
Example
console.log(cdbl('25'))
// => 25

console.log(cdbl(Infinity))
// => 1.7976931348623157e+308 (Number.MAX_VALUE)

console.log(cdbl(-Infinity))
// => -1.7976931348623157e+308 (-Number.MAX_VALUE)

console.log(cdbl('1e400'))
// => 1.7976931348623157e+308 (Number.MAX_VALUE)
Parameters:
Name Type Description
v Number | String

輸入數字或字串

Returns:

回傳數字,恆為有限數,非數字回傳0,±Infinity回傳±Number.MAX_VALUE

Type
Number

(static) ceil(v, idigopt) → {Number}

Description:
  • 數字或字串無條件進位至指定位數(0位為整數)

    v須為有效數字(isenum: 有限數字,或去頭尾空白後為十進位寫法之數字字串),其餘(Infinity、'Infinity'、'0x10'、'1e400'、'-'、''、null、包裝物件等)回傳空字串; idig屬選填參數,須為0~100之有效整數(iseint,use為'digits'),不是則用預設0,不報錯。

    Unit Test: Github

Source:
Example
console.log(ceil(1.5))
// => 2

console.log(ceil('1.5'))
// => 2

console.log(ceil(-1.5))
// => -1

console.log(ceil('125abc'))
// => ''

console.log(ceil(9.83501, 2))
// => 9.84

console.log(ceil(9.8350, 2))
// => 9.84

console.log(ceil(9.82501, 2))
// => 9.83

console.log(ceil(9.8250, 2))
// => 9.83

console.log(ceil(9.8249, 2))
// => 9.83

console.log(ceil(12.6449, 2))
// => 12.65

console.log(ceil(12.645, 2))
// => 12.65

console.log(ceil(12.6451, 2))
// => 12.65

console.log(ceil(12.65, 2))
// => 12.65

console.log(ceil(12.64, 2))
// => 12.64

console.log(ceil(12.6, 2))
// => 12.6

console.log(ceil(12, 2))
// => 12

console.log(ceil(' 1.2 '))
// => 2

console.log(ceil(Infinity))
// => ''

console.log(ceil('0x10'))
// => ''
Parameters:
Name Type Attributes Default Description
v Number | String

輸入數值,需為有效數字(數字或數字字串,定義見isenum,不收Infinity與'0x10'等),非有效數字時回傳空字串

idig Integer <optional>
0

輸入指定位數,需為0~100之有效整數(數字或數字字串,定義見iseint之use為digits),非有效時改用預設0,預設0

Returns:

回傳無條件進位的數字,v非有效數字時回傳空字串

Type
Number

(static) cfilesize(b) → {String}

Description:
  • 檔案大小(bytes)自動轉換單位 可調整檔案大小為b,kb,mb,gb,tb,並添加單位,tb為最高單位(1 TB以上皆以tb表示,如1024 ** 5為'1024.0 tb') b須為有效數字(isenum: 有限數字,或去頭尾空白後為十進位寫法之數字字串),其餘(Infinity、'Infinity'、'0x10'、'1e400'、'-'、''、null、包裝物件等)回傳空字串

    Unit Test: Github

Source:
Example
console.log(cfilesize(0))
// => '0.0 b'

console.log(cfilesize(100))
// => '100.0 b'

console.log(cfilesize(2048))
// => '2.0 kb'

console.log(cfilesize(2000000))
// => '1.9 mb'

console.log(cfilesize(2000000000))
// => '1.9 gb'

console.log(cfilesize(1099511627776))
// => '1.0 tb'
Parameters:
Name Type Description
b Number | String

輸入單位需為bytes的檔案大小,需為有效數字(數字或數字字串,定義見isenum,不收Infinity與'0x10'等),非有效數字時回傳空字串

Returns:

回傳自動轉換單位後的字串,b非有效數字時回傳空字串

Type
String

(static) cfinancial(v, idigopt) → {String}

Description:
  • 數字或字串轉金融格式(百分位添加逗號)表示 v須為有效數字(isenum: 有限數字,或去頭尾空白後為十進位寫法之數字字串),其餘(Infinity、'Infinity'、'0x10'、'1e400'、'-'、''、null、包裝物件等)回傳空字串

    Unit Test: Github

Source:
Example
console.log(cfinancial(0.123456789, 3))
// => '0.123'

console.log(cfinancial(1234567.89))
// => '1,234,568'

console.log(cfinancial(1234567.89, 1))
// => '1,234,567.9'
Parameters:
Name Type Attributes Default Description
v Number | String

輸入數值,需為有效數字(數字或數字字串,定義見isenum,不收Infinity與'0x10'等),非有效數字時回傳空字串

idig Integer | String <optional>
0

輸入指定小數位,opt類參數(有效整數,小數位數0~100,數字字串亦可,去頭尾空白後取值),非預期之輸入(非有效整數、小數、負數、超過100、Infinity、'0x10'、包裝物件等)視為未給而改用預設,不報錯,預設為0

Returns:

回傳金融格式的字串,v非有效數字時回傳空字串

Type
String

(static) chkOrmData(data, optopt) → {null|Object}

Description:
  • w-orm系列寫入資料(鍵名與字串值,含巢狀物件與陣列元素)之良構檢核,回傳null(合格)或{ reason, path }

    輸入為各後端於複製(如cloneDeep)後、補主鍵與加欄位前之寫入資料(單一文件、文件陣列或任何值),本函數不修改輸入(但會呼叫可列舉存取器,見第7點),並假設後端其後寫入的就是被檢查之值;存取器屬性(自有或繼承之可列舉者)於檢核時呼叫其getter一次取值,有狀態之getter須由後端於複製後轉為資料屬性。

    1. 走訪範圍:一般物件與類別實例之自有可列舉字串鍵(鍵名與值)及繼承自Object.prototype以外原型之可列舉字串鍵(lodash merge、sequelize update、mdb取值皆經原型鏈,自有同名或較近原型同名者含不可列舉者遮蔽之)、陣列元素(依索引)、Map之項目(字串鍵、物件鍵之內容與值,逐項迭代)、Set之元素、String包裝物件之字串值與其額外屬性(字元索引鍵除外)、RegExp之source、Error之name/message/cause;Map、Set、RegExp、Error另走訪其自有與繼承之可列舉屬性;被後端自動轉成文字之函數(原始碼)與Symbol值(描述);字串經chkOrmStr檢核,預設只檢孤立代理(值之NUL不檢查,opt.nul為true時一併檢查NUL)。內建物件依內部槽判型(與標籤無關,標籤被改寫者亦然;原型為Object.prototype或null者直接當一般物件)。

    2. 略過:Date、TypedArray、ArrayBuffer、SharedArrayBuffer、DataView、Buffer(整個物件,連其上自有額外屬性)、數字、布林、null、undefined、BigInt、Symbol鍵、不可列舉鍵、陣列之洞與非索引屬性、Object.prototype上之屬性、Number/Boolean包裝與Promise/WeakMap/WeakSet(無可列舉內容);toJSON或自訂序列化之輸出不檢查。

    3. 走訪順序固定為文件順序(深度優先):同一物件內鍵名先於其值(自有鍵名、由近至遠之繼承鍵名、自有值、繼承值),各值依自有鍵序(陣列依索引、整數樣鍵依引擎規定先於其他鍵);回傳首個不合格處。

    4. 迭代走訪(顯式堆疊,不遞迴),深度、節點數與字串長度皆不設上限;循環參照與共享參照安全,同一物件出現多處只走訪一次(路徑取首次出現處);稀疏陣列依實際元素走訪,成本不隨length;Map、Set逐項迭代不預先具現;同一原型(如同一類別之多個實例)之鍵只掃描一次。

    5. 回傳{ reason, path }:reason為chkOrmStr之固定原因詞彙(不回顯值);path以root起始,物件鍵為.鍵名(限30字元並以?取代控制字元、格式字元、方括號)、陣列元素與Set元素為[索引]、Map項目為序號,不合格之物件鍵名不出現在path,以.標示;Error與RegExp之文字為.message、.name、.cause、.source;路徑超過120字元截為...加末100碼元(切點避開代理對中間);opt.root含控制字元、孤立代理、NUL或過長者改用預設。

    6. 不吞例外:讀取過程中Proxy陷阱、getter等拋出之例外原樣拋出;各後端於複製後呼叫則一般資料不會遇到。

    7. 會呼叫可列舉存取器(含繼承者),後端應於獨立複本上走訪:存取器之getter以被走訪者為this執行,其副作用可能改動被走訪之同一份複本——例如繼承之存取器把已檢查之欄位改成不合格字串,或把主鍵改指向既有他列——使其後寫入或刪除的不是被檢查之值(cloneDeep保留原型而不讀繼承存取器,故複製後存取器仍在)。後端須另做一份獨立複本(如再cloneDeep一次)供本函數走訪,寫入用複本不被走訪;交給事件訂閱者之物件亦須為獨立快照(訂閱者的改動不得影響其後各筆),訂閱函數拋錯不得影響操作。此作法擋得住存取器對寫入複本的直接改動,但擋不住存取器『修好』走訪用複本中的不合格值(寫入用複本仍帶原值而通過檢核);要連此一併杜絕,須在檢核前把存取器固定為資料(每個可列舉屬性含繼承者只讀一次,產生不含存取器之資料),檢核並寫入同一份固定後之資料。契約案例表增補案例next之toctou組(inh-getter-、event-shared、listener-throws)驗證獨立複本與事件快照;『修好』之情形尚無案例,列為已知限制。

    後端依回傳組成訊息:invalid data: reason at [path];w-orm系列契約案例表見wsemi/src/_cvOrmStrCases.mjs。

    Unit Test: Github

Source:
Example
console.log(chkOrmData({ id: 'a', name: '中文\u{1F600}', tags: ['x', 'y'], meta: { k: 'v' } }))
// => null

console.log(chkOrmData({ id: 'a', meta: { tags: ['ok', 'b\uD800'] } }))
// => { reason: 'string contains lone surrogate', path: 'data.meta.tags[1]' }

console.log(chkOrmData({ id: 'a', ['k\uD800']: 1 }, { root: 'data[2]' }))
// => { reason: 'string contains lone surrogate', path: 'data[2].<invalid key>' }

console.log(chkOrmData({ name: 'a\u0000b' }))
// => null

console.log(chkOrmData({ name: 'a\u0000b' }, { nul: true }))
// => { reason: 'string contains NUL', path: 'data.name' }
Parameters:
Name Type Attributes Default Description
data *

輸入已複製之寫入資料,可為物件、陣列或任意值

opt Object <optional>
{}

輸入設定物件,預設{}

Properties
Name Type Attributes Default Description
nul Boolean <optional>
false

輸入是否一併檢查鍵名與字串值之NUL布林值,僅嚴格等於true時檢查,預設false

root String <optional>
'data'

輸入path之起始標籤字串,如data[1],預設'data'

Returns:

回傳null(合格),或{ reason, path }

Type
null | Object

(static) chkOrmStr(s, optopt) → {String|null}

Description:
  • w-orm系列字串之良構檢核,回傳null(合格)或固定原因字串

    檢查順序:非字串→NUL→孤立代理,回傳首個命中之原因。

    1. 非字串(含String包裝物件、undefined、null、數字、物件等任何非原始字串值)回傳'not a string',不呼叫該值之任何方法。

    2. NUL:字串含U+0000回傳'string contains NUL';opt.nul嚴格等於false時不檢查(僅自有資料屬性生效,繼承值、存取器與其他假值皆維持檢查)。

    3. 孤立代理:含孤立之代理碼元(高代理之後無低代理,或低代理之前無高代理,即String.prototype.isWellFormed()為false)回傳'string contains lone surrogate';U+FFFD本身與成對代理(emoji、CJK擴充B區以後之罕用字)為良構,回傳null。

    4. 長度不另限;對字串輸入不拋錯;不修改輸入;純JS(不import任何模組、不用Node API),無String.prototype.isWellFormed之環境走等價之正則退路;檢核所用之內建於模組載入時取得,載入後被覆寫或原型被汙染不影響結果。

    回傳之原因字串為固定詞彙,不回顯輸入值,供呼叫端組成'invalid id: 原因 at [路徑]'等訊息;w-orm系列契約案例表見wsemi/src/_cvOrmStrCases.mjs。

    Unit Test: Github

Source:
Example
console.log(chkOrmStr('abc'))
// => null

console.log(chkOrmStr('中文\u{1F600}'))
// => null

console.log(chkOrmStr('a\uD800'))
// => string contains lone surrogate

console.log(chkOrmStr('a\u0000b'))
// => string contains NUL

console.log(chkOrmStr('a\u0000b', { nul: false }))
// => null

console.log(chkOrmStr(123))
// => not a string
Parameters:
Name Type Attributes Default Description
s *

輸入任意值,通常為字串

opt Object <optional>
{}

輸入設定物件,預設{}

Properties
Name Type Attributes Default Description
nul Boolean <optional>
true

輸入是否檢查NUL布林值,僅嚴格等於false時不檢查,預設true

Returns:

回傳null(合格),或原因字串'not a string'、'string contains NUL'、'string contains lone surrogate'

Type
String | null

(static) chkReadable(v, optopt) → {String}

Description:
  • 可讀性探針,回傳''(可讀)或固定原因字串(不可讀)

    判斷函數(isobj、isarr、iseobj、isearr、isfun、haskey等)對「讀取即拋錯」之值(拋錯之Symbol.toStringTag、已撤銷之Proxy、陷阱拋錯之Proxy、元素讀取拋錯之陣列)一律回false而不拋錯, 呼叫端因而無從分辨「型別不符」與「不可讀」;本函數於判斷函數之前先探針:回''表示可讀(其後交判斷函數,false即為型別不符),回原因字串表示不可讀(呼叫端依其失敗通道回報,不當成型別不符或未給)。

    1. 永不拋錯:任何輸入(含已撤銷之Proxy、陷阱全拋錯之Proxy、讀取即拋錯之物件)與任何opt(null、非物件、存取器)皆不拋錯;opt非物件視為{},各鍵只讀一次且只採自有資料屬性(存取器不呼叫、繼承值不採用),非預期之鍵值視為未給改用預設。
    2. 不呼叫存取器(accessor)與toJSON:屬性與元素先取描述子,存取器者略過(不呼叫、不視為不可讀,其拋錯無從偵測),toJSON只查描述子不讀值;不改寫受檢物。唯一會執行使用端程式者為Proxy之陷阱與Symbol.toStringTag之存取器(Object.prototype.toString之規格行為,與判斷函數同)。
    3. 原始值(null、undefined、數字、字串、布林、Symbol、BigInt)無可讀取者,一律回''。
    4. 預設(不給opt)之讀取範圍:對物件與函數讀內部標籤Object.prototype.toString.call(v),與isobj、isarr、isnull、isfun之前置讀取同源;不可讀回'tag is unreadable'。
    5. opt.fun:另做函數型之讀取(isfun所用lodash isFunction之讀取,唯不讀Symbol.toStringTag之值、不暫時改寫),即Symbol.toStringTag之has與描述子;不可讀回'function type is unreadable'。lodash之getRawTag另會暫時改寫與刪除Symbol.toStringTag,本函數不做(不改寫受檢物),故僅壞set或deleteProperty陷阱之Proxy,isfun為false而本函數回''。
    6. opt.has:對各鍵k做k in v(haskey之讀取,觸發Proxy之has陷阱);不可讀回'key is unreadable';只收字串、Symbol與數字之鍵(數字同haskey轉為字串鍵)、至多1000個。
    7. opt.ownKeys:讀自有鍵(Reflect.ownKeys,觸發ownKeys陷阱);標籤為[object Object]者另沿原型鏈逐層讀自有鍵與字串鍵之描述子(觸發getPrototypeOf、getOwnPropertyDescriptor陷阱,為iseobj之for...in讀取之超集,原型鏈超過1000層視為不可讀);不可讀回'keys are unreadable'。
    8. opt.elements:陣列之長度與元素。'none'(預設)不讀;'first'同isearr(讀length,為1時讀第0個元素);'all'讀length(須為非負安全整數,否則回'length is not a non-negative safe integer',超過opt.maxElements回'too many elements')並逐一讀取各元素(洞與存取器元素略過)。length不可讀回'length is unreadable'、元素不可讀回'element is unreadable'。'first'依內部標籤判陣列(同isarr),'all'依Array.isArray;'first'以描述子加取值讀取,對Proxy較isearr(只讀length與[0])多觸發一次getOwnPropertyDescriptor陷阱(為其超集)。
    9. opt.deep:深探,迭代堆疊走訪(不遞迴,深層不致堆疊溢位),WeakSet去重(循環與共享參照不算不可讀);走訪範圍對齊序列化器會走到者:葉節點(函數、型別陣列與DataView、ArrayBuffer、SharedArrayBuffer、Error、DOMException、有toJSON者)不展開,陣列逐元素(同opt.elements='all',含長度檢查),其他物件取自有可列舉字串鍵之資料屬性值(先取描述子,資料屬性再經Reflect.get取值,Proxy之get陷阱拋錯即不可讀,與序列化器經[[Get]]讀取同;Symbol鍵、不可列舉鍵、存取器略過);葉節點依內部標籤判定,偽造Symbol.toStringTag者其子圖不被走訪(同序列化器,已知限制);走訪之讀取總量(節點、陣列元素、物件鍵各計一次)超過opt.maxReads回'structure is too large';不可讀回'tag is unreadable'、'keys are unreadable'、'property is unreadable'、'length is unreadable'、'element is unreadable'等。opt.fun、opt.has、opt.ownKeys、opt.elements只作用於頂層之v,深探走訪之節點只讀標籤、陣列長度與元素。
    10. 原因字串為固定詞彙,不回顯輸入值與原例外訊息,供呼叫端組成'invalid args[1]: must be a readable value'等訊息。

    Unit Test: Github

Source:
Example
let o = { a: 1 }
console.log(chkReadable(o))
// => ''

let r = Proxy.revocable({}, {})
r.revoke()
console.log(chkReadable(r.proxy))
// => 'tag is unreadable'
console.log(chkReadable(r.proxy) !== '' ? 'unreadable' : 'readable')
// => 'unreadable'

let p = new Proxy({ a: 1 }, { ownKeys: () => { throw new Error('x') } })
console.log(chkReadable(p))
// => ''
console.log(chkReadable(p, { ownKeys: true }))
// => 'keys are unreadable'

let a = [0]
Object.defineProperty(a, '0', { get: () => { throw new Error('x') } })
console.log(chkReadable(a, { elements: 'first' }))
// => '' (存取器不呼叫,拋錯無從偵測)

console.log(chkReadable({ x: { y: [1, 2, 3] } }, { deep: true }))
// => ''

console.log(chkReadable(1))
// => ''
Parameters:
Name Type Attributes Default Description
v *

輸入任意值

opt Object <optional>
{}

輸入設定物件,預設{}

Properties
Name Type Attributes Default Description
deep Boolean <optional>
false

輸入是否深探布林值,預設false

fun Boolean <optional>
false

輸入是否另做函數型讀取布林值,預設false

ownKeys Boolean <optional>
false

輸入是否讀自有鍵布林值,預設false

has Array <optional>
[]

輸入需做in探測之鍵(字串、Symbol或數字)陣列,預設[]

elements String <optional>
'none'

輸入陣列長度與元素之讀取方式字串,可選'none'、'first'、'all',預設'none'

maxElements Integer <optional>
1000000

輸入陣列長度上限(opt.elements為'all'與opt.deep時)非負整數,預設1000000

maxReads Integer <optional>
50000000

輸入深探之讀取總量上限(opt.deep時)非負整數,預設50000000,需無上限者傳Number.MAX_SAFE_INTEGER

Returns:

回傳''(可讀),或原因字串'tag is unreadable'、'function type is unreadable'、'key is unreadable'、'keys are unreadable'、'length is unreadable'、'length is not a non-negative safe integer'、'too many elements'、'element is unreadable'、'property is unreadable'、'structure is too large'、'unreadable'(保險:未預期之例外)

Type
String

(static) cint(v, optopt) → {Integer}

Description:
  • 數字或字串四捨五入轉整數 若輸入非數字則回傳0 轉型函數照舊拆包: 包裝物件new Number(1)、new String('1')先取出原始值再轉換(判斷函數isnum只收原始值,轉型函數不受影響)

    注意: 超出安全整數範圍(絕對值大於Number.MAX_SAFE_INTEGER)之數值轉換後會失真(如cint(2 ** 60)為1152921504606847000,已非原值;字串'9007199254740993'轉為9007199254740992),本函數行為不改。 要精確、可安全計算之整數,請先以iseint判斷(iseint(v)為true者其安全整數轉換無損,字串並檢查精度遺失),再以cint轉換;亦可用opt.useClampSafe鉗制或opt.useLimitSafe視為錯誤

    Unit Test: Github

Source:
Example
console.log(cint('1.5'))
// => 2

console.log(cint('-1.5'))
// => -1

console.log(cint(Infinity))
// => 1.7976931348623157e+308

console.log(cint(Infinity, { useClampSafe: true }))
// => 9007199254740991

console.log(cint(-Infinity, { useClampSafe: true }))
// => -9007199254740991

try {
    cint(Infinity, { useLimitSafe: true })
}
catch (err) {
    console.log(err.message)
    // => invalid v: must be a safe integer
}

console.log(cint(Infinity, { useLimitSafe: true, returnWithStateAndMsg: true }))
// => { state: 'error', msg: 'invalid v: must be a safe integer' }

console.log(cint('1.5', { returnWithStateAndMsg: true }))
// => { state: 'success', msg: 2 }
Parameters:
Name Type Attributes Default Description
v Number | String

輸入數字或字串

opt Object <optional>
{}

輸入設定物件,預設{}

Properties
Name Type Attributes Default Description
useClampSafe Boolean <optional>
false

輸入是否鉗制至安全整數範圍布林值,若為true則四捨五入後之整數超出安全整數範圍時取邊界值,大於Number.MAX_SAFE_INTEGER者取Number.MAX_SAFE_INTEGER、小於Number.MIN_SAFE_INTEGER者取Number.MIN_SAFE_INTEGER,預設false

useLimitSafe Boolean <optional>
false

輸入是否限制須為安全整數布林值,若為true則四捨五入後之整數超出安全整數範圍(即Number.isSafeInteger為false,含Infinity、-Infinity與絕對值大於Number.MAX_SAFE_INTEGER者)時視為錯誤,預設false。與opt.useClampSafe同時為true時因已先鉗制至安全整數範圍故不會觸發

returnWithStateAndMsg Boolean <optional>
false

輸入是否回傳含狀態與訊息物件布林值,若為true則回傳{ state, msg }物件,state為'success'或'error',msg於success時為回傳結果、於error時為錯誤訊息字串,預設false。預設false時錯誤仍以拋出錯誤表達,行為不變

Returns:

回傳四捨五入後整數;若opt.returnWithStateAndMsg為true則回傳{ state, msg }物件

Type
Integer

(static) clearXSS(inp) → {Object|Array|String}

Description:
  • 清除xss攻擊語法

    Depend on: https://jsxss.com/zh/index.html

    白名單外之標籤轉義,白名單內之標籤刪除白名單外之屬性與危險網址(style屬性保留),標籤外之文字只轉義會開始標籤之<(其後為英文字母、斜線、驚嘆號、問號或位於結尾),>與其餘之<維持原樣,故'a < b'等數學式不改寫

    輸出僅供以HTML內文呈現(如v-html、innerHTML),不可放入屬性值或註解內

    走訪採顯式堆疊並以來源物件之參照記憶化,不遞迴:深巢狀與循環參照不拋錯(循環保持),共用子結構只處理一次且輸出中保持共用,成本與節點數成正比,不設深度上限(僅受堆積限制)。處置如下:

    1. 字串清除(含包裝String,清除後為原始字串);空字串與number、boolean、null、undefined等非字串原值回傳

    2. 物件(含類別實例)與真陣列(含子類別)走訪並保留原型(null原型物件變一般物件),length視為一般鍵(不使走訪改為類陣列,不新增鍵),成本與length值無關;物件依自有可列舉之字串鍵與Symbol鍵,陣列依索引(空洞補undefined,非索引屬性不複製,正規表示式比對結果之index與input除外,其input亦清除);Map走訪值、Set走訪元素(Map之鍵不處理,清除後相同之Set元素合併),Map與Set之自有可列舉屬性一併走訪;不可列舉屬性不複製,原型上之資料不處理

    3. 物件之字串鍵與Map之鍵不清除,由使用端自行檢核

    4. arguments物件與以Symbol.toStringTag偽稱Array或Arguments之物件,視為物件並依自有可列舉鍵走訪,轉為一般物件

    5. Date、RegExp、型別陣列、Buffer、ArrayBuffer、包裝Number等回傳複本,其自有字串屬性不清除(物件值屬性依上述走訪);函數、Error、WeakMap、Promise、URL等不可複製者,巢狀時回傳同一參照而不清除其內字串,位於最外層時函數複製為一般物件(清除其可列舉屬性)、Error等回傳{};其餘經lodash cloneDeep複製後仍帶自訂Symbol.toStringTag之物件亦不清除其內字串

    6. 經lodash cloneDeep複製之物件(上述第4、5點以外之非一般物件,如類別實例、null原型物件、陣列子類別、自訂標籤者)沿用其複製行為(含原型上之setter),再依複本之終態逐鍵清除;除此之外輸入不被修改

    7. 清除對字串不保證冪等(如<b='<<>清一次與清兩次結果不同),已清除之值再送入可能再被改寫

    Unit Test: Github

Source:
Example
console.log(clearXSS(`><script>alert('XSS')</script>`))
// => `>&lt;script>alert('XSS')&lt;/script>`

console.log(clearXSS(`<img src="javascript:alert('XSS')">`))
// => `<img src>`

console.log(clearXSS(`孔深 < 500 m 且 > 10 m`))
// => `孔深 < 500 m 且 > 10 m`

console.log(clearXSS({ a: `<script>alert('XSS')</script>`, b: [1, `<b>x</b>`, { c: `<img src=x onerror=alert(1)>` }], d: new Map([['k', `<script>1</script>`]]) }))
// => { a: "&lt;script>alert('XSS')&lt;/script>", b: [ 1, '<b>x</b>', { c: '<img src>' } ], d: Map(1) { 'k' => '&lt;script>1&lt;/script>' } }
Parameters:
Name Type Description
inp String | Object | Array

輸入資料,可為字串,或含字串之物件、陣列、Map、Set

Returns:

輸出資料,字串輸入回傳清除後字串,其餘回傳清除後之新結構(原始值原樣回傳)

Type
Object | Array | String

(static) color() → {Object}

Description:
  • 顏色轉換

    輸入無效一律同步拋Error,訊息為固定字串、不含輸入值(V19、V20;原訊息回顯顏色字串與整個物件並以console.log輸出輸入值):

    1. 顏色參數(c、c1、c2)非字串亦非一般物件為'invalid color: must be a string or an object',字串或物件無法解析為顏色為'invalid color: must be a valid color';
    2. 調整量amount(modSaturate、modLighten、modBrighten、modHue)與權重w1、w2(mix)為必須參數,須為有效數字(有限數字或十進位數字字串,去頭尾空白後取值;NaN、Infinity、'0x10'、null、undefined、布林、包裝物件皆非有效數字)且介於0至1(含端點),判定通過後以cdbl轉為數字再使用(數字字串'0.5'與0.5結果相同,原以字串串接而得'rgb(NaN, NaN, NaN)'),否則為'invalid amount: must be a number from 0 to 1'、'invalid w1: must be a number from 0 to 1'、'invalid w2: must be a number from 0 to 1';
    3. 個數num(spreadHue、spreadMonochromatic)須為有效整數(數字字串亦可),否則為'invalid num: must be an integer';個數範圍為1至4294967295(use: 'count'且不小於1),超出範圍(0、負數、超過4294967295)視為未給而改用預設1,回傳只含輸入色一色之陣列(經fmtOutput轉出,不再回傳未轉出之rgba物件;修前超過上限者迴圈無上限而耗盡記憶體);
    4. 輸出格式fmtOutput須為輸出格式名稱之一(如'toRgbString',只認自有鍵,'constructor'等原型鏈成員名無效),否則為'invalid fmtOutput: must be one of the output formats';
    5. 檢測順序為顏色參數(解析)、amount或w1與w2、num、fmtOutput(轉出時);
    6. getBrightness、getLuminance之顏色須為不透明(alpha為1),否則為'invalid color: must have an alpha of 1'。

    Unit Test: Github

Source:
Example
import oc from 'wsemi/src/color.mjs'

let c
let c1
let c2
let r

c = '#cd'
r = oc.toRgbaString(c)
console.log(r)
// => rgba(205, 205, 205, 1)

c = '#6a3'
r = oc.toRgbaString(c)
console.log(r)
// => rgba(102, 170, 51, 1)

c = '#6b8e23'
r = oc.toRgbaString(c)
console.log(r)
// => rgba(107, 142, 35, 1)

c1 = '#cd'
c2 = 'hsl (320, 50%, 40%)'
r = oc.mix(c1, 0.5, c2, 0.5, 'toRgbString')
console.log(r)
// => rgb(179, 128, 162)

c1 = '#cd'
c2 = 'hsl (320, 50%, 40%)' //rgb(153, 51, 119)
r = oc.mix(c1, 0, c2, 1, 'toRgbString')
console.log(r)
// => rgb(153, 51, 119)

c1 = 'rgb(250, 120, 50)'
c2 = 'hsva (320, 100%, 50%, 0.1)'
r = oc.mix(c1, 0.5, c2, 0.5, 'toRgba')
console.log(r)
// => { r: 189, g: 60, b: 68, a: 0.55 }

c = 'rgb(250, 120, 50)'
r = oc.toRgbaString(c)
console.log(r)
// => rgba(250, 120, 50, 1)

c = 'rgb(250, 120, 50)'
r = oc.toHslaString(c)
console.log(r)
// => hsla(21, 0.952, 0.588, 1)

c = 'rgb(250, 120, 50)'
r = oc.toHsvaString(c)
console.log(r)
// => hsva(21, 0.8, 0.98, 1)

c = 'rgb(250, 120, 50)'
r = oc.toHexString(c)
console.log(r)
// => #fa7832

c = 'skyblue'
r = oc.toRgbaString(c)
console.log(r)
// => rgba(135, 206, 235, 1)

c = 'hsl (320, 50%, 40%)'
r = oc.toRgba(c)
console.log(r)
// => { r: 153, g: 51, b: 119, a: 1 }

c = 'hsva (320, 100%, 50%, 0.1)'
r = oc.toRgba(c)
console.log(r)
// => { r: 128, g: 0, b: 85, a: 0.1 }

c = { r: 255, g: 150, b: 50 }
r = oc.toHsla(c)
console.log(r)
// => { h: 29, s: 0.672, l: 0.002, a: 1 }

c = { r: '50%', g: 150, b: 50, a: 0.1 }
r = oc.toHsva(c)
console.log(r)
// => { h: 74, s: 0.667, v: 0.002, a: 0.1 }

c = { h: 320, s: 0.2, l: 0.15 }
r = oc.toRgba(c)
console.log(r)
// => { r: 46, g: 31, b: 31, a: 1 }

c = { h: 320, s: '12%', l: '8%', a: 0.1 }
r = oc.toRgba(c)
console.log(r)
// => { r: 23, g: 18, b: 18, a: 0.1 }

c = { h: 320, s: 0.2, v: 0.15 }
r = oc.toRgba(c)
console.log(r)
// => { r: 38, g: 31, b: 31, a: 1 }

c = { h: '50%', s: 0.2, l: 0.15 }
r = oc.toHexString(c)
console.log(r)
// => #1f2e2e

c = { h: '50%', s: 0.2, l: 0.15 }
r = oc.toRgbaString(c)
console.log(r)
// => rgba(31, 46, 46, 1)

c = { h: '50%', s: 0.2, l: 0.15 }
r = oc.toRgba(c)
console.log(r)
// => { r: 31, g: 46, b: 46, a: 1 }

c = { h: 180, s: 0.2, l: 0.15 }
r = oc.toHexString(c)
console.log(r)
// => #1f2e2e

c = { h: '50%', s: '12%', v: '8%', a: 0.1 }
r = oc.toRgba(c)
console.log(r)
// => { r: 20, g: 18, b: 18, a: 0.1 }

let gradient = {
    0: 'rgb(255, 255, 255)',
    0.2: 'rgb(254, 178, 76)',
    0.4: 'rgb(252, 78, 42)',
    0.6: 'rgb(220, 58, 38)',
    0.8: 'rgb(200, 40, 23)',
    1: 'rgba(180, 30, 60, 0.5)',
}
let fun = oc.interp(gradient)
console.log('fun(0)', fun(0))
//fun(0) rgba(255, 255, 255, 1)

console.log('fun(0.1)', fun(0.1))
//fun(0.1) rgba(255, 217, 166, 1)

console.log('fun(0.2)', fun(0.2))
//fun(0.2) rgba(254, 178, 76, 1)

console.log('fun(0.8)', fun(0.8))
//fun(0.8) rgba(200, 40, 23, 1)

console.log('fun(0.9)', fun(0.9))
//fun(0.9) rgba(190, 35, 42, 0.75)

console.log('fun(1)', fun(1))
//fun(1) rgba(180, 30, 60, 0.5)

console.log('fun(2)', fun(2))
//fun(2) null

console.log('fun(-1)', fun(-1))
//fun(-1) null
Returns:

回傳color物件,提供toRgbaString、toHslaString、toHsvaString、toHexString等共37種處理函數

Type
Object

(static) composeToTree(items, optopt) → {Array}

Description:
  • 組合關聯陣列成為樹狀陣列

    規則(使用者2026-11-14裁定):id與parentId只取項目之自有可列舉欄位,只有undefined、null、''視為無值(0為有效值);id以嚴格相等比對(1與'1'不同); parentId無值者為頂層;孤兒(parentId指向不存在之id)、循環(含指向自己)者放到頂層並保留原parentId,其子節點照常掛在其下,循環者以該循環中最先出現之項目為頂層而斷開;頂層依項目原順序排列; id須唯一,重複時子節點掛在最後一個同id之節點下;缺id(無值)者只能為葉節點;項目已有children(或opt.bindChildren所指欄位)時,子節點合併於其後(該欄位須為陣列,非陣列時拋出原生TypeError,同修前)

    Unit Test: Github

Source:
Example
let data = [
    {
        id: 1,
        text: '1-a',
    },
    {
        id: 2,
        text: '2-b',
    },
    {
        id: 3,
        text: '3-c',
        parentId: 2,
    },
    {
        id: 4,
        text: '4-d',
        parentId: 2,
    },
    {
        id: 5,
        text: '5-e',
        parentId: 3,
    },
    {
        id: 6,
        text: 'empty',
    },
]
let r = composeToTree(data)
let cr = JSON.stringify(r)
console.log(cr)
// => [
//   {
//     "id": 1,
//     "text": "1-a"
//   },
//   {
//     "id": 2,
//     "text": "2-b",
//     "children": [
//       {
//         "id": 3,
//         "text": "3-c",
//         "parentId": 2,
//         "children": [
//           {
//             "id": 5,
//             "text": "5-e",
//             "parentId": 3
//           }
//         ]
//       },
//       {
//         "id": 4,
//         "text": "4-d",
//         "parentId": 2
//       }
//     ]
//   },
//   {
//     "id": 6,
//     "text": "empty"
//   }
// ]

//id為0為有效值
console.log(JSON.stringify(composeToTree([{ id: 0, text: 'zero' }, { id: 1, parentId: 0, text: 'c' }])))
// => [{"id":0,"text":"zero","children":[{"id":1,"parentId":0,"text":"c"}]}]

//孤兒(parentId指向不存在之id)放到頂層並保留原parentId, 其子節點照常掛在其下
console.log(JSON.stringify(composeToTree([{ id: 1 }, { id: 2, parentId: 99 }, { id: 3, parentId: 2 }, { id: 4 }])))
// => [{"id":1},{"id":2,"parentId":99,"children":[{"id":3,"parentId":2}]},{"id":4}]

//循環以最先出現者為頂層而斷開, 指向自己者放到頂層
console.log(JSON.stringify(composeToTree([{ id: 9, parentId: 1 }, { id: 1, parentId: 2 }, { id: 2, parentId: 1 }, { id: 3, parentId: 3 }])))
// => [{"id":1,"parentId":2,"children":[{"id":9,"parentId":1},{"id":2,"parentId":1}]},{"id":3,"parentId":3}]

//id嚴格比對(1與'1'不同)
console.log(JSON.stringify(composeToTree([{ id: 1 }, { id: '1' }, { id: 3, parentId: 1 }])))
// => [{"id":1,"children":[{"id":3,"parentId":1}]},{"id":"1"}]

//id重複時子節點掛在最後一個
console.log(JSON.stringify(composeToTree([{ id: 1, a: 'first' }, { id: 1, a: 'last' }, { id: 2, parentId: 1 }])))
// => [{"id":1,"a":"first"},{"id":1,"a":"last","children":[{"id":2,"parentId":1}]}]

//輸入已有children時合併
console.log(JSON.stringify(composeToTree([{ id: 1, children: [{ x: 1 }] }, { id: 2, parentId: 1 }])))
// => [{"id":1,"children":[{"x":1},{"id":2,"parentId":1}]}]

//元素非物件或為空物件時拋錯
try {
    composeToTree([{ id: 1 }, null])
}
catch (err) {
    console.log(err.message)
}
// => invalid items[1]: must be a non-empty object
Parameters:
Name Type Attributes Default Description
items Array

輸入關聯陣列,非陣列或空陣列回傳空陣列[];元素須為有效物件(至少一個自有可列舉鍵),任一元素非物件或為空物件時拋出Error並指出第幾個(如'invalid items[0]: must be a non-empty object')

opt Object <optional>
{}

輸入設定物件,預設{}

Properties
Name Type Attributes Default Description
bindKey String <optional>
'id'

輸入項目物件識別用欄位字串,預設'id'

bindParent String <optional>
'parentId'

輸入項目物件內存放父節點欄位字串,預設'parentId'

bindChildren String <optional>
'children'

輸入產生樹狀物件時,各節點內存放子節點欄位字串,預設'children'

saveExtProps Boolean <optional>
false

輸入是否儲存項目物件從屬資訊布林值,預設false

Returns:

回傳樹狀陣列

Type
Array

(static) convertToTree(data, optopt) → {Array}

Description:
  • 展開物件或陣列成為樹狀陣列

    Unit Test: Github

Source:
Example
let r

let obj = {
    a: 1,
    b: 12.3,
    c: 'abc',
    d: '45-de',
    x: true,
    y: null,
    z: function() {},
    e: [],
    f: [
        91,
        912.3,
        'abc',
        '945-de',
        true,
        null,
        function() {},
        [
            5,
            54.3,
            'xyz',
        ]
    ],
    g: {},
    h: {
        ga: 81,
        gb: 812.3,
        gc: 'abc',
        gd: '845-de',
        ge: [
            71,
            712.3,
            'abc',
            '745-de',
            true,
            null,
            function() {},
        ],
        gf: {
            gfa: 61,
            gfb: 612.3,
            gfc: 'abc',
            gfd: '645-de',
            gfe: true,
            gff: null,
            gfg: function() {},
        },
        gx: true,
        gy: null,
        gz: function() {},
    },
    i: Symbol('foo'),
    [Symbol('i-sym-key-a')]: 'i-sym-value',
    [Symbol('i-sym-key-b')]: {
        symfa: 61,
        symfb: 612.3,
        symfc: 'abc',
        symfd: '645-de',
        symfe: true,
        symff: null,
        symfg: function() {},
    },
}
r = convertToTree(obj)
console.log('convertToTree obj', JSON.stringify(r, null, 2))
// => convertToTree obj [
//   {
//     "id": "root",
//     "parentId": "",
//     "type": "object",
//     "key": "root",
//     "numOfChilren": 12,
//     "children": [
//       {
//         "id": "root-a",
//         "parentId": "root",
//         "type": "node",
//         "key": "a",
//         "text": 1
//       },
//       {
//         "id": "root-b",
//         "parentId": "root",
//         "type": "node",
//         "key": "b",
//         "text": 12.3
//       },
//       {
//         "id": "root-c",
//         "parentId": "root",
//         "type": "node",
//         "key": "c",
//         "text": "abc"
//       },
//       {
//         "id": "root-d",
//         "parentId": "root",
//         "type": "node",
//         "key": "d",
//         "text": "45-de"
//       },
//       {
//         "id": "root-x",
//         "parentId": "root",
//         "type": "node",
//         "key": "x",
//         "text": true
//       },
//       {
//         "id": "root-y",
//         "parentId": "root",
//         "type": "node",
//         "key": "y",
//         "text": null
//       },
//       {
//         "id": "root-z",
//         "parentId": "root",
//         "type": "node",
//         "key": "z"
//       },
//       {
//         "id": "root-e",
//         "parentId": "root",
//         "type": "array",
//         "key": "e",
//         "numOfChilren": 0
//       },
//       {
//         "id": "root-f",
//         "parentId": "root",
//         "type": "array",
//         "key": "f",
//         "numOfChilren": 8,
//         "children": [
//           {
//             "id": "root-f-0",
//             "parentId": "root-f",
//             "type": "node",
//             "key": 0,
//             "text": 91
//           },
//           {
//             "id": "root-f-1",
//             "parentId": "root-f",
//             "type": "node",
//             "key": 1,
//             "text": 912.3
//           },
//           {
//             "id": "root-f-2",
//             "parentId": "root-f",
//             "type": "node",
//             "key": 2,
//             "text": "abc"
//           },
//           {
//             "id": "root-f-3",
//             "parentId": "root-f",
//             "type": "node",
//             "key": 3,
//             "text": "945-de"
//           },
//           {
//             "id": "root-f-4",
//             "parentId": "root-f",
//             "type": "node",
//             "key": 4,
//             "text": true
//           },
//           {
//             "id": "root-f-5",
//             "parentId": "root-f",
//             "type": "node",
//             "key": 5,
//             "text": null
//           },
//           {
//             "id": "root-f-6",
//             "parentId": "root-f",
//             "type": "node",
//             "key": 6
//           },
//           {
//             "id": "root-f-7",
//             "parentId": "root-f",
//             "type": "array",
//             "key": 7,
//             "numOfChilren": 3,
//             "children": [
//               {
//                 "id": "root-f-7-0",
//                 "parentId": "root-f-7",
//                 "type": "node",
//                 "key": 0,
//                 "text": 5
//               },
//               {
//                 "id": "root-f-7-1",
//                 "parentId": "root-f-7",
//                 "type": "node",
//                 "key": 1,
//                 "text": 54.3
//               },
//               {
//                 "id": "root-f-7-2",
//                 "parentId": "root-f-7",
//                 "type": "node",
//                 "key": 2,
//                 "text": "xyz"
//               }
//             ]
//           }
//         ]
//       },
//       {
//         "id": "root-g",
//         "parentId": "root",
//         "type": "object",
//         "key": "g",
//         "numOfChilren": 0
//       },
//       {
//         "id": "root-h",
//         "parentId": "root",
//         "type": "object",
//         "key": "h",
//         "numOfChilren": 9,
//         "children": [
//           {
//             "id": "root-h-ga",
//             "parentId": "root-h",
//             "type": "node",
//             "key": "ga",
//             "text": 81
//           },
//           {
//             "id": "root-h-gb",
//             "parentId": "root-h",
//             "type": "node",
//             "key": "gb",
//             "text": 812.3
//           },
//           {
//             "id": "root-h-gc",
//             "parentId": "root-h",
//             "type": "node",
//             "key": "gc",
//             "text": "abc"
//           },
//           {
//             "id": "root-h-gd",
//             "parentId": "root-h",
//             "type": "node",
//             "key": "gd",
//             "text": "845-de"
//           },
//           {
//             "id": "root-h-ge",
//             "parentId": "root-h",
//             "type": "array",
//             "key": "ge",
//             "numOfChilren": 7,
//             "children": [
//               {
//                 "id": "root-h-ge-0",
//                 "parentId": "root-h-ge",
//                 "type": "node",
//                 "key": 0,
//                 "text": 71
//               },
//               {
//                 "id": "root-h-ge-1",
//                 "parentId": "root-h-ge",
//                 "type": "node",
//                 "key": 1,
//                 "text": 712.3
//               },
//               {
//                 "id": "root-h-ge-2",
//                 "parentId": "root-h-ge",
//                 "type": "node",
//                 "key": 2,
//                 "text": "abc"
//               },
//               {
//                 "id": "root-h-ge-3",
//                 "parentId": "root-h-ge",
//                 "type": "node",
//                 "key": 3,
//                 "text": "745-de"
//               },
//               {
//                 "id": "root-h-ge-4",
//                 "parentId": "root-h-ge",
//                 "type": "node",
//                 "key": 4,
//                 "text": true
//               },
//               {
//                 "id": "root-h-ge-5",
//                 "parentId": "root-h-ge",
//                 "type": "node",
//                 "key": 5,
//                 "text": null
//               },
//               {
//                 "id": "root-h-ge-6",
//                 "parentId": "root-h-ge",
//                 "type": "node",
//                 "key": 6
//               }
//             ]
//           },
//           {
//             "id": "root-h-gf",
//             "parentId": "root-h",
//             "type": "object",
//             "key": "gf",
//             "numOfChilren": 7,
//             "children": [
//               {
//                 "id": "root-h-gf-gfa",
//                 "parentId": "root-h-gf",
//                 "type": "node",
//                 "key": "gfa",
//                 "text": 61
//               },
//               {
//                 "id": "root-h-gf-gfb",
//                 "parentId": "root-h-gf",
//                 "type": "node",
//                 "key": "gfb",
//                 "text": 612.3
//               },
//               {
//                 "id": "root-h-gf-gfc",
//                 "parentId": "root-h-gf",
//                 "type": "node",
//                 "key": "gfc",
//                 "text": "abc"
//               },
//               {
//                 "id": "root-h-gf-gfd",
//                 "parentId": "root-h-gf",
//                 "type": "node",
//                 "key": "gfd",
//                 "text": "645-de"
//               },
//               {
//                 "id": "root-h-gf-gfe",
//                 "parentId": "root-h-gf",
//                 "type": "node",
//                 "key": "gfe",
//                 "text": true
//               },
//               {
//                 "id": "root-h-gf-gff",
//                 "parentId": "root-h-gf",
//                 "type": "node",
//                 "key": "gff",
//                 "text": null
//               },
//               {
//                 "id": "root-h-gf-gfg",
//                 "parentId": "root-h-gf",
//                 "type": "node",
//                 "key": "gfg"
//               }
//             ]
//           },
//           {
//             "id": "root-h-gx",
//             "parentId": "root-h",
//             "type": "node",
//             "key": "gx",
//             "text": true
//           },
//           {
//             "id": "root-h-gy",
//             "parentId": "root-h",
//             "type": "node",
//             "key": "gy",
//             "text": null
//           },
//           {
//             "id": "root-h-gz",
//             "parentId": "root-h",
//             "type": "node",
//             "key": "gz"
//           }
//         ]
//       },
//       {
//         "id": "root-i",
//         "parentId": "root",
//         "type": "node",
//         "key": "i"
//       },
//       {
//         "id": "root-Symbol(i-sym-key-a)",
//         "parentId": "root",
//         "type": "node",
//         "text": "i-sym-value"
//       },
//       {
//         "id": "root-Symbol(i-sym-key-b)",
//         "parentId": "root",
//         "type": "object",
//         "numOfChilren": 7,
//         "children": [
//           {
//             "id": "root-Symbol(i-sym-key-b)-symfa",
//             "parentId": "root-Symbol(i-sym-key-b)",
//             "type": "node",
//             "key": "symfa",
//             "text": 61
//           },
//           {
//             "id": "root-Symbol(i-sym-key-b)-symfb",
//             "parentId": "root-Symbol(i-sym-key-b)",
//             "type": "node",
//             "key": "symfb",
//             "text": 612.3
//           },
//           {
//             "id": "root-Symbol(i-sym-key-b)-symfc",
//             "parentId": "root-Symbol(i-sym-key-b)",
//             "type": "node",
//             "key": "symfc",
//             "text": "abc"
//           },
//           {
//             "id": "root-Symbol(i-sym-key-b)-symfd",
//             "parentId": "root-Symbol(i-sym-key-b)",
//             "type": "node",
//             "key": "symfd",
//             "text": "645-de"
//           },
//           {
//             "id": "root-Symbol(i-sym-key-b)-symfe",
//             "parentId": "root-Symbol(i-sym-key-b)",
//             "type": "node",
//             "key": "symfe",
//             "text": true
//           },
//           {
//             "id": "root-Symbol(i-sym-key-b)-symff",
//             "parentId": "root-Symbol(i-sym-key-b)",
//             "type": "node",
//             "key": "symff",
//             "text": null
//           },
//           {
//             "id": "root-Symbol(i-sym-key-b)-symfg",
//             "parentId": "root-Symbol(i-sym-key-b)",
//             "type": "node",
//             "key": "symfg"
//           }
//         ]
//       }
//     ]
//   }
// ]

let arr = [
    91,
    912.3,
    'abc',
    '945-de',
    true,
    null,
    function() {},
    [
        5,
        54.3,
        'xyz',
        {
            gf: {
                gfa: 61,
                gfb: 612.3,
                gfc: 'abc',
                gfd: '645-de',
                gfe: true,
                gff: null,
                gfg: function() {},
            },
        },
    ],
    {
        h: {
            ga: 81,
            gb: 812.3,
            gc: 'abc',
            gd: '845-de',
            ge: [
                71,
                712.3,
                'abc',
                '745-de',
                true,
                null,
                function() {},
            ],
            gx: true,
            gy: null,
            gz: function() {},
        },
        i: Symbol('foo'),
        [Symbol('i-sym-key-a')]: 'i-sym-value',
        [Symbol('i-sym-key-b')]: {
            symfa: 61,
            symfb: 612.3,
            symfc: 'abc',
            symfd: '645-de',
            symfe: true,
            symff: null,
            symfg: function() {},
        },
    },
]
r = convertToTree(arr)
console.log('convertToTree arr', JSON.stringify(r, null, 2))
// => convertToTree arr [
//   {
//     "id": "root",
//     "parentId": "",
//     "type": "array",
//     "key": "root",
//     "numOfChilren": 9,
//     "children": [
//       {
//         "id": "root-0",
//         "parentId": "root",
//         "type": "node",
//         "key": 0,
//         "text": 91
//       },
//       {
//         "id": "root-1",
//         "parentId": "root",
//         "type": "node",
//         "key": 1,
//         "text": 912.3
//       },
//       {
//         "id": "root-2",
//         "parentId": "root",
//         "type": "node",
//         "key": 2,
//         "text": "abc"
//       },
//       {
//         "id": "root-3",
//         "parentId": "root",
//         "type": "node",
//         "key": 3,
//         "text": "945-de"
//       },
//       {
//         "id": "root-4",
//         "parentId": "root",
//         "type": "node",
//         "key": 4,
//         "text": true
//       },
//       {
//         "id": "root-5",
//         "parentId": "root",
//         "type": "node",
//         "key": 5,
//         "text": null
//       },
//       {
//         "id": "root-6",
//         "parentId": "root",
//         "type": "node",
//         "key": 6
//       },
//       {
//         "id": "root-7",
//         "parentId": "root",
//         "type": "array",
//         "key": 7,
//         "numOfChilren": 4,
//         "children": [
//           {
//             "id": "root-7-0",
//             "parentId": "root-7",
//             "type": "node",
//             "key": 0,
//             "text": 5
//           },
//           {
//             "id": "root-7-1",
//             "parentId": "root-7",
//             "type": "node",
//             "key": 1,
//             "text": 54.3
//           },
//           {
//             "id": "root-7-2",
//             "parentId": "root-7",
//             "type": "node",
//             "key": 2,
//             "text": "xyz"
//           },
//           {
//             "id": "root-7-3",
//             "parentId": "root-7",
//             "type": "object",
//             "key": 3,
//             "numOfChilren": 1,
//             "children": [
//               {
//                 "id": "root-7-3-gf",
//                 "parentId": "root-7-3",
//                 "type": "object",
//                 "key": "gf",
//                 "numOfChilren": 7,
//                 "children": [
//                   {
//                     "id": "root-7-3-gf-gfa",
//                     "parentId": "root-7-3-gf",
//                     "type": "node",
//                     "key": "gfa",
//                     "text": 61
//                   },
//                   {
//                     "id": "root-7-3-gf-gfb",
//                     "parentId": "root-7-3-gf",
//                     "type": "node",
//                     "key": "gfb",
//                     "text": 612.3
//                   },
//                   {
//                     "id": "root-7-3-gf-gfc",
//                     "parentId": "root-7-3-gf",
//                     "type": "node",
//                     "key": "gfc",
//                     "text": "abc"
//                   },
//                   {
//                     "id": "root-7-3-gf-gfd",
//                     "parentId": "root-7-3-gf",
//                     "type": "node",
//                     "key": "gfd",
//                     "text": "645-de"
//                   },
//                   {
//                     "id": "root-7-3-gf-gfe",
//                     "parentId": "root-7-3-gf",
//                     "type": "node",
//                     "key": "gfe",
//                     "text": true
//                   },
//                   {
//                     "id": "root-7-3-gf-gff",
//                     "parentId": "root-7-3-gf",
//                     "type": "node",
//                     "key": "gff",
//                     "text": null
//                   },
//                   {
//                     "id": "root-7-3-gf-gfg",
//                     "parentId": "root-7-3-gf",
//                     "type": "node",
//                     "key": "gfg"
//                   }
//                 ]
//               }
//             ]
//           }
//         ]
//       },
//       {
//         "id": "root-8",
//         "parentId": "root",
//         "type": "object",
//         "key": 8,
//         "numOfChilren": 2,
//         "children": [
//           {
//             "id": "root-8-h",
//             "parentId": "root-8",
//             "type": "object",
//             "key": "h",
//             "numOfChilren": 8,
//             "children": [
//               {
//                 "id": "root-8-h-ga",
//                 "parentId": "root-8-h",
//                 "type": "node",
//                 "key": "ga",
//                 "text": 81
//               },
//               {
//                 "id": "root-8-h-gb",
//                 "parentId": "root-8-h",
//                 "type": "node",
//                 "key": "gb",
//                 "text": 812.3
//               },
//               {
//                 "id": "root-8-h-gc",
//                 "parentId": "root-8-h",
//                 "type": "node",
//                 "key": "gc",
//                 "text": "abc"
//               },
//               {
//                 "id": "root-8-h-gd",
//                 "parentId": "root-8-h",
//                 "type": "node",
//                 "key": "gd",
//                 "text": "845-de"
//               },
//               {
//                 "id": "root-8-h-ge",
//                 "parentId": "root-8-h",
//                 "type": "array",
//                 "key": "ge",
//                 "numOfChilren": 7,
//                 "children": [
//                   {
//                     "id": "root-8-h-ge-0",
//                     "parentId": "root-8-h-ge",
//                     "type": "node",
//                     "key": 0,
//                     "text": 71
//                   },
//                   {
//                     "id": "root-8-h-ge-1",
//                     "parentId": "root-8-h-ge",
//                     "type": "node",
//                     "key": 1,
//                     "text": 712.3
//                   },
//                   {
//                     "id": "root-8-h-ge-2",
//                     "parentId": "root-8-h-ge",
//                     "type": "node",
//                     "key": 2,
//                     "text": "abc"
//                   },
//                   {
//                     "id": "root-8-h-ge-3",
//                     "parentId": "root-8-h-ge",
//                     "type": "node",
//                     "key": 3,
//                     "text": "745-de"
//                   },
//                   {
//                     "id": "root-8-h-ge-4",
//                     "parentId": "root-8-h-ge",
//                     "type": "node",
//                     "key": 4,
//                     "text": true
//                   },
//                   {
//                     "id": "root-8-h-ge-5",
//                     "parentId": "root-8-h-ge",
//                     "type": "node",
//                     "key": 5,
//                     "text": null
//                   },
//                   {
//                     "id": "root-8-h-ge-6",
//                     "parentId": "root-8-h-ge",
//                     "type": "node",
//                     "key": 6
//                   }
//                 ]
//               },
//               {
//                 "id": "root-8-h-gx",
//                 "parentId": "root-8-h",
//                 "type": "node",
//                 "key": "gx",
//                 "text": true
//               },
//               {
//                 "id": "root-8-h-gy",
//                 "parentId": "root-8-h",
//                 "type": "node",
//                 "key": "gy",
//                 "text": null
//               },
//               {
//                 "id": "root-8-h-gz",
//                 "parentId": "root-8-h",
//                 "type": "node",
//                 "key": "gz"
//               }
//             ]
//           },
//           {
//             "id": "root-8-i",
//             "parentId": "root-8",
//             "type": "node",
//             "key": "i"
//           },
//           {
//             "id": "root-8-Symbol(i-sym-key-a)",
//             "parentId": "root-8",
//             "type": "node",
//             "text": "i-sym-value"
//           },
//           {
//             "id": "root-8-Symbol(i-sym-key-b)",
//             "parentId": "root-8",
//             "type": "object",
//             "numOfChilren": 7,
//             "children": [
//               {
//                 "id": "root-8-Symbol(i-sym-key-b)-symfa",
//                 "parentId": "root-8-Symbol(i-sym-key-b)",
//                 "type": "node",
//                 "key": "symfa",
//                 "text": 61
//               },
//               {
//                 "id": "root-8-Symbol(i-sym-key-b)-symfb",
//                 "parentId": "root-8-Symbol(i-sym-key-b)",
//                 "type": "node",
//                 "key": "symfb",
//                 "text": 612.3
//               },
//               {
//                 "id": "root-8-Symbol(i-sym-key-b)-symfc",
//                 "parentId": "root-8-Symbol(i-sym-key-b)",
//                 "type": "node",
//                 "key": "symfc",
//                 "text": "abc"
//               },
//               {
//                 "id": "root-8-Symbol(i-sym-key-b)-symfd",
//                 "parentId": "root-8-Symbol(i-sym-key-b)",
//                 "type": "node",
//                 "key": "symfd",
//                 "text": "645-de"
//               },
//               {
//                 "id": "root-8-Symbol(i-sym-key-b)-symfe",
//                 "parentId": "root-8-Symbol(i-sym-key-b)",
//                 "type": "node",
//                 "key": "symfe",
//                 "text": true
//               },
//               {
//                 "id": "root-8-Symbol(i-sym-key-b)-symff",
//                 "parentId": "root-8-Symbol(i-sym-key-b)",
//                 "type": "node",
//                 "key": "symff",
//                 "text": null
//               },
//               {
//                 "id": "root-8-Symbol(i-sym-key-b)-symfg",
//                 "parentId": "root-8-Symbol(i-sym-key-b)",
//                 "type": "node",
//                 "key": "symfg"
//               }
//             ]
//           }
//         ]
//       }
//     ]
//   }
// ]
Parameters:
Name Type Attributes Default Description
data Array | Object

輸入項目物件或陣列,須為非空物件或非空陣列,否則回傳[];單一空元素之陣列([null]、['']、[{}])視為一個元素,轉為只含該元素之樹(不被當成空陣列)

opt Object <optional>
{}

輸入設定物件,預設{}

Properties
Name Type Attributes Default Description
bindKey String <optional>
'id'

輸入識別用欄位字串,預設'id'

bindParent String <optional>
'parentId'

輸入存放父節點欄位字串,預設'parentId'

bindText String <optional>
'text'

輸入存放值欄位字串,預設'text'

bindChildren String <optional>
'children'

輸入產生樹狀物件時,各節點內存放子節點欄位字串,預設'children'

bindType String <optional>
'type'

輸入存放值種類欄位字串,預設'type'

bindNumOfChilren String <optional>
'numOfChilren'

輸入存放值為物件或陣列時所屬子節點數量欄位字串,預設'numOfChilren'

bindRoot String <optional>
'root'

輸入若為物件時,自動給予根節點鍵值字串,預設'root'

saveExtProps Boolean <optional>
false

輸入是否儲存項目物件從屬資訊布林值,預設false

Returns:

回傳樹狀陣列

Type
Array

(static) copyStrToClipboard(str, optopt) → {String}

Description:
  • 複製字串至剪貼簿

    Unit Test: Github

Source:
Example
copyStrToClipboard('The Woodman(樵夫) set to work at once, and so...')

let ele = document.querySelector('#id')
copyStrToClipboard('The Woodman(樵夫) set to work at once, and so...', { eleParent: ele })
Parameters:
Name Type Attributes Default Description
str String

輸入欲複製至剪貼簿的字串,非字串則拋錯

opt Object <optional>
{}

輸入設定物件,預設{}

Properties
Name Type Attributes Default Description
eleParent HTMLElement <optional>
document.body

輸入臨時插入的父層元素,因例如於鎖定焦點(focus)的區域內要複製字串,會因臨時創建的textarea元素無法聚焦導致無法複製至剪貼簿,故得由外部傳入可聚焦的父層元素供創建textarea之用,非元素則使用document.body,預設document.body

Throws:

str非字串拋出Error('invalid str: must be a string')且不建立任何元素;臨時textarea無法取得焦點拋出Error('ele can not be focused');document.execCommand('copy')拋錯或回傳false拋出Error('can not copy str to clipboard');訊息不含輸入值且不外洩內部錯誤,臨時建立之textarea不論成敗皆已移除

Type
Error
Returns:

回傳字串,複製成功則為空字串,失敗(含非預期輸入)皆經拋錯回報而不回傳訊息字串

Type
String

(static) core(t, tNowopt, optopt) → {Object}

Description:
  • 毫秒時間轉過去時間

    err之值分兩類:'invalid t: must be a time string YYYY-MM-DDTHH:mm:ss.SSS with a time zone (Z, +HH:mm or -HH:mm)'(t無效)、'時間轉換失敗'為失敗(狀態模式下為state: 'error');'時間未到'為算得之結果(狀態模式下為state: 'success');正常算得時err為'' 轉換方式:時刻依其時區之固定偏移解析為絕對時刻(不經本機時間往返)後計算時間差;「今天、昨天、明天」之日界與顯示之時:分依本機時區

    Unit Test: Github

Source:
Example
let t
let tNow = '2020-10-18T12:34:56.987+08:00'
let r

t = '2020-10-18T12:34:54.987+08:00'
r = timemsTZ2past(t, tNow)
console.log(r)
// => { today: true, msg: '2秒前', err: '' }

t = '2020-10-18T04:34:54.987+00:00'
r = timemsTZ2past(t, tNow)
console.log(r)
// => { today: true, msg: '2秒前', err: '' }

t = '2020-10-18T04:34:54.987Z'
r = timemsTZ2past(t, tNow)
console.log(r)
// => { today: true, msg: '2秒前', err: '' }

t = '2020-10-18T12:34:55.500+08:00'
r = timemsTZ2past(t, tNow)
console.log(r)
// => { today: true, msg: '1秒前', err: '' }

t = '2020-10-18T12:31:54.987+08:00'
r = timemsTZ2past(t, tNow)
console.log(r)
// => { today: true, msg: '3分鐘前', err: '' }

t = '2020-10-18T08:31:54.987+08:00'
r = timemsTZ2past(t, tNow)
console.log(r)
// => { today: true, msg: '4小時前', err: '' }

t = '2020-10-13T08:31:54.987+08:00'
r = timemsTZ2past(t, tNow)
console.log(r)
// => { today: false, msg: '5天前', err: '' }

t = '2020-04-13T08:31:54.987+08:00'
r = timemsTZ2past(t, tNow)
console.log(r)
// => { today: false, msg: '6個月前', err: '' }

t = '2013-04-13T08:31:54.987+08:00'
r = timemsTZ2past(t, tNow)
console.log(r)
// => { today: false, msg: '7年前', err: '' }

t = '2023-04-13T08:31:54.987+08:00'
r = timemsTZ2past(t, tNow)
console.log(r)
// => { today: null, msg: '', err: '時間未到' }
Parameters:
Name Type Attributes Default Description
t String

輸入毫秒時間字串

tNow String <optional>
null

輸入現在毫秒時間字串

opt Object <optional>
{}

輸入設定物件,預設{}

Properties
Name Type Attributes Default Description
returnWithStateAndMsg Boolean <optional>
false

輸入是否回傳含狀態與訊息物件布林值,若為true則回傳{ state, msg }物件,state為'success'或'error',msg於success時為回傳結果、於error時為錯誤訊息字串,預設false

Returns:

回傳物件,含today、msg、err三欄位;t非有效毫秒時間字串時回傳{ today: null, msg: '', err: 'invalid t: must be a time string YYYY-MM-DDTHH:mm:ss.SSS with a time zone (Z, +HH:mm or -HH:mm)' },時間未到時回傳{ today: null, msg: '', err: '時間未到' };若opt.returnWithStateAndMsg為true則回傳{ state, msg }物件,其中時間未到屬算得之結果故state仍為'success'

Type
Object

(static) cosd(deg) → {Number}

Description:
  • 輸入角度計算cos值

    deg須為有效數字(isenum: 有限數字,或去頭尾空白後為十進位寫法之數字字串),其餘(Infinity、'Infinity'、'0x10'、'1e400'、'-'、''、null、包裝物件等)回傳null。

    Unit Test: Github

Source:
Example
console.log(cosd(0))
// => 1

console.log(cosd(30))
// => 0.8660254037844387

console.log(cosd(45))
// => 0.7071067811865476

console.log(cosd(60))
// => 0.5000000000000001

console.log(cosd(90))
// => 6.123233995736766e-17

console.log(cosd(120))
// => -0.4999999999999998

console.log(cosd(135))
// => -0.7071067811865475

console.log(cosd(150))
// => -0.8660254037844387

console.log(cosd(180))
// => -1

console.log(cosd(210))
// => -0.8660254037844386

console.log(cosd(225))
// => -0.7071067811865477

console.log(cosd(240))
// => -0.5000000000000004

console.log(cosd(270))
// => -1.8369701987210297e-16

console.log(cosd(300))
// => 0.5000000000000001

console.log(cosd(315))
// => 0.7071067811865474

console.log(cosd(330))
// => 0.8660254037844384

console.log(cosd(360))
// => 1

console.log(cosd(450))
// => 3.061616997868383e-16

console.log(cosd(720))
// => 1

console.log(cosd(' 60 '))
// => 0.5000000000000001

console.log(cosd(Infinity))
// => null

console.log(cosd('0x10'))
// => null
Parameters:
Name Type Description
deg Number | String

輸入角度,需為有效數字(數字或數字字串,定義見isenum,不收Infinity與'0x10'等),非有效數字時回傳null

Returns:

回傳cos值,deg非有效數字時回傳null

Type
Number

(static) cotd(deg) → {Number}

Description:
  • 輸入角度計算cot值

    deg須為有效數字(isenum: 有限數字,或去頭尾空白後為十進位寫法之數字字串),其餘(Infinity、'Infinity'、'0x10'、'1e400'、'-'、''、null、包裝物件等)回傳null。

    Unit Test: Github

Source:
Example
console.log(cotd(0))
// => Infinity

console.log(cotd(30))
// => 1.7320508075688774

console.log(cotd(45))
// => 1.0000000000000002

console.log(cotd(60))
// => 0.577350269189626

console.log(cotd(90))
// => 6.123233995736766e-17

console.log(cotd(120))
// => -0.5773502691896254

console.log(cotd(135))
// => -0.9999999999999998

console.log(cotd(150))
// => -1.7320508075688774

console.log(cotd(180))
// => -8165619676597685

console.log(cotd(210))
// => 1.7320508075688767

console.log(cotd(225))
// => 1.0000000000000004

console.log(cotd(240))
// => 0.5773502691896264

console.log(cotd(270))
// => 1.83697019872103e-16

console.log(cotd(300))
// => -0.5773502691896258

console.log(cotd(315))
// => -0.9999999999999996

console.log(cotd(330))
// => -1.7320508075688754

console.log(cotd(360))
// => -4082809838298842.5

console.log(cotd(450))
// => 3.061616997868383e-16

console.log(cotd(720))
// => -2041404919149421.2

console.log(cotd(Infinity))
// => null

console.log(cotd('0x10'))
// => null
Parameters:
Name Type Description
deg Number | String

輸入角度,需為有效數字(數字或數字字串,定義見isenum,不收Infinity與'0x10'等),非有效數字時回傳null

Returns:

回傳cot值,deg非有效數字時回傳null

Type
Number

(static) createExcelWorkbook() → {Object}

Description:
  • 產生Excel的Workbook空物件

    Workbook物件格式為{ sheets: [] },各分頁為{ name, rows }物件,可交由addExcelWorksheetFromData添加分頁、getExcelU8ArrFromWorkbook輸出檔案

    Unit Test: Github

Source:
Example
let wb = createExcelWorkbook()
console.log(wb)
// => { sheets: [] }
Returns:

回傳Excel的Workbook物件

Type
Object

(static) cscd(deg) → {Number}

Description:
  • 輸入角度計算csc值

    deg須為有效數字(isenum: 有限數字,或去頭尾空白後為十進位寫法之數字字串),其餘(Infinity、'Infinity'、'0x10'、'1e400'、'-'、''、null、包裝物件等)回傳null。

    Unit Test: Github

Source:
Example
console.log(cscd(0))
// => Infinity

console.log(cscd(30))
// => 2.0000000000000004

console.log(cscd(45))
// => 1.4142135623730951

console.log(cscd(60))
// => 1.1547005383792517

console.log(cscd(90))
// => 1

console.log(cscd(120))
// => 1.1547005383792515

console.log(cscd(135))
// => 1.414213562373095

console.log(cscd(150))
// => 2.0000000000000004

console.log(cscd(180))
// => 8165619676597685

console.log(cscd(210))
// => -1.9999999999999996

console.log(cscd(225))
// => -1.4142135623730951

console.log(cscd(240))
// => -1.1547005383792517

console.log(cscd(270))
// => -1

console.log(cscd(300))
// => -1.1547005383792517

console.log(cscd(315))
// => -1.4142135623730947

console.log(cscd(330))
// => -1.9999999999999982

console.log(cscd(360))
// => -4082809838298842.5

console.log(cscd(450))
// => 1

console.log(cscd(720))
// => -2041404919149421.2

console.log(cscd(Infinity))
// => null

console.log(cscd('0x10'))
// => null
Parameters:
Name Type Description
deg Number | String

輸入角度,需為有效數字(數字或數字字串,定義見isenum,不收Infinity與'0x10'等),非有效數字時回傳null

Returns:

回傳csc值,deg非有效數字時回傳null

Type
Number

(static) cstr(v) → {String}

Description:
  • 輸入轉字串 若輸入不是字串、數字、Symbol、BigInt時則回傳空字串 轉型函數照舊拆包: 包裝物件new String('a')、new Number(1)先取出原始值再轉換(判斷函數isestr、isnum只收原始值,轉型函數不受影響)

    Unit Test: Github

Source:
Example
console.log(cstr(2.25))
// => '2.25'

console.log(cstr(123n))
// => '123'

console.log(cstr(BigInt('9007199254740993')))
// => '9007199254740993' (超過Number.MAX_SAFE_INTEGER, BigInt精確保留)
Parameters:
Name Type Description
v String | Number | Symbol | BigInt

輸入資料

Returns:

回傳字串

Type
String

(static) cvOrmFind(find, optopt) → {Object}

Description:
  • w-orm系列條件(find)之形狀檢核與正規化,回傳全新之null原型深複本,不合白名單者同步拋錯

    輸入為任意值:undefined與一般物件{}為全部(回傳空的null原型物件),其餘依系列白名單檢核,通過者回傳全新複本(物件皆為null原型、陣列為全新密集陣列、Date為新Date,與輸入無任何共用參照),後續一律只使用複本。

    白名單:

    1. 頂層與每層條件物件須為一般物件(原型為Object.prototype或null),null、陣列、字串、數值、布林、函數、Date、RegExp、Map、Set、類別實例等一律reject,不得視同{};原型被改為null或Object.prototype之Map、Set、WeakMap、WeakSet、Promise、ArrayBuffer、DataView、TypedArray、Symbol與BigInt包裝、WeakRef、FinalizationRegistry等內建品牌物件,於任何位置(頂層、欄位運算子物件、$and/$or元素,空或帶自有鍵)亦reject;頂層空物件(代表全部)須可證明為真實空物件,Proxy與不可複製之宿主物件不視為全部

    2. 欄位等值{欄: 純量},多欄隱含AND;純量為字串、有限數字(含-0)、布林、有效Date,字串不得含NUL與孤立代理字元;null僅可用於欄位等值、$eq、$ne

    3. 欄位運算子:$eq $ne $gt $gte $lt $lte(值為純量)、$in $nin(值為純量陣列,元素不收null;$in:[]允許為恆假,$nin:[]reject),運算子物件須至少一個運算子

    4. 文件層邏輯:$and、$or(值為非空陣列,元素為非空條件物件),可巢狀、可與欄位鍵並列

    5. 欄名:1~128字元(UTF-16碼元),符合^[\p{L}][\p{L}\p{M}\p{N}]*$且非__proto__;點路徑、$開頭、連字號、空白、引號等一律reject

    6. 其餘一律reject(整批性、不得靜默忽略):$not $nor $regex $options $exists $type $where $expr $function $elemMatch $size $all $mod $like $ilike $custom等白名單外運算子、欄位層$and/$or、子查詢、Symbol鍵、函數值、BigInt、Buffer、RegExp、NaN、±Infinity、無效Date、undefined、包裝物件

    7. 異常結構一律reject:存取器屬性、不可列舉屬性、Symbol鍵、陣列之洞與額外屬性、length非非負整數之陣列;每個屬性與元素只讀一次並只使用該次所讀之值,帶length鍵之一般物件(如{length:3})之length為一般欄名

    8. 上限(opt只可下調,不可放寬):邏輯巢狀深度32、$and/$or長度1000、$in/$nin長度10000、節點總數100000(條件物件、運算子物件、純量各計1)、欄名128

    錯誤一律為同步拋出之Error('invalid find: 原因 at [路徑]'),不回顯值(鍵名為路徑之一部分,限30字元並以?取代控制字元、格式字元與方括號);走訪中任何例外(含呼叫端之getter、Proxy陷阱、Symbol.toStringTag getter)一律轉為此格式,不轉述呼叫端之錯誤訊息,描述子陷阱拋錯、存取器與不可列舉屬性之路徑含該屬性鍵或元素索引;可重入。opt須為物件、null或未給,僅可含下列五個鍵(自有資料屬性),設定錯誤另拋Error('invalid opt: 原因')。

    已知限制:判定內部標籤須讀Symbol.toStringTag,可能執行呼叫端之Proxy陷阱或getter(例外一律轉為invalid find);Proxy無法穿透,非空位置之Proxy包住原型被改之品牌物件視同其經陷阱暴露之條件物件;無法觀察品牌者(含私有欄位之類別實例與AbortController等宿主物件改原型為null、自有鍵為純量constructor之Promise)不被辨出;品牌檢查先以一次結構化複製(structuredClone)證明被記錄之條件物件皆非品牌物件,環境無可用之該全域、字串總長逾400萬碼元或樹內含Proxy時改逐物件探針(每物件約50微秒,含Proxy之近節點上限輸入可達數秒),且無可用之該全域時無法辨出空Proxy;被判為品牌物件而reject者,其內部資料(Map/Set之項目、ArrayBuffer之位元組)可能被複製讀取一次,成本不受節點預算約束;Proxy之ownKeys結果於引擎內先被完整具現化,其成本不受節點預算約束;共享參照(同一物件出現於多處)每出現一次即各讀各檢各複製,節點數亦逐次計入

    後端專屬之檢核(欄位型別、欄是否存在、主鍵正規化、DATE範圍、NULL三值語意)不在此,由各後端於本函數之後自行處理;契約案例表見wsemi/src/_cvOrmFindCases.mjs。

    Unit Test: Github

Source:
Example
console.log(Object.keys(cvOrmFind()))
// => []

console.log(Object.keys(cvOrmFind({})))
// => []

let r = cvOrmFind({ name: 'a', age: { $gt: 20, $in: [21, 22] }, $or: [{ g: 'A' }, { g: null }] })
console.log(Object.getPrototypeOf(r), Object.keys(r))
// => null [ 'name', 'age', '$or' ]

try {
    cvOrmFind({ name: { $regex: 'a' } })
}
catch (err) {
    console.log(err.message)
}
// => invalid find: unsupported operator [$regex] at [find.name.$regex]

try {
    cvOrmFind(null)
}
catch (err) {
    console.log(err.message)
}
// => invalid find: condition must be a plain object, got [null] at [find]
Parameters:
Name Type Attributes Default Description
find *

輸入條件,可為任意值,undefined或{}代表全部

opt Object <optional>
{}

輸入設定物件,預設{}

Properties
Name Type Attributes Default Description
maxDepth Integer <optional>
32

輸入邏輯巢狀深度上限整數,只可下調,預設32

maxList Integer <optional>
1000

輸入$and/$or長度上限整數,只可下調,預設1000

maxIn Integer <optional>
10000

輸入$in/$nin長度上限整數,只可下調,預設10000

maxNodes Integer <optional>
100000

輸入節點總數上限整數,只可下調,預設100000

maxKey Integer <optional>
128

輸入欄名長度上限整數,只可下調,預設128

Throws:

不合白名單者拋出Error('invalid find: 原因 at [路徑]'),opt錯誤者拋出Error('invalid opt: 原因')

Type
Error
Returns:

回傳全新之null原型條件物件,無自有鍵代表全部

Type
Object

(static) day2cht(t, bNoDisplayYearopt) → {String}

Description:
  • 日時間轉中文格式時間字串

    Unit Test: Github

Source:
Example
console.log(day2cht('2019-01-02'))
// => '民國 108 年 1 月 2 日'
Parameters:
Name Type Attributes Default Description
t String

輸入日時間字串

bNoDisplayYear boolean <optional>
false

輸入是否輸出民國年,預設為false

Returns:

回傳中文格式時間字串

Type
String

(static) debounce(msopt, optopt) → {function}

Description:
  • 函數去除抖動

    呼叫無回傳值,任務不被等待;任務同步拋錯或其Promise被reject時記錄而不外拋(不產生未處理之rejection),不影響後續佇列;輸入非函數時不排入佇列(不影響已排入之任務),記錄'invalid func: must be a function'

    記錄經getDiag(opt)之出口(診斷輸出與遮罩之單一實作,規則R-DIAG-01):任務拋出之值常含權杖、使用者識別或資料值,不得原樣輸出。預設以console.error只輸出固定詞彙之label'[wsemi debounce] task threw'與安全摘要{ errType, errCode };opt.logDetail為true時改輸出遮罩後之拋出值;opt.funLog為函數時輸出只交給它,不寫console。輸入非函數時以console.log輸出固定詞彙'[wsemi debounce] invalid func: must be a function'(同樣可由opt.funLog接管)

    回傳之函數另帶cancel():立即停止偵測(清除偵測計時器)並丟棄尚未執行之任務,回傳undefined;已開始執行之任務(含其尚未完成之Promise)不受影響、不被中止;未有待執行之任務時呼叫亦無妨(只通知事件);cancel之後再呼叫去除抖動函數,則如同初次呼叫重新排入並開始偵測

    Unit Test: Github

Source:
Example
async function topAsync() {

    function test1() {
        return new Promise((resolve, reject) => {
            let ms = []

            let dbc = debounce(300)

            let i = 0
            function core(name) {
                i++
                ms.push({ name, i })
                console.log({ name, i })
            }

            setTimeout(function() {
                dbc(() => {
                    core('A')
                })
            }, 100)
            setTimeout(function() {
                dbc(() => {
                    core('B')
                })
            }, 200)
            setTimeout(function() {
                dbc(() => {
                    core('C')
                })
            }, 250)
            setTimeout(function() {
                dbc(() => {
                    core('D')
                })
            }, 350)
            setTimeout(function() {
                dbc(() => {
                    core('E')
                })
            }, 400)
            setTimeout(function() {
                resolve(ms)
            }, 800)
        })
    }
    console.log('test1')
    let r1 = await test1()
    console.log(JSON.stringify(r1))
    // test1
    // { name: 'E', i: 1 }
    // [{"name":"E","i":1}]

    function test2() {
        return new Promise((resolve, reject) => {
            let ms = []

            let dbc = debounce(300)

            let i = 0
            function core(name) {
                i++
                ms.push({ name, i })
                console.log({ name, i })
            }

            setTimeout(function() {
                dbc(() => {
                    core('A')
                })
            }, 50)
            setTimeout(function() {
                dbc(() => {
                    core('B')
                })
            }, 100)
            setTimeout(function() {
                dbc(() => {
                    core('C')
                })
            }, 150)
            setTimeout(function() {
                dbc(() => {
                    core('D')
                })
            }, 500)
            setTimeout(function() {
                dbc(() => {
                    core('E')
                })
            }, 550)
            setTimeout(function() {
                resolve(ms)
            }, 1400)
        })
    }
    console.log('test2')
    let r2 = await test2()
    console.log(JSON.stringify(r2))
    // test2
    // { name: 'C', i: 1 }
    // { name: 'E', i: 2 }
    // [{"name":"C","i":1},{"name":"E","i":2}]

}
topAsync().catch(() => {})
Parameters:
Name Type Attributes Default Description
ms Integer <optional>
300

輸入未有調用的時間區間,為正整數(1至9007199254740991,數字字串亦可),預設300ms;非預期(0、負數、小數、Infinity、超過安全整數、'0x10'等)視為未給而改用預設300ms,不報錯(Infinity不代表永不觸發);ms只與時間差比較、不交給原生計時器,故不設2147483647之計時器上限

opt Object <optional>
{}

輸入設定物件,預設{}

Properties
Name Type Attributes Default Description
debug Boolean <optional>
false

輸入是否於ms為非預期之輸入時輸出警告布林值,須為true才生效,警告為固定詞彙(不含輸入值),同一行程只警告一次,預設false;警告出口為opt.funLog,以(msg, { fn, reason, key })呼叫,其形狀同診斷輸出之(label, safe, detail)(msg為固定詞彙之label,{ fn, reason, key }為安全摘要,無detail)

onTrace function <optional>
null

輸入觀察回調函數,於內部事件發生當下同步呼叫,傳入一個凍結之事件物件{ type, ... },供測試以事件(而非等待時間)同步與診斷;type為'push'時為任務排入佇列(含size為排入後之佇列長度),'start'時為開始偵測(每10ms檢查一次是否已超過ms未有調用),'run'時為已超過ms未有調用而即將執行最後之任務(含dropped為被捨棄之較早任務數),'stop'時為佇列已空而停止偵測,'cancel'時為呼叫cancel()(含dropped為被丟棄之待執行任務數、stopped為是否停止了進行中之偵測布林值;cancel不另通知'stop');回調不帶接收者呼叫,其拋錯與回傳值皆忽略,不影響去除抖動,預設null

logDetail Boolean <optional>
false

輸入是否於console輸出遮罩後之任務拋出值,須為true才生效,同getDiag,建構時取快照,預設false(只輸出安全摘要)

funLog function <optional>
null

輸入診斷輸出函數,格式為(label, safe, detail)=>{},給予時記錄只交給它而不寫console,同getDiag,建構時取快照,預設null

Returns:

回傳去除抖動函數,格式為(func, ...input)=>undefined,func為欲去除抖動之任務函數,input為呼叫func時之引數;另帶cancel方法

Type
function

(static) delay(msopt, optopt) → {Promise}

Description:
  • Promise延遲毫秒

    Unit Test: Github

Source:
Example
need test in browser

delay(1000)
// => 延遲1s才執行
Parameters:
Name Type Attributes Default Description
ms Number <optional>
10

輸入延遲毫秒數,須為有效數字且在0至2147483647(計時器上限)之內,可帶小數,數字字串(去頭尾空白後為十進位寫法)亦可,預設10ms;非預期(NaN、負數、Infinity、超過2147483647、'0x10'、包裝物件、非數字等)視為未給而改用預設10ms,不報錯、不夾至上限

opt Object <optional>
null

輸入設定物件,預設null

Properties
Name Type Attributes Default Description
onTrace function <optional>
null

輸入觀察回調函數,於內部事件發生當下同步呼叫,傳入一個凍結之事件物件{ type, ... },供測試以事件(而非等待時間)同步與診斷;type為'start'時為開始延遲(含ms為實際使用之延遲毫秒數,已套用預設值),'done'時為延遲完畢而即將resolve(含ms同上);回調不帶接收者呼叫,其拋錯與回傳值皆忽略,不影響延遲,預設null

debug Boolean <optional>
false

輸入是否於ms為非預期之輸入時輸出警告布林值,須為true才生效,警告為固定詞彙(不含輸入值),同一行程只警告一次,預設false

funLog function <optional>
null

輸入警告輸出函數,格式為(msg, { fn, reason, key })=>{},未給則用console.warn,預設null

Returns:

回傳Promise,resolve代表延遲完畢

Type
Promise

(static) detectXSS(str) → {Array}

Description:
  • 偵測字串內之xss攻擊語法,回傳clearXSS會轉義或刪除之可疑項目,供提示用,不改寫資料

    Depend on: https://jsxss.com/zh/index.html

    與clearXSS共用同一份js-xss設定(白名單、網址判定、白名單外之style屬性保留),判定規則:

    1. 標籤(type為'tag'):白名單外之標籤,名稱由原始標籤片段取得且其後須接空白、斜線、大於或結尾,故含'<svg/onload=...>',不含'孔深 < 500 m'、'5<6>4'、'<o:p>';結尾未閉合且無屬性之白名單標籤(如'若 a<b'之'<b')亦不計

    2. 屬性(type為'attr'):白名單內標籤被刪除之事件屬性,名稱為on接英文字母且有值,故不含'ac'之once

    3. 網址(type為'url'):白名單內標籤之href或src被擋下,且依HTML5規則解碼字元參照、刪除tab與換行、刪除開頭控制字元與空白後,協定為javascript、vbscript或data,相對網址被擋不計

    4. 註解:js-xss先刪註解再解析,與瀏覽器之註解規則不同(如'--!>'亦結束註解),有註解時另保留註解再解析一次取聯集,註解本身不計

    5. 重複項目合併為1筆,依出現順序排列

    限制:style屬性比照clearXSS保留不檢查;非HTML之純文字(如'javascript:alert(1)')不偵測,網址欄位須另檢查協定

    Unit Test: Github

Source:
Example
console.log(detectXSS('<img src=x onerror=alert(1)><script>alert(1)</script>'))
// => [ { type: 'attr', tag: 'img', name: 'onerror' }, { type: 'tag', tag: 'script' } ]

console.log(detectXSS('<svg/onload=alert(1)>'))
// => [ { type: 'tag', tag: 'svg' } ]

console.log(detectXSS('<a href="jav&#x09;ascript:alert(1)">點我</a>'))
// => [ { type: 'url', tag: 'a', name: 'href', scheme: 'javascript' } ]

console.log(detectXSS('<!-- --!><script>alert(1)</script>-->'))
// => [ { type: 'tag', tag: 'script' } ]

console.log(detectXSS('&lt;b&gt; 為粗體標籤'))
// => []

console.log(detectXSS('孔深 < 500 m 且 > 10 m'))
// => []

console.log(detectXSS('若 a<b'))
// => []

console.log(detectXSS('a<b and once>c'))
// => []

console.log(detectXSS('<div style="text-align:center;">圖1 名稱</div>'))
// => []

console.log(detectXSS('<img src="pics/a.png" alt="圖">'))
// => []
Parameters:
Name Type Description
str String

輸入字串

Returns:

回傳偵測項目陣列,無則回傳空陣列,非字串或空字串回傳空陣列,項目為{ type: 'tag', tag }、{ type: 'attr', tag, name }或{ type: 'url', tag, name, scheme }

Type
Array

(static) dig(v, idigopt) → {String}

Description:
  • 數字取指定小數位的字串 為字串故可自動補0 console.log(1.005.toFixed(2)) //1.00 console.log(dig(1.005, 2)) //1.01 v須為有效數字(isenum: 有限數字,或去頭尾空白後為十進位寫法之數字字串),其餘(Infinity、'Infinity'、'0x10'、'1e400'、'-'、''、null、包裝物件等)回傳空字串

    Unit Test: Github

Source:
Example
console.log(dig(0.123456789, 3))
// => '0.123'

console.log(dig(0.123456789, 4))
// => '0.1235'

console.log(dig(' 1.005 ', 2))
// => '1.01'

console.log(dig(Infinity, 2))
// => '' (舊版為'NaN')

console.log(dig('0x10', 2))
// => '' (舊版為'16.00')

console.log(dig(1.25, Infinity))
// => '1' (idig非預期改用預設0; 舊版拋RangeError)
Parameters:
Name Type Attributes Default Description
v Number | String

輸入數值,需為有效數字(數字或數字字串,定義見isenum,不收Infinity與'0x10'等),非有效數字時回傳空字串

idig Integer <optional>
0

輸入指定小數位整數,須為有效整數且介於0至100(iseint之use:'digits',toFixed之範圍,可為字串型數字),非預期之輸入(含Infinity、負數、小數、超過100、'0x10'、包裝物件)視為未給而改用預設0(舊版回傳空字串或拋RangeError),預設為0

Returns:

回傳取指定小數位的字串,v非有效數字時回傳空字串

Type
String

(static) digExp(v, idigopt) → {String}

Description:
  • 數字取指定小數位,小於1e-6改指數顯示 v須為有效數字(isenum: 有限數字,或去頭尾空白後為十進位寫法之數字字串),其餘(Infinity、'Infinity'、'0x10'、'1e400'、'-'、''、null、包裝物件等)回傳空字串

    Unit Test: Github

Source:
Example
console.log(digExp(0.000000123456789, 2))
// => '1.23e-7'

console.log(digExp(Infinity, 2))
// => '' (舊版為'NaN')
Parameters:
Name Type Attributes Default Description
v Number | String

輸入數值,需為有效數字(數字或數字字串,定義見isenum,不收Infinity與'0x10'等),非有效數字時回傳空字串

idig Integer | String <optional>
0

輸入指定小數位,opt類參數(有效整數,小數位數0~100,數字字串亦可,去頭尾空白後取值),非預期之輸入(非有效整數、小數、負數、超過100、Infinity、'0x10'、包裝物件等)視為未給而改用預設,不報錯,預設為0

Returns:

回傳取指定小數位的字串,v非有效數字時回傳空字串

Type
String

(static) domAlert(msg, optopt) → {Promise}

Description:
  • 前端彈出訊息視窗

    輸入之處置(使用者2026-11-12定):

    1. msg須為非空之原始字串(包裝物件new String、不可讀之Proxy等皆無效,規格§3.4 S1),否則不顯示、回傳已完成(resolved)之Promise(不拋錯亦不reject,呼叫端以fire-and-forget方式呼叫時不會產生未處理之rejection);
    2. opt非物件(含null、陣列、不可讀之Proxy)視為{}(以typeof與Array.isArray判定,帶自訂Symbol.toStringTag之一般物件仍為設定物件);paddingStyle、closeIconShift同;opt之各鍵讀取拋錯(拋錯之getter、已撤銷之Proxy)視為未給(規格§4 V11);
    3. 數值類opt(time、paddingStyle各鍵、borderWidth、borderRadius、closeIconShift各鍵)逐一以isenum檢查(有限數字或數字字串),非預期之輸入(含NaN、Infinity、'0x10'、包裝物件、非數字,及time、paddingStyle、borderWidth、borderRadius之負數)視為未給而改用該欄預設,不報錯;
    4. paddingStyle部分給鍵時,未給或無效之鍵保留該鍵預設(top:14、right:26、bottom:14、left:14);closeIconShift部分給鍵時,未給之鍵保留預設(top:10、right:10),但同軸已給有效值者不再套用另一端之預設(給bottom而未給top時不設top,給left而未給right時不設right),以免上下或左右同時定位;
    5. 關閉: 顯示時間到、或按關閉按鈕(✕)時,皆先resolve回傳之Promise再移除彈窗;關閉按鈕與滑鼠移入移出之淡入淡出以addEventListener綁定,不使用行內事件屬性與全域函數(嚴格CSP下亦可用); 5b. 字串型樣式opt(textColor、backgroundColor、borderColor、shadowStyle,使用者2026-11-16 W-14縮限D6):只認原始字串,null、非字串、包裝物件、讀取拋錯視為未給而改用該欄預設(K3),空字串''為合法值(表示不要該樣式);opt.type只認內建圖標之自有鍵,不經原型鏈判定;
    6. 外框、內寬層與關閉按鈕以createElement建立,msg與圖標以innerHTML插入內寬層內之內容容器,其HTML之解析限於該容器: msg含未閉合之標籤(如'