Skip to content

Implement array! and json! proc macros to make creation/instantiation easier #4515

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

dcechano
Copy link

This PR merges two proc macros that make js_sys::Array and js_sys::Object creation and instantiation easier.

Currently, to create an Object, you must use the Reflect API. Retrieving a property requires a Reflect::get call for every attempted retrieval. Likewise, to add a key-value pair to an Object, we must make a Reflect::set call for every property we would like to set. If we are adding an Object to another Object, that Object must be instantiated the same way before finally setting it in the target Object. This process is very cumbersome and quickly clutters the code.

The json! and array! proc macros address this problem. json! allows the creation of a js_sys::Object using JavaScript object literal syntax:

let john = json! {
    name: "John",
    age: 26
};

let has_name = Object::has_own_property(&john, &"name".into());
let has_age = Object::has_own_property(&john, &"age".into());
assert!(has_name);
assert!(has_age);

Similarly, the array! macro facilitates the creation of js_sys::Arrays using JavaScript array literal syntax:

let arr = array![1, 2, 3];
let expected = Array::of3(&1.into(), &2.into(), &3.into());
assert_eq!(arr.get(0).as_f64().unwrap(), expected.get(0).as_f64().unwrap());
assert_eq!(arr.get(1).as_f64().unwrap(), expected.get(1).as_f64().unwrap());
assert_eq!(arr.get(2).as_f64().unwrap(), expected.get(2).as_f64().unwrap());

Both macros support the use of variables in the JSON as long as the underlying type implements Into<JsValue>. Comments are also supported. I have been thinking about how useful a macro like this could be for quite some time, and I finally decided to implement it. Please check out the README.md for more information, as I've only covered the basics here. Let me know your thoughts!

@dcechano dcechano force-pushed the create-creation-macros branch from af03bcc to 42f22f5 Compare May 31, 2025 05:45
@dcechano dcechano force-pushed the create-creation-macros branch from 42f22f5 to 87a68bd Compare May 31, 2025 05:52
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant