1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
use crate::js::function::NativeFunctionData;
use crate::js::object::INSTANCE_PROTOTYPE;
use crate::js::value::{from_value, to_value, ResultValue, Value, ValueData};
use chrono::Local;
use gc::Gc;
use std::fmt::Write;
use std::iter::FromIterator;
pub fn log(_: Value, _: Value, args: Vec<Value>) -> ResultValue {
let args: Vec<String> = FromIterator::from_iter(args.iter().map(|x| {
return match *x.clone() {
ValueData::Object(ref v, _) => {
let mut s = String::new();
write!(s, "{}", "{").unwrap();
match v.borrow().iter().last() {
Some((last_key, _)) => {
for (key, val) in v.borrow().iter() {
if key == INSTANCE_PROTOTYPE {
continue;
}
write!(s, "{}: {}", key, val.value.clone()).unwrap();
if key != last_key {
write!(s, "{}", ", ").unwrap();
}
}
}
None => (),
}
write!(s, "{}", "}").unwrap();
s
}
_ => from_value::<String>(x.clone()).unwrap(),
};
}));
println!(
"{}: {}",
Local::now().format("%X").to_string(),
args.join(" ")
);
Ok(Gc::new(ValueData::Undefined))
}
pub fn error(_: Value, _: Value, args: Vec<Value>) -> ResultValue {
let args: Vec<String> = FromIterator::from_iter(
args.iter()
.map(|x| from_value::<String>(x.clone()).unwrap()),
);
println!(
"{}: {}",
Local::now().format("%X").to_string(),
args.join(" ")
);
Ok(Gc::new(ValueData::Undefined))
}
pub fn _create(global: &Value) -> Value {
let console = ValueData::new_obj(Some(global));
console.set_field_slice("log", to_value(log as NativeFunctionData));
console.set_field_slice("error", to_value(error as NativeFunctionData));
console.set_field_slice("exception", to_value(error as NativeFunctionData));
console
}
pub fn init(global: &Value) {
global.set_field_slice("console", _create(global));
}