clojurescriptclojurescript-javascript-interop

Are there any way to treat Javascript methods like ClojureScript functions?


I like ClojureScript, but to interop between CLJS and Javascript is difficult. I would like to create a function that can perform date culculations in arbitrary units, such as the following. But this code results in errors. Is it not possible to treat JS methods like .foo like functions?

 (defn date-add [date num unit]
    (let [[getter setter]
          (case unit
            :sec [.getSeconds .setSeconds]
            :min [.getMinutes .setMinutes]
            :hour [.getHours .setHours]
            :day [.getDate .setDate]
            :month [.getMonth .setMonth]
            :year [.getFullYear .setFullYear])]
      ;; such as (.setDate date (+ num (.getDate date)))
      (setter date (+ num (getter date)))
      (js/Date. (.getTime date))))

Though I know great libraries like deja-fu or cljs-time, the avobe is the example. I would like to be able to perform simple operations on dates without using a library.


Solution

  • The answer below that uses memfn is the best at the time of this edit: https://stackoverflow.com/a/78348692/573110


    Here's another thought:

    user> (let [f js/Date.prototype.getSeconds]
            (.call f (js/Date.)))
    46