Skip to content

Latest commit

 

History

History
55 lines (43 loc) · 1.73 KB

README.md

File metadata and controls

55 lines (43 loc) · 1.73 KB

What is this

This is a proof of concept of an idea that's loosely inspired by the univalence principle from homotopy type theory. The general idea is that we define mappers between types to create generic functions that can handle any type equivalent to the type that it's been initially written for. I.e. if we have three types that represent a customer

[firstName, surname, email] // CustomerArr

{name: firstName, surname: surname, email: email} // CustomerRecord

{firstName: firstName, lastName: surname, emailAddress: email} // PrettyCustomerRecord

We define a function that handles only one of these, but thanks to the system that's represented in this proof of concept, it can handle each of these types equally as well. i.e.:

const swapSurnameWithName = (customerArr: CustomerArr) => {
  const [ firstName, lastName, emailAddress ] = customerArr
  return [
    lastName,
    firstName,
    emailAddress
  ]
}

const swapSurnameWithNameU = graph.createUnivalentFunction(swapSurnameWithName,
[
  // Which type does the body of the function understand
  Symbol('CustomerArr')
])

This function will handle all the types despite the fact that it only operates on CustomerArr:

// Because we defined how types relate to each other
// our function can handle any of these types

swapSurnameWithNameU({
  firstName: 'John',
  lastName: 'Doe',
  emailAddress: '[email protected]'
})
// outputs { firstName: 'Doe', lastName: 'John', emailAddress: '[email protected]' }


swapSurnameWithNameU({
  name: 'John',
  surname: 'Doe',
  email: '[email protected]'
})
// outputs { name: 'Doe', surname: 'John', email: '[email protected]' }

How to run demo

The good, old npm i and npm start. It uses ts-node as a dependency to run this example.