use geojson::Feature;
pub fn get_property_str(feature: &Feature, key: &str, default: &str) -> String {
feature
.properties
.as_ref()
.and_then(|props| props.get(key))
.and_then(|val| val.as_str())
.unwrap_or(default)
.to_string()
}
pub fn get_property_num(feature: &Feature, key: &str, default: f64) -> f64 {
feature
.properties
.as_ref()
.and_then(|props| props.get(key))
.and_then(|val| val.as_f64())
.unwrap_or(default)
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn test_get_property_str_found() {
let feature: Feature = serde_json::from_value(json!({
"type": "Feature",
"geometry": {"type": "Point", "coordinates": [0.0, 0.0]},
"properties": {
"name": "test",
"color": "red"
}
}))
.unwrap();
assert_eq!(get_property_str(&feature, "name", "default"), "test");
assert_eq!(get_property_str(&feature, "color", "default"), "red");
}
#[test]
fn test_get_property_str_missing() {
let feature: Feature = serde_json::from_value(json!({
"type": "Feature",
"geometry": {"type": "Point", "coordinates": [0.0, 0.0]},
"properties": {}
}))
.unwrap();
assert_eq!(get_property_str(&feature, "name", "default"), "default");
}
#[test]
fn test_get_property_num_found() {
let feature: Feature = serde_json::from_value(json!({
"type": "Feature",
"geometry": {"type": "Point", "coordinates": [0.0, 0.0]},
"properties": {
"size": 42,
"opacity": 0.5
}
}))
.unwrap();
assert_eq!(get_property_num(&feature, "size", 10.0), 42.0);
assert_eq!(get_property_num(&feature, "opacity", 1.0), 0.5);
}
#[test]
fn test_get_property_num_missing() {
let feature: Feature = serde_json::from_value(json!({
"type": "Feature",
"geometry": {"type": "Point", "coordinates": [0.0, 0.0]},
"properties": {}
}))
.unwrap();
assert_eq!(get_property_num(&feature, "size", 10.0), 10.0);
}
}