harn-stdlib 0.8.5

Embedded Harn standard library source catalog
Documentation
// std/json — JSON utility patterns
//
// Import with: import "std/json"
/**
 * Pretty-print a value as indented JSON (2-space indent).
 * pretty.
 */
pub fn pretty(value) {
  return json_stringify(value)
}

/**
 * Safely parse JSON, returning nil on failure instead of throwing.
 * safe_parse.
 */
pub fn safe_parse(text) {
  let result = try {
    json_parse(text)
  }
  if is_ok(result) {
    return unwrap(result)
  }
  return nil
}

/**
 * Shallow-merge two dicts. Keys in `b` override matching keys in `a`. Generic
 * over the value type so the resulting dict keeps the same value contract as
 * the inputs (`dict<string, V>` in, `dict<string, V>` out).
 */
pub fn merge<V>(a: dict<string, V>, b: dict<string, V>) -> dict<string, V> {
  var result = a
  for entry in b {
    result = result + {[entry.key]: entry.value}
  }
  return result
}

/**
 * Pick the listed keys from `data`, dropping entries whose stored value is
 * `nil`. Generic over the value type — when called with a `dict<string, V>`
 * the projection keeps the same V.
 */
pub fn pick<V>(data: dict<string, V>, keys: list<string>) -> dict<string, V> {
  var result = {}
  for k in keys {
    if data[k] != nil {
      result = result + {[k]: data[k]}
    }
  }
  return result
}

/**
 * Drop the listed keys from `data`. Generic over the value type — the
 * resulting dict keeps the same value contract as the input.
 */
pub fn omit<V>(data: dict<string, V>, keys: list<string>) -> dict<string, V> {
  let exclude = set(keys)
  var result = {}
  for entry in data {
    if !set_contains(exclude, entry.key) {
      result = result + {[entry.key]: entry.value}
    }
  }
  return result
}