jetcrab\runtime/
object.rs

1use crate::vm::value::Value;
2use std::collections::HashMap;
3
4pub struct Object {
5    properties: HashMap<String, Value>,
6    prototype: Option<Box<Object>>,
7}
8
9impl Default for Object {
10    fn default() -> Self {
11        Self::new()
12    }
13}
14
15impl Object {
16    pub fn new() -> Self {
17        Self {
18            properties: HashMap::new(),
19            prototype: None,
20        }
21    }
22
23    pub fn set_property(&mut self, name: String, value: Value) {
24        self.properties.insert(name, value);
25    }
26
27    pub fn get_property(&self, name: &str) -> Option<&Value> {
28        if let Some(value) = self.properties.get(name) {
29            Some(value)
30        } else if let Some(ref prototype) = self.prototype {
31            prototype.get_property(name)
32        } else {
33            None
34        }
35    }
36
37    pub fn has_property(&self, name: &str) -> bool {
38        self.properties.contains_key(name)
39            || self
40                .prototype
41                .as_ref()
42                .is_some_and(|p| p.has_property(name))
43    }
44
45    pub fn delete_property(&mut self, name: &str) -> bool {
46        self.properties.remove(name).is_some()
47    }
48
49    pub fn set_prototype(&mut self, prototype: Object) {
50        self.prototype = Some(Box::new(prototype));
51    }
52
53    pub fn get_prototype(&self) -> Option<&Object> {
54        self.prototype.as_ref().map(|p| p.as_ref())
55    }
56}