@asfris/resatypejs
Version:
Javascript type checker
121 lines (102 loc) • 2.05 kB
JavaScript
/**
* Type Creator
*
* Created by resa dev team.
*/
/**
* @name U8
* @type
*/
const U8 = 0xFF;
/**
* @name U8
* @type
*/
const U16 = 0xFFFF;
/**
* @name U8
* @type
*/
const U32 = 0xFFFFFFFF;
/**
* @name T
* @description All Type checker functions,
* this object will filled with user types
*/
const T = {};
/**
* @name object
* @description Checks if input value type is object
* @param {object} value
*/
const object = (value) => {
if (typeof value !== 'object')
throw Error(`Type Error: Except object found ${typeof value}`);
return value;
}
/**
* @name string
* @description Checks if input value type is string
* @param {string} value
*/
const string = (value) => {
if (typeof value !== 'string')
throw Error(`Type Error: Except string found ${typeof value}`);
return value;
}
/**
* @name Interface
* @description Creates a new function witch checks type
* @param {string} name
* @param {object} obj
*/
const Interface = (name, obj) => {
object(obj);
T[name] = (arg) => {
if (Object.keys(obj).length !== Object.keys(arg).length)
throw Error(`Type error: Exepted ${name} type found ${typeof arg}`);
return arg;
};
return obj;
}
/**
* @name uChecker
* @description Unsigned types checker
* @param {number} len
*/
function uChecker(value, len) {
if (typeof value !== 'number')
throw Error(`Type Error: variable with value: ${value}, type is not number`);
if (value > len)
throw Error("Error: Value length more than required");
if (value < 0)
throw Error("Error: value cant less than Zero ( 0 ) Use signed types");
}
/**
* @function
* @name u8
* @description U8 type checker
*/
const u8 = (value) => {
uChecker(value, U8);
return value;
}
/**
* @function
* @name u16
* @description U16 type checker
*/
const u16 = (value) => {
uChecker(value, U16);
return value;
}
/**
* @function
* @name u32
* @description U32 type checker
*/
const u32 = (value) => {
uChecker(value, U32);
return value;
}
export { T, Interface, u8, u16, u32, object, string};