Add docs and remove typecheck from variadic attribute

This commit is contained in:
Richard Dodd
2018-09-01 13:55:35 +01:00
parent ce1cb84327
commit 7d5d845608
7 changed files with 53 additions and 58 deletions

View File

@ -42,6 +42,7 @@
- [`module = "blah"`](./reference/attributes/on-js-imports/module.md)
- [`static_method_of = Blah`](./reference/attributes/on-js-imports/static_method_of.md)
- [`structural`](./reference/attributes/on-js-imports/structural.md)
- [variadic](./reference/attributes/on-js-imports/variadic.md)
- [On Rust Exports](./reference/attributes/on-rust-exports/index.md)
- [`constructor`](./reference/attributes/on-rust-exports/constructor.md)
- [`js_name = Blah`](./reference/attributes/on-rust-exports/js_name.md)

View File

@ -0,0 +1,38 @@
# Variadic Parameters
In javascript, both the types of function arguments, and the number of function arguments are
dynamic. For example
```js
function sum(...rest) {
let i;
// the old way
let old_way = 0;
for (i=0; i<arguments.length; i++) {
old_way += arguments[i];
}
// the new way
let new_way = 0;
for (i=0; i<rest.length; i++) {
new_way += rest[i];
}
// both give the same answer
assert(old_way === new_way);
return new_way;
}
```
This function doesn't translate directly into rust, since we don't currently support variadic
arguments on the wasm target. To bind to it, we use a slice as the last argument, and annotate the
function as variadic:
```rust
#[wasm_bindgen]
extern {
#[wasm_bindgen(variadic)]
fn sum(args: &[i32]) -> i32;
}
```
when we call this function, the last argument will be expanded as the javascript expects.

View File

@ -64,6 +64,10 @@ extern {
fn new() -> Awesome;
#[wasm_bindgen(method)]
fn get_internal(this: &Awesome) -> u32;
// We can call javascript functions that have a dynamic number of arguments,
// e.g. rust `sum(&[1, 2, 3])` will be called like `sum(1, 2, 3)`
#[wasm_bindgen(variadic)]
fn sum(vals: &[u32]) -> u32;
}
#[wasm_bindgen]
@ -143,5 +147,13 @@ export class Awesome {
}
}
export function sum(...args) {
let answer = 0;
for(var i=0; i<args.length; i++) {
answer += args[i];
}
return answer;
}
booted.then(main);
```