- Notifications
You must be signed in to change notification settings - Fork10
Immutable and structurally typed data
License
typed-immutable/typed-immutable
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
=========
Library provides is built uponimmutable.js to leverage it’s immutablepersistent data and provide structural typing on top of that. Library is not aiming to provide type safety of typed language (some static type checker likeflow would be tool for that) although it allows user to define structured types and guarantees that values produced and later transformed will conform to pre-defined structure. Handy use case for such tool would be an application state modelling (inMVC sense), specially if state is centralised but compartmentalized for us by independent components.
In the following sections we would use term "type" for a javascript class that can be instantiated via function call (although use ofnew
still possible) and produces immutable persistent data structure that we’ll refer to as "value" as they will have more common with primitive values like strings or numbers than with objects.
Records are a labeled data structure. They provide a lightweight representation for complex data. Record types can be defined by invokingRecord
function with a type structure descriptor, that is an object that provides field names and types associated with them:
var{Record}=require("typed-immutable")varPoint=Record({x:Number,y:Number})
Record types maybe invoked as functions or instantiated as a class to produce a value in form of immutable object with a pre-defined structure:
Point({x:0,y:0})// => {x:0, y:0}newPoint({x:0,y:0})// => {x:0, y:0}
Record types enforce pre-defined structure and will fail if input provided does not match it:
Point()// => TypeError: Invalid value for "x" field:// "undefined" is not a numberPoint({x:"1",y:"2"})// => TypeError: Invalid value for "x" field:// "1" is not a number
Record types definitions may also be provided a default values for feilds for a convenience of use:
varPoint=Record({x:Number(0),y:Number(0)})Point()// => { "x": 0, "y": 0 }Point({x:20})// => { "x": 20, "y": 0 }Point({x:null})// => TypeError: Invalid value for "x" field:// "null" is not a number
Record fields can be accessed by name via property access syntax:
varp1=Point({x:17})p1.x// => 17p1.y// => 0
Attempts to update a field will fail with error:
p1.x=30// => TypeError: Cannot set on an immutable record.
Instead of changing a record values you can transform them or create new values from existing one similar to how you do that with strings or numbers:
p1=Point()// => {x:0, y:0}p1.set("x",7)// => {x: 7, y:0}p1// => {x:0, y:0}
Removeing a field from a record simply resets it's value to the default if one was defined.
varp1=Point({x:1,y:25})// => {x:1, y:25}p1.remove("y")// => {x:1, y:0}
Record types proudce values with only fields that they were defined with everything elsethey simply ignore:
Point({x:30,y:40,z:8})// => {x:30, y:40}
Although the do explicitly forbid setting undeclared fields with error:
Point().set("z",5)// => TypeError: Cannot set unknown field "z" on "Typed.Record({x: Number(0), y: Number(0)})"
Record values are actually instances of the record type / class but given immutablity they have much more common with values which is why we refer to them as such:
varp1=Point()p1instanceofPoint// truep1.x// => 0p1.y// => 0varp2=p1.merge({x:23})p2instanceofPoint// truep2.x// => 23p2.y// => 0p1.equals(Point())// => truep1.equals(p2)// => falsep2.equals(Point({x:23}))// => true
Record values serialize to strings that containing their value and a type signature
Point({x:23}).toString()// => ‘Typed.Record({x: Number(0), y: Number(0)})({ "x": 23, "y": 0 })’
But for records with large number of fields it maybe more handy to provide a name, thatcan be done during definition:
varPoint=Record({x:Number(0),y:Number(0)},"Point")Point({x:4,y:7}).toString()// => ‘Point({ "x": 4, "y": 7 })’
For any complex data defining records contaning records is crucial, which works exactly as expected:
varLine=Record({begin:Point,end:Point},"Line")varline=Line({end:{x:70}})lineinstanceofLine// => trueline.toString()// => Line({ "begin": Point({ "x": 0, "y": 0 }), "end": Point({ "x": 70, "y": 0 }) })line.begin// => {x: 0, y:0}line.begininstanceofPoint// => trueline.end// => {x: 70, y:0}line.endinstanceofPoint// => true
As with primitive fields you could provide defaults to a complex records as well:
varLine=Record({begin:Point({x:23}),end:Point({y:4})},"Line")Line().toString()//=> Line({ "begin": Point({ "x": 23, "y": 0 }), "end": Point({ "x": 0, "y": 4 }) })
Records can be serialized to JSON and then instantiated back to an equal record value:
Line(line.toJSON()).equals(line)// => true
You can define typed lists by providing aList
function a type that it’sitems are supposed to be of:
var{List}=require("typed-immutable")varNumbers=List(Number)Numbers().toString()// ‘Typed.List(Number)([])’Numbers.of(1,2,3).toString()// => ‘Typed.List(Number)([ 1, 2, 3 ])’
Typed lists may contain only items of that type and fail with error if attempted to do otherwise:
Numbers([2,3]).toString()// => Typed.List(Number)([ 2, 3 ])Numbers([1,2,3,"4","5"])// => TypeError: Invalid value: "4" is not a numberNumbers([1,2,3]).push(null)// => TypeError: Invalid value: "null" is not a number
Typed lists can also be named for convenience:
varStrings=List(String,"Strings")Strings.of("hello","world").toString()// => Strings([ "hello", "world" ])
List can be of a complex a specific record type & records can also have fields of typed list:
varPoints=List(Point,"Points")Points().toString()// => Points([])ps=Points.of({x:3},{y:5}).toString()ps.toString()// => Points([ Point({ "x": 3, "y": 0 }), Point({ "x": 0, "y": 5 }) ])'ps.get(0)instanceofPoint// => trueps.get(1)instanceofPoint// => trueps.get(0).x// => 3ps.get(1).y// => 5ps.push({z:4,x:-4}).toJSON()// => [ { x: 3, y: 0 }, { x: 0, y: 5 }, { x: -4, y: 0 } ]Points(ps.toJSON()).equals(ps)// => true
One somewhat tricky thing about lists is that while they enforce certain type they can also be as easily converted to list of other type by simply mapping it:
ps=Points.of({x:1},{x:2})xs=ps.map(p=>p.x)ps.toString()// => Points([ Point({ "x": 1, "y": 0 }), Point({ "x": 2, "y": 0 }) ])xs.toString()// => Typed.List(Number)([ 1, 2 ])
As you can see from example above originalps
list was ofPoint
records while mappedxs
list is of numbers and that is refleced in the type of the list. Although given that JS is untyped language theer is no guarantee that mapping function will return values of the same type which makes things little more complex, result of such mapping will be list of union type of all types that mapping funciton produced (see types section for union types).
You can define a typed map by providingMap
the type for the key and the type for the value:
var{Map, Record}=require("typed-immutable")varProduct=Record({name:String},"Product")varProducts=Map(Number,Product)Products().toString()// ‘Typed.Map(Number, Product)({})’Products([[1,{name:"Mapper 1000"}]]).toString()//Typed.Map(Number, Product)({ 1: Product({ "name": "Mapper 1000" }) })
Typed maps may contain only entries with key and value that match the specified type:
Products([[1,"Mapper 1000"]])// => TypeError: Invalid value: Invalid data structure "Mapper 1000" was passed to ProductProducts().set("P1",{name:"Mapper 1000"})// TypeError: Invalid key: "P1" is not a number// All keys in an object are strings, so this fails too:Products({1:{name:"Mapper 1000"}})// TypeError: Invalid key: "1" is not a number
Note the last example - all keys in an object are strings so if you instantiate a map from an object the type of your key must be a string (or something that handles strings).
As with other types Typed maps can also be named for convenience:
varProducts=Map(Number,Product,"Products")Products([[1,{name:"Mapper 1000"}]]).toString()// Products({ 1: Product({ "name": "Mapper 1000" }) })
As it was illustrated in above sections we strucutre our types using other types there for this libary supports most JS types out of the box and provides few extra to cover more complex cases.
You can useBoolean
Number
String
RegExp
JS built-in constructs structures of those types.
You can define an optional type usingMaybe
that will produce a type whos value can beundefined
null
or a value of the provided type:
var{Maybe}=require("typed-immutable")varColor=Record({red:Number(0),green:Number(0),blue:Number(0),opacity:Maybe(Number)})Color().toJSON()// => { red: 0, green: 0, blue: 0, opacity: null }Color({red:200,opacity:80}).toJSON()// => { red: 200, green: 0, blue: 0, alpha: 80 }Color({red:200,opacity:"transparent"})// => TypeError: Invalid value for "opacity" field:// "transparent" is not nully nor it is of Number type
A union type is a way to put together many different types. This lets you create list or records fields that can take either one of the several types:
var{Union}=require("typed-immutable")varForm=Record({user:Union(Username,Email),password:String('')})varform=Form()form.set('user',Username('gozala'))form.set('user',Email('gozala@mail.com'))
Library lets you declare your own custom types that then you can use in defining more complex types with records and lists:
var{Typed}=require("typed-immutable")varRange=(from,to=+Infinity)=>Typed(`Typed.Number.Range(${from}..${to})`,value=>{if(typeof(value)!=='number'){returnTypeError(`"${value}" is not a number`)}if(!(value>=from&&value<=to)){returnTypeError(`"${value}" isn't in the range of${from}..${to}`)}returnvalue})varColor=Record({red:Range(0,255),green:Range(0,255),blue:Range(0,255)})Color({red:20,green:20,blue:20}).toJSON()// => { red: 20, green: 20, blue: 20 }Color({red:20,green:20,blue:300})// => TypeError: Invalid value for "blue" field:// "300" isn't in the range of 0..255Color()// => TypeError: Invalid value for "red" field:// "undefined" is not a numbervarColor=Record({red:Range(0,255)(0),green:Range(0,255)(0),blue:Range(0,255)(0)})Color().toJSON()// => { red: 0, green: 0, blue: 0 }
As a matter of factTyped
contains bunch of other types includingTyped.Number.Range
similar to one from the example above.
While this defeats the whole purpose there are still cases where use ofAny
type may be a good short term solution. In addition as described in the section about list mapping lists could be mapped to arbitrary types and there are cases where result of mapping isList(Any)
:
var{Any}=require("typed-immutable")varBox=Record({value:Any})varv1=Box({value:5})varv2=v1.set("value","hello")varv3=v2.set("value",v2)v1.toString()// => Typed.Record({value: Any})({ "value": 5 })v2.toString()// => Typed.Record({value: Any})({ "value": "hello" })v3.toString()// => Typed.Record({value: Any})({ "value": Typed.Record({value: Any})({ "value": "hello" }) })
- Run
npm start
beforenpm test
as the tests are ran on built code
About
Immutable and structurally typed data
Topics
Resources
License
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Packages0
Uh oh!
There was an error while loading.Please reload this page.
Contributors8
Uh oh!
There was an error while loading.Please reload this page.