rusted
Rust's syntax features for javascript.
These features will help our functional programming.
Feature
Install
npm install --save rusted
Example
These examples require es6 transpiler like Babel.
enum
import {Enum} from 'rusted';
let Message=Enum({
Quit:null,
ChangeColor:Array,
Move:'object',
Write:'string'
});
let x=Message.Move({x:3,y:4});
let y=Message.Quit;
struct
struct
and enum
checks type of property when instantiate.
'any'
'number'
,'string'
,'object'
... (String)
- compared to
typeof value_of_prop
Object
,Array
,Number
... (Constructor)
- compared to
value_of_prop.constructor
import {struct} from 'rusted';
let Position=struct({
x:'number',
y:'number'
});
let Player=struct({
name:'string',
position:Position,
items:Array,
memory:'any'
});
let player=Player({
name:'foo',
position:Position({
x:0,y:0
}),
items:[],
memory:{}
});
console.log(player.position.x);
impl
import {Enum,struct,match,impl} from 'rusted';
let SomeStruct=struct({
x:'number',y:'number'
});
impl(SomeStruct,{
$new(x,y){
return SomeStruct({x,y});
},
print(self){
console.log(`(${x},${y})`);
}
});
let some_struct=SomeStruct.new(2,3);
some_struct.print();
let SomeEnum=Enum({
Foo:null,
Bar:'number'
});
impl(SomeEnum,{
unwrap(self){
return match(self,{
Foo:()=>'Foo!',
Bar:x=>`Bar,${x}!`
});
}
});
let x=SomeEnum.Foo,y=SomeEnum.Bar(7);
console.log(x.unwrap());
console.log(y.unwrap());
let SomeConstructor=function(){
this.name='foo';
};
impl(SomeConstructor,{
create(){
return new SomeConstructor();
},
greet(self){
console.log(`Hello, ${self.name} !`);
}
});
let some_constructor=SomeConstructor.create();
some_constructor.greet();
trait
import {struct,trait,impl} from 'rusted';
let Foo=struct({
name:'string'
});
let BarTrait=trait({
print(self){},
hello(self){
console.log('hello');
}
});
impl(BarTrait,Foo,{
print(self){
console.log(self.name);
}
});
let foo=Foo({name:'Taro'});
foo.print();
foo.hello();
Option
import {Some,None,match} from 'rusted';
let divide=(numerator,denominator)=>{
return denominator==0
? None
: Some(numerator/denominator);
};
let result = divide(2.0, 3.0);
match(result,{
Some:x=>console.log(`Result: ${x}`),
None:()=>console.log('Cannot divide by 0')
});
Result
import {Ok,Err,match} from 'rusted';
function Foo(x){
if(x>5){
return Ok(x);
}else{
return Err('Less than 5 !');
}
}
console.log(match(Foo(3),{
Ok:x=>x,
Err:e=>e
}));
console.log(Foo(10).unwrap());
console.log(Foo(3).unwrap());
(es5 version.)
var rusted=require('rusted'),
Ok=rusted.Ok,
Err=rusted.Err,
match=rusted.match;
function Foo(x){
if(x>5){
return Ok(x);
}else{
return Err('Less than 5 !');
}
}
console.log(match(Foo(3),{
Ok:function(x){
return x;
},
Err:function(e){
return e;
}
}));
console.log(Foo(10).unwrap());
console.log(Foo(3).unwrap());
License
MIT