diff --git a/cycle-detection-floyds-the-tortoise-and-the-the-hare/index.js b/cycle-detection-floyds-the-tortoise-and-the-the-hare/index.js new file mode 100644 index 0000000..a66d72b --- /dev/null +++ b/cycle-detection-floyds-the-tortoise-and-the-the-hare/index.js @@ -0,0 +1,15 @@ +// https://www.codewars.com/kata/cycle-detection-floyds-the-tortoise-and-the-the-hare/javascript + +const floyd = function(f, x0) { + let x = x0; + let i = 0; + const map = new WeakMap(); + + while (1) { + map[x] = i++; + x = f(x); + if (x in map) break; + } + + return [map[x], i - map[x]]; +}