diff --git a/function.js b/function.js index 8bd8caf..3cac21e 100644 --- a/function.js +++ b/function.js @@ -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} + */ +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} + **/ + n => n && n.constructor === T diff --git a/function.test.js b/function.test.js index 21b9b0b..dccd975 100644 --- a/function.test.js +++ b/function.test.js @@ -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} + */ + 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) + } + }) } /**