Skip to content

Commit

Permalink
[function] implement multiple is*() functions
Browse files Browse the repository at this point in the history
  • Loading branch information
dmonad committed May 4, 2023
1 parent 4c259c5 commit 5c03634
Show file tree
Hide file tree
Showing 2 changed files with 72 additions and 0 deletions.
33 changes: 33 additions & 0 deletions function.js
Expand Up @@ -151,3 +151,36 @@ export const equalityDeep = (a, b) => {
// @ts-ignore
export const isOneOf = (value, options) => options.includes(value)
/* c8 ignore stop */

export const isArray = array.isArray

/**
* @param {any} s
* @return {s is String}
*/
export const isString = (s) => s && s.constructor === String

/**
* @param {any} n
* @return {n is Number}
*/
export const isNumber = n => n != null && n.constructor === Number

/**
* @template TYPE
* @param {any} n
* @param {TYPE} T
* @return {n is InstanceType<TYPE>}
*/
export const is = (n, T) => n && n.constructor === T

/**
* @template TYPE
* @param {TYPE} T
*/
export const isTemplate = (T) =>
/**
* @param {any} n
* @return {n is InstanceType<TYPE>}
**/
n => n && n.constructor === T
39 changes: 39 additions & 0 deletions function.test.js
Expand Up @@ -10,6 +10,45 @@ export const testBasics = _tc => {
t.assert(calls === 1)
t.assert(f.isOneOf(1, [3, 2, 1]))
t.assert(!f.isOneOf(0, [3, 2, 1]))
// test is*
const arr = [1, 'two', [1], { one: 1 }]
arr.forEach(val => {
if (f.isArray(val)) {
/**
* @type {Array<any>}
*/
const yy = val
t.assert(yy)
}
if (f.isString(val)) {
/**
* @type {string}
*/
const yy = val
t.assert(yy)
}
if (f.isNumber(val)) {
/**
* @type {number}
*/
const yy = val
t.assert(yy)
}
if (f.is(val, String)) {
/**
* @type {string}
*/
const yy = val
t.assert(yy)
}
if (f.isTemplate(Number)(val)) {
/**
* @type {number}
*/
const yy = val
t.assert(yy)
}
})
}

/**
Expand Down

0 comments on commit 5c03634

Please sign in to comment.