You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

utils.ts 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750
  1. import { Bounds } from 'types'
  2. import vec from 'utils/vec'
  3. /* ----------------- Start Copy Here ---------------- */
  4. export default class Utils {
  5. /**
  6. * Linear interpolation betwen two numbers.
  7. * @param y1
  8. * @param y2
  9. * @param mu
  10. */
  11. static lerp(y1: number, y2: number, mu: number): number {
  12. mu = Utils.clamp(mu, 0, 1)
  13. return y1 * (1 - mu) + y2 * mu
  14. }
  15. /**
  16. * Modulate a value between two ranges.
  17. * @param value
  18. * @param rangeA from [low, high]
  19. * @param rangeB to [low, high]
  20. * @param clamp
  21. */
  22. static modulate(
  23. value: number,
  24. rangeA: number[],
  25. rangeB: number[],
  26. clamp = false
  27. ): number {
  28. const [fromLow, fromHigh] = rangeA
  29. const [v0, v1] = rangeB
  30. const result = v0 + ((value - fromLow) / (fromHigh - fromLow)) * (v1 - v0)
  31. return clamp
  32. ? v0 < v1
  33. ? Math.max(Math.min(result, v1), v0)
  34. : Math.max(Math.min(result, v0), v1)
  35. : result
  36. }
  37. /**
  38. * Clamp a value into a range.
  39. * @param n
  40. * @param min
  41. */
  42. static clamp(n: number, min: number): number
  43. static clamp(n: number, min: number, max: number): number
  44. static clamp(n: number, min: number, max?: number): number {
  45. return Math.max(min, typeof max !== 'undefined' ? Math.min(n, max) : n)
  46. }
  47. // TODO: replace with a string compression algorithm
  48. static compress(s: string): string {
  49. return s
  50. }
  51. // TODO: replace with a string decompression algorithm
  52. static decompress(s: string): string {
  53. return s
  54. }
  55. /**
  56. * Recursively clone an object or array.
  57. * @param obj
  58. */
  59. static deepClone<T>(obj: T): T {
  60. if (obj === null) return null
  61. const clone: any = { ...obj }
  62. Object.keys(obj).forEach(
  63. (key) =>
  64. (clone[key] =
  65. typeof obj[key] === 'object' ? Utils.deepClone(obj[key]) : obj[key])
  66. )
  67. if (Array.isArray(obj)) {
  68. clone.length = obj.length
  69. return Array.from(clone) as any as T
  70. }
  71. return clone as T
  72. }
  73. /**
  74. * Seeded random number generator, using [xorshift](https://en.wikipedia.org/wiki/Xorshift).
  75. * The result will always be betweeen -1 and 1.
  76. *
  77. * Adapted from [seedrandom](https://github.com/davidbau/seedrandom).
  78. */
  79. static rng(seed = ''): () => number {
  80. let x = 0
  81. let y = 0
  82. let z = 0
  83. let w = 0
  84. function next() {
  85. const t = x ^ (x << 11)
  86. ;(x = y), (y = z), (z = w)
  87. w ^= ((w >>> 19) ^ t ^ (t >>> 8)) >>> 0
  88. return w / 0x100000000
  89. }
  90. for (let k = 0; k < seed.length + 64; k++) {
  91. ;(x ^= seed.charCodeAt(k) | 0), next()
  92. }
  93. return next
  94. }
  95. /**
  96. * Shuffle the contents of an array.
  97. * @param arr
  98. * @param offset
  99. */
  100. static shuffleArr<T>(arr: T[], offset: number): T[] {
  101. return arr.map((_, i) => arr[(i + offset) % arr.length])
  102. }
  103. /**
  104. * Deep compare two arrays.
  105. * @param a
  106. * @param b
  107. */
  108. static deepCompareArrays<T>(a: T[], b: T[]): boolean {
  109. if (a?.length !== b?.length) return false
  110. return Utils.deepCompare(a, b)
  111. }
  112. /**
  113. * Deep compare any values.
  114. * @param a
  115. * @param b
  116. */
  117. static deepCompare<T>(a: T, b: T): boolean {
  118. return a === b || JSON.stringify(a) === JSON.stringify(b)
  119. }
  120. /**
  121. * Find whether two arrays intersect.
  122. * @param a
  123. * @param b
  124. * @param fn An optional function to apply to the items of a; will check if b includes the result.
  125. */
  126. static arrsIntersect<T, K>(a: T[], b: K[], fn?: (item: K) => T): boolean
  127. static arrsIntersect<T>(a: T[], b: T[]): boolean
  128. static arrsIntersect<T>(
  129. a: T[],
  130. b: unknown[],
  131. fn?: (item: unknown) => T
  132. ): boolean {
  133. return a.some((item) => b.includes(fn ? fn(item) : item))
  134. }
  135. /**
  136. * Get the unique values from an array of strings or numbers.
  137. * @param items
  138. */
  139. static uniqueArray<T extends string | number>(...items: T[]): T[] {
  140. return Array.from(new Set(items).values())
  141. }
  142. /**
  143. * Convert a set to an array.
  144. * @param set
  145. */
  146. static setToArray<T>(set: Set<T>): T[] {
  147. return Array.from(set.values())
  148. }
  149. /**
  150. * Get the outer of between a circle and a point.
  151. * @param C The circle's center.
  152. * @param r The circle's radius.
  153. * @param P The point.
  154. * @param side
  155. */
  156. static getCircleTangentToPoint(
  157. C: number[],
  158. r: number,
  159. P: number[],
  160. side: number
  161. ): number[] {
  162. const B = vec.lrp(C, P, 0.5),
  163. r1 = vec.dist(C, B),
  164. delta = vec.sub(B, C),
  165. d = vec.len(delta)
  166. if (!(d <= r + r1 && d >= Math.abs(r - r1))) {
  167. return
  168. }
  169. const a = (r * r - r1 * r1 + d * d) / (2.0 * d),
  170. n = 1 / d,
  171. p = vec.add(C, vec.mul(delta, a * n)),
  172. h = Math.sqrt(r * r - a * a),
  173. k = vec.mul(vec.per(delta), h * n)
  174. return side === 0 ? vec.add(p, k) : vec.sub(p, k)
  175. }
  176. /**
  177. * Get outer tangents of two circles.
  178. * @param x0
  179. * @param y0
  180. * @param r0
  181. * @param x1
  182. * @param y1
  183. * @param r1
  184. * @returns [lx0, ly0, lx1, ly1, rx0, ry0, rx1, ry1]
  185. */
  186. static getOuterTangentsOfCircles(
  187. C0: number[],
  188. r0: number,
  189. C1: number[],
  190. r1: number
  191. ): number[][] {
  192. const a0 = vec.angle(C0, C1)
  193. const d = vec.dist(C0, C1)
  194. // Circles are overlapping, no tangents
  195. if (d < Math.abs(r1 - r0)) return
  196. const a1 = Math.acos((r0 - r1) / d),
  197. t0 = a0 + a1,
  198. t1 = a0 - a1
  199. return [
  200. [C0[0] + r0 * Math.cos(t1), C0[1] + r0 * Math.sin(t1)],
  201. [C1[0] + r1 * Math.cos(t1), C1[1] + r1 * Math.sin(t1)],
  202. [C0[0] + r0 * Math.cos(t0), C0[1] + r0 * Math.sin(t0)],
  203. [C1[0] + r1 * Math.cos(t0), C1[1] + r1 * Math.sin(t0)],
  204. ]
  205. }
  206. /**
  207. * Get the closest point on the perimeter of a circle to a given point.
  208. * @param C The circle's center.
  209. * @param r The circle's radius.
  210. * @param P The point.
  211. */
  212. static getClosestPointOnCircle(
  213. C: number[],
  214. r: number,
  215. P: number[]
  216. ): number[] {
  217. const v = vec.sub(C, P)
  218. return vec.sub(C, vec.mul(vec.div(v, vec.len(v)), r))
  219. }
  220. static det(
  221. a: number,
  222. b: number,
  223. c: number,
  224. d: number,
  225. e: number,
  226. f: number,
  227. g: number,
  228. h: number,
  229. i: number
  230. ): number {
  231. return a * e * i + b * f * g + c * d * h - a * f * h - b * d * i - c * e * g
  232. }
  233. /**
  234. * Get a circle from three points.
  235. * @param A
  236. * @param B
  237. * @param C
  238. * @returns [x, y, r]
  239. */
  240. static circleFromThreePoints(
  241. A: number[],
  242. B: number[],
  243. C: number[]
  244. ): number[] {
  245. const a = Utils.det(A[0], A[1], 1, B[0], B[1], 1, C[0], C[1], 1)
  246. const bx = -Utils.det(
  247. A[0] * A[0] + A[1] * A[1],
  248. A[1],
  249. 1,
  250. B[0] * B[0] + B[1] * B[1],
  251. B[1],
  252. 1,
  253. C[0] * C[0] + C[1] * C[1],
  254. C[1],
  255. 1
  256. )
  257. const by = Utils.det(
  258. A[0] * A[0] + A[1] * A[1],
  259. A[0],
  260. 1,
  261. B[0] * B[0] + B[1] * B[1],
  262. B[0],
  263. 1,
  264. C[0] * C[0] + C[1] * C[1],
  265. C[0],
  266. 1
  267. )
  268. const c = -Utils.det(
  269. A[0] * A[0] + A[1] * A[1],
  270. A[0],
  271. A[1],
  272. B[0] * B[0] + B[1] * B[1],
  273. B[0],
  274. B[1],
  275. C[0] * C[0] + C[1] * C[1],
  276. C[0],
  277. C[1]
  278. )
  279. const x = -bx / (2 * a)
  280. const y = -by / (2 * a)
  281. const r = Math.sqrt(bx * bx + by * by - 4 * a * c) / (2 * Math.abs(a))
  282. return [x, y, r]
  283. }
  284. /**
  285. * Find the approximate perimeter of an ellipse.
  286. * @param rx
  287. * @param ry
  288. */
  289. static perimeterOfEllipse(rx: number, ry: number): number {
  290. const h = Math.pow(rx - ry, 2) / Math.pow(rx + ry, 2)
  291. const p = Math.PI * (rx + ry) * (1 + (3 * h) / (10 + Math.sqrt(4 - 3 * h)))
  292. return p
  293. }
  294. /**
  295. * Get the short angle distance between two angles.
  296. * @param a0
  297. * @param a1
  298. */
  299. static shortAngleDist(a0: number, a1: number): number {
  300. const max = Math.PI * 2
  301. const da = (a1 - a0) % max
  302. return ((2 * da) % max) - da
  303. }
  304. /**
  305. * Get the long angle distance between two angles.
  306. * @param a0
  307. * @param a1
  308. */
  309. static longAngleDist(a0: number, a1: number): number {
  310. return Math.PI * 2 - Utils.shortAngleDist(a0, a1)
  311. }
  312. /**
  313. * Interpolate an angle between two angles.
  314. * @param a0
  315. * @param a1
  316. * @param t
  317. */
  318. static lerpAngles(a0: number, a1: number, t: number): number {
  319. return a0 + Utils.shortAngleDist(a0, a1) * t
  320. }
  321. /**
  322. * Get the short distance between two angles.
  323. * @param a0
  324. * @param a1
  325. */
  326. static angleDelta(a0: number, a1: number): number {
  327. return Utils.shortAngleDist(a0, a1)
  328. }
  329. /**
  330. * Get the "sweep" or short distance between two points on a circle's perimeter.
  331. * @param C
  332. * @param A
  333. * @param B
  334. */
  335. static getSweep(C: number[], A: number[], B: number[]): number {
  336. return Utils.angleDelta(vec.angle(C, A), vec.angle(C, B))
  337. }
  338. /**
  339. * Rotate a point around a center.
  340. * @param x The x-axis coordinate of the point.
  341. * @param y The y-axis coordinate of the point.
  342. * @param cx The x-axis coordinate of the point to rotate round.
  343. * @param cy The y-axis coordinate of the point to rotate round.
  344. * @param angle The distance (in radians) to rotate.
  345. */
  346. static rotatePoint(A: number[], B: number[], angle: number): number[] {
  347. const s = Math.sin(angle)
  348. const c = Math.cos(angle)
  349. const px = A[0] - B[0]
  350. const py = A[1] - B[1]
  351. const nx = px * c - py * s
  352. const ny = px * s + py * c
  353. return [nx + B[0], ny + B[1]]
  354. }
  355. /**
  356. * Clamp radians within 0 and 2PI
  357. * @param r
  358. */
  359. static clampRadians(r: number): number {
  360. return (Math.PI * 2 + r) % (Math.PI * 2)
  361. }
  362. /**
  363. * Clamp rotation to even segments.
  364. * @param r
  365. * @param segments
  366. */
  367. static clampToRotationToSegments(r: number, segments: number): number {
  368. const seg = (Math.PI * 2) / segments
  369. return Math.floor((Utils.clampRadians(r) + seg / 2) / seg) * seg
  370. }
  371. /**
  372. * Is angle c between angles a and b?
  373. * @param a
  374. * @param b
  375. * @param c
  376. */
  377. static isAngleBetween(a: number, b: number, c: number): boolean {
  378. if (c === a || c === b) return true
  379. const PI2 = Math.PI * 2
  380. const AB = (b - a + PI2) % PI2
  381. const AC = (c - a + PI2) % PI2
  382. return AB <= Math.PI !== AC > AB
  383. }
  384. /**
  385. * Convert degrees to radians.
  386. * @param d
  387. */
  388. static degreesToRadians(d: number): number {
  389. return (d * Math.PI) / 180
  390. }
  391. /**
  392. * Convert radians to degrees.
  393. * @param r
  394. */
  395. static radiansToDegrees(r: number): number {
  396. return (r * 180) / Math.PI
  397. }
  398. /**
  399. * Get the length of an arc between two points on a circle's perimeter.
  400. * @param C
  401. * @param r
  402. * @param A
  403. * @param B
  404. */
  405. static getArcLength(
  406. C: number[],
  407. r: number,
  408. A: number[],
  409. B: number[]
  410. ): number {
  411. const sweep = Utils.getSweep(C, A, B)
  412. return r * (2 * Math.PI) * (sweep / (2 * Math.PI))
  413. }
  414. /**
  415. * Get a dash offset for an arc, based on its length.
  416. * @param C
  417. * @param r
  418. * @param A
  419. * @param B
  420. * @param step
  421. */
  422. static getArcDashOffset(
  423. C: number[],
  424. r: number,
  425. A: number[],
  426. B: number[],
  427. step: number
  428. ): number {
  429. const del0 = Utils.getSweep(C, A, B)
  430. const len0 = Utils.getArcLength(C, r, A, B)
  431. const off0 = del0 < 0 ? len0 : 2 * Math.PI * C[2] - len0
  432. return -off0 / 2 + step
  433. }
  434. /**
  435. * Get a dash offset for an ellipse, based on its length.
  436. * @param A
  437. * @param step
  438. */
  439. static getEllipseDashOffset(A: number[], step: number): number {
  440. const c = 2 * Math.PI * A[2]
  441. return -c / 2 + -step
  442. }
  443. /**
  444. * Get an array of points between two points.
  445. * @param a
  446. * @param b
  447. * @param options
  448. */
  449. static getPointsBetween(
  450. a: number[],
  451. b: number[],
  452. options = {} as {
  453. steps?: number
  454. ease?: (t: number) => number
  455. }
  456. ): number[][] {
  457. const { steps = 6, ease = (t) => t * t * t } = options
  458. return Array.from(Array(steps))
  459. .map((_, i) => ease(i / steps))
  460. .map((t) => [...vec.lrp(a, b, t), (1 - t) / 2])
  461. }
  462. static getRayRayIntersection(
  463. p0: number[],
  464. n0: number[],
  465. p1: number[],
  466. n1: number[]
  467. ): number[] {
  468. const p0e = vec.add(p0, n0),
  469. p1e = vec.add(p1, n1),
  470. m0 = (p0e[1] - p0[1]) / (p0e[0] - p0[0]),
  471. m1 = (p1e[1] - p1[1]) / (p1e[0] - p1[0]),
  472. b0 = p0[1] - m0 * p0[0],
  473. b1 = p1[1] - m1 * p1[0],
  474. x = (b1 - b0) / (m0 - m1),
  475. y = m0 * x + b0
  476. return [x, y]
  477. }
  478. static bez1d(a: number, b: number, c: number, d: number, t: number): number {
  479. return (
  480. a * (1 - t) * (1 - t) * (1 - t) +
  481. 3 * b * t * (1 - t) * (1 - t) +
  482. 3 * c * t * t * (1 - t) +
  483. d * t * t * t
  484. )
  485. }
  486. static getCubicBezierBounds(
  487. p0: number[],
  488. c0: number[],
  489. c1: number[],
  490. p1: number[]
  491. ): Bounds {
  492. // solve for x
  493. let a = 3 * p1[0] - 9 * c1[0] + 9 * c0[0] - 3 * p0[0]
  494. let b = 6 * p0[0] - 12 * c0[0] + 6 * c1[0]
  495. let c = 3 * c0[0] - 3 * p0[0]
  496. let disc = b * b - 4 * a * c
  497. let xl = p0[0]
  498. let xh = p0[0]
  499. if (p1[0] < xl) xl = p1[0]
  500. if (p1[0] > xh) xh = p1[0]
  501. if (disc >= 0) {
  502. const t1 = (-b + Math.sqrt(disc)) / (2 * a)
  503. if (t1 > 0 && t1 < 1) {
  504. const x1 = Utils.bez1d(p0[0], c0[0], c1[0], p1[0], t1)
  505. if (x1 < xl) xl = x1
  506. if (x1 > xh) xh = x1
  507. }
  508. const t2 = (-b - Math.sqrt(disc)) / (2 * a)
  509. if (t2 > 0 && t2 < 1) {
  510. const x2 = Utils.bez1d(p0[0], c0[0], c1[0], p1[0], t2)
  511. if (x2 < xl) xl = x2
  512. if (x2 > xh) xh = x2
  513. }
  514. }
  515. // Solve for y
  516. a = 3 * p1[1] - 9 * c1[1] + 9 * c0[1] - 3 * p0[1]
  517. b = 6 * p0[1] - 12 * c0[1] + 6 * c1[1]
  518. c = 3 * c0[1] - 3 * p0[1]
  519. disc = b * b - 4 * a * c
  520. let yl = p0[1]
  521. let yh = p0[1]
  522. if (p1[1] < yl) yl = p1[1]
  523. if (p1[1] > yh) yh = p1[1]
  524. if (disc >= 0) {
  525. const t1 = (-b + Math.sqrt(disc)) / (2 * a)
  526. if (t1 > 0 && t1 < 1) {
  527. const y1 = Utils.bez1d(p0[1], c0[1], c1[1], p1[1], t1)
  528. if (y1 < yl) yl = y1
  529. if (y1 > yh) yh = y1
  530. }
  531. const t2 = (-b - Math.sqrt(disc)) / (2 * a)
  532. if (t2 > 0 && t2 < 1) {
  533. const y2 = Utils.bez1d(p0[1], c0[1], c1[1], p1[1], t2)
  534. if (y2 < yl) yl = y2
  535. if (y2 > yh) yh = y2
  536. }
  537. }
  538. return {
  539. minX: xl,
  540. minY: yl,
  541. maxX: xh,
  542. maxY: yh,
  543. width: Math.abs(xl - xh),
  544. height: Math.abs(yl - yh),
  545. }
  546. }
  547. static getExpandedBounds(a: Bounds, b: Bounds): Bounds {
  548. const minX = Math.min(a.minX, b.minX),
  549. minY = Math.min(a.minY, b.minY),
  550. maxX = Math.max(a.maxX, b.maxX),
  551. maxY = Math.max(a.maxY, b.maxY),
  552. width = Math.abs(maxX - minX),
  553. height = Math.abs(maxY - minY)
  554. return { minX, minY, maxX, maxY, width, height }
  555. }
  556. static getCommonBounds(...b: Bounds[]): Bounds {
  557. if (b.length < 2) return b[0]
  558. let bounds = b[0]
  559. for (let i = 1; i < b.length; i++) {
  560. bounds = Utils.getExpandedBounds(bounds, b[i])
  561. }
  562. return bounds
  563. }
  564. /**
  565. * Get a bezier curve data for a spline that fits an array of points.
  566. * @param pts
  567. * @param tension
  568. * @param isClosed
  569. * @param numOfSegments
  570. */
  571. static getCurvePoints(
  572. pts: number[][],
  573. tension = 0.5,
  574. isClosed = false,
  575. numOfSegments = 3
  576. ): number[][] {
  577. const _pts = [...pts],
  578. len = pts.length,
  579. res: number[][] = [] // results
  580. let t1x: number, // tension vectors
  581. t2x: number,
  582. t1y: number,
  583. t2y: number,
  584. c1: number, // cardinal points
  585. c2: number,
  586. c3: number,
  587. c4: number,
  588. st: number,
  589. st2: number,
  590. st3: number
  591. // The algorithm require a previous and next point to the actual point array.
  592. // Check if we will draw closed or open curve.
  593. // If closed, copy end points to beginning and first points to end
  594. // If open, duplicate first points to befinning, end points to end
  595. if (isClosed) {
  596. _pts.unshift(_pts[len - 1])
  597. _pts.push(_pts[0])
  598. } else {
  599. //copy 1. point and insert at beginning
  600. _pts.unshift(_pts[0])
  601. _pts.push(_pts[len - 1])
  602. // _pts.push(_pts[len - 1])
  603. }
  604. // For each point, calculate a segment
  605. for (let i = 1; i < _pts.length - 2; i++) {
  606. // Calculate points along segment and add to results
  607. for (let t = 0; t <= numOfSegments; t++) {
  608. // Step
  609. st = t / numOfSegments
  610. st2 = Math.pow(st, 2)
  611. st3 = Math.pow(st, 3)
  612. // Cardinals
  613. c1 = 2 * st3 - 3 * st2 + 1
  614. c2 = -(2 * st3) + 3 * st2
  615. c3 = st3 - 2 * st2 + st
  616. c4 = st3 - st2
  617. // Tension
  618. t1x = (_pts[i + 1][0] - _pts[i - 1][0]) * tension
  619. t2x = (_pts[i + 2][0] - _pts[i][0]) * tension
  620. t1y = (_pts[i + 1][1] - _pts[i - 1][1]) * tension
  621. t2y = (_pts[i + 2][1] - _pts[i][1]) * tension
  622. // Control points
  623. res.push([
  624. c1 * _pts[i][0] + c2 * _pts[i + 1][0] + c3 * t1x + c4 * t2x,
  625. c1 * _pts[i][1] + c2 * _pts[i + 1][1] + c3 * t1y + c4 * t2y,
  626. ])
  627. }
  628. }
  629. res.push(pts[pts.length - 1])
  630. return res
  631. }
  632. /**
  633. * Simplify a line (using Ramer-Douglas-Peucker algorithm).
  634. * @param points An array of points as [x, y, ...][]
  635. * @param tolerance The minimum line distance (also called epsilon).
  636. * @returns Simplified array as [x, y, ...][]
  637. */
  638. static simplify(points: number[][], tolerance = 1): number[][] {
  639. const len = points.length,
  640. a = points[0],
  641. b = points[len - 1],
  642. [x1, y1] = a,
  643. [x2, y2] = b
  644. if (len > 2) {
  645. let distance = 0
  646. let index = 0
  647. const max = Math.hypot(y2 - y1, x2 - x1)
  648. for (let i = 1; i < len - 1; i++) {
  649. const [x0, y0] = points[i],
  650. d =
  651. Math.abs((y2 - y1) * x0 - (x2 - x1) * y0 + x2 * y1 - y2 * x1) / max
  652. if (distance > d) continue
  653. distance = d
  654. index = i
  655. }
  656. if (distance > tolerance) {
  657. const l0 = Utils.simplify(points.slice(0, index + 1), tolerance)
  658. const l1 = Utils.simplify(points.slice(index + 1), tolerance)
  659. return l0.concat(l1.slice(1))
  660. }
  661. }
  662. return [a, b]
  663. }
  664. }