javascript - 函数测试值范围内的值并返回值

标签 javascript clojure clojurescript

我是 clojure 脚本的新手,我正在尝试将以下函数覆盖到 clojurescript

function getLengthAtPoint(pt){
        var i = 0;
    while(i < p.getTotalLength())
    {
        var xy = p.getPointAtLength(i);
      // console.log(i, xy);
        if(Math.round(xy.y) == pt[1] && Math.round(xy.x) == pt[0])
      {
            return i;
      }

      i++;
    }

    return 0;
 }

我有以下逻辑

(defn get-length-at-point
  [p pt]
  (doseq [
     i (range (.getTotalLength p))
    :let [xy (.getPointAtLength p i)]
    :when (and (= (round js/Math (first xy)) (first pt)) (= (round js/Math (last xy)) (last pt)))]
    i)
  0)

但我想我可能错了,因为:什么时候不会返回i会吗?

更新

<小时/>

想出了这个

(defn get-length-at-point
  [pt {p :path}]
  (loop [i 0]
    (let [point (.getPointAtLength p i)]
    (cond
       (and (= (.round js/Math (.-x point)) (.round js/Math (:x pt)))
       (= (.round js/Math (.-y point)) (.round js/Math (:y pt)))) i
       (>= i (.getTotalLength p)) 0
        :else (recur (inc i))
       ))))

如果有人知道更简单的方法,请分享

最佳答案

尚不完全清楚您要在这里计算什么,但这是实现您所追求的目标的一些方法:

(defn get-length-at-point
  [pt p]
  (->> (map #(.getPointAtLength p %) (range (.getTotalLength p)))
       (filter (fn [point] (and (= (.round js/Math (.-x point)) (.round js/Math (:x pt)))
                                (= (.round js/Math (.-y point)) (.round js/Math (:y pt))))))
       (count)))

惯用的 Clojure 代码通常会避免使用 map 实现的循环doseq 运行只是为了产生副作用,并且不会向您返回值。大多数时候,Clojure 代码也不使用索引。如果您更新帖子并提供更多有关您想要执行的操作以及可以在 p 上调用哪些函数的上下文,我们也许能够提供更多帮助。

关于javascript - 函数测试值范围内的值并返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38677665/

相关文章:

javascript - 为什么我的 JavaScript DOM 遍历不起作用?

clojure - Scheme中引用的符号

java - Clojure 与 Var.intern 和 RT.var 的怪异

clojure - 如何调试 ClojureScript

javascript - 为什么可以使用 .length 检查 Javascript 中是否存在数组

javascript - Protractor> TypeError : item. 元素不是函数

clojure - 如何将关键字转换为字符串并保留冒号

javascript - 将 clojurescript 集成到 javascript 框架中

clojurescript - 重构中的嵌套组件未更新

javascript - 当没有空间容纳时如何在新行中断开长单词