Skip to content

Instantly share code, notes, and snippets.

@SergProduction
Last active February 22, 2018 11:38
Show Gist options
  • Save SergProduction/3b29d8f4232ece8d55f3035933303bbe to your computer and use it in GitHub Desktop.
Save SergProduction/3b29d8f4232ece8d55f3035933303bbe to your computer and use it in GitHub Desktop.
// ------lib------
const getType = (o) => {
return Object.prototype.toString.call(o).slice(8,-1).toLocaleLowerCase()
}
const types = () => {
const func = (val) => getType(val) === 'function'
const number = (val) => getType(val) === 'number'
const string = (val) => getType(val) === 'string'
const bool = (val) => getType(val) === 'boolean'
const arrayOf = (type) => (val) => getType(val) === 'array' && type(val[0])
const objectOf = (obj) => (val) => Object.entries(obj).every(([key, value]) => value(val[key]))
const oneOfType = (types) => (val) => types.some(type => type(val))
const oneOf = (values) => (val) => values.some(type => type === val)
const sumOf = (values) => (param) => values.every((type, i) => type === param[i])
return {
func,
number,
string,
bool,
arrayOf,
objectOf,
oneOfType,
}
}
const createType = (type) => {
if (type) {
return (val) => type(val) ? val : null
}
const newType = (otherType) => otherType === newType || newType
return newType
}
/*
// ------feature------
const createFunc = (...types) => (fn) => (...param) => {
const isValid = types.every((type, i) => type(param[i]))
if (isValid === false) {
console.error('type is not valid')
return
}
fn(...param)
}
const createFuncR = (...types) => (...param) => (fn) => createFuncType(...types)(fn)(...param)
*/
// ------used------
// primitive types
const t = types()
const Person = createType(t.objectOf({
id: t.number,
name: t.string,
}))
const Personal = createType(t.arrayOf(Person))
const person1 = {id: 2, name: 'Alex'}
const person2 = {id: 1, name: 'Joh'}
const personal = [person1, person2]
Person(person1)
Personal(personal)
// new types
const True = createType()
const False = createType()
const Bool = t.oneOfType([True, False])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment