我是 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/