0
Fork 0
mirror of https://github.com/penpot/penpot.git synced 2025-03-13 08:11:30 -05:00
penpot/frontend/src/app/util/object.cljs

97 lines
2 KiB
Text
Raw Normal View History

2020-04-24 15:26:05 +02:00
;; This Source Code Form is subject to the terms of the Mozilla Public
;; License, v. 2.0. If a copy of the MPL was not distributed with this
;; file, You can obtain one at http://mozilla.org/MPL/2.0/.
;;
2021-04-10 09:43:04 +02:00
;; Copyright (c) UXBOX Labs SL
2020-04-24 15:26:05 +02:00
(ns app.util.object
2020-04-24 15:26:05 +02:00
"A collection of helpers for work with javascript objects."
(:refer-clojure :exclude [set! new get get-in merge clone contains?])
(:require
["lodash/omit" :as omit]
[cuerdas.core :as str]))
2020-04-24 15:26:05 +02:00
(defn create [] #js {})
2020-10-09 12:29:35 +02:00
2020-04-24 15:26:05 +02:00
(defn get
([obj k]
2020-05-05 12:34:51 +02:00
(when-not (nil? obj)
2020-04-24 15:26:05 +02:00
(unchecked-get obj k)))
([obj k default]
(let [result (get obj k)]
(if (undefined? result) default result))))
2020-04-24 15:26:05 +02:00
2021-06-02 15:51:20 +02:00
(defn contains?
[obj k]
(some? (unchecked-get obj k)))
2021-04-21 17:20:38 +02:00
(defn get-keys
[obj]
(js/Object.keys ^js obj))
2020-04-24 15:26:05 +02:00
(defn get-in
2021-05-31 18:06:28 +02:00
([obj keys]
(get-in obj keys nil))
([obj keys default]
(loop [key (first keys)
keys (rest keys)
res obj]
(if (or (nil? key) (nil? res))
(or res default)
(recur (first keys)
(rest keys)
(unchecked-get res key))))))
2020-04-24 15:26:05 +02:00
#_:clj-kondo/ignore
(defn without
[obj keys]
(let [keys (cond
(vector? keys) (into-array keys)
(array? keys) keys
:else (throw (js/Error. "unexpected input")))]
(omit obj keys)))
(defn clone
[a]
(js/Object.assign #js {} a))
(defn merge!
2020-04-24 15:26:05 +02:00
([a b]
(js/Object.assign a b))
([a b & more]
(reduce merge! (merge! a b) more)))
2020-04-24 15:26:05 +02:00
(defn merge
([a b]
(js/Object.assign #js {} a b))
([a b & more]
(reduce merge! (merge a b) more)))
(defn set!
[obj key value]
(unchecked-set obj key value)
obj)
2021-05-31 18:06:28 +02:00
(defn update!
[obj key f & args]
(let [found (get obj key ::not-found)]
(if-not (identical? ::not-found found)
(do (unchecked-set obj key (apply f found args))
obj)
obj)))
(defn- props-key-fn
[key]
(if (or (= key :class) (= key :class-name))
"className"
(str/camel (name key))))
(defn clj->props
[props]
(clj->js props :keyword-fn props-key-fn))
2020-11-18 17:36:14 +01:00
(defn ^boolean in?
[obj prop]
(js* "~{} in ~{}" prop obj))