|
| 1 | +/* eslint-disable no-constant-condition */ |
| 2 | +import { unsafeCoerce } from "../../data/Function.js" |
| 3 | +import type { Predicate } from "../../data/Predicate.js" |
| 4 | +import { List } from "./definition.js" |
| 5 | + |
| 6 | +/** |
| 7 | + * @tsplus fluent List filter |
| 8 | + */ |
| 9 | +export function filter<A>(self: List<A>, p: Predicate<A>): List<A> { |
| 10 | + return filterCommon_(self, p, false) |
| 11 | +} |
| 12 | + |
| 13 | +function noneIn<A>(l: List<A>, p: Predicate<A>, isFlipped: boolean): List<A> { |
| 14 | + while (true) { |
| 15 | + if (l.isNil()) { |
| 16 | + return List.nil() |
| 17 | + } else { |
| 18 | + if (p(l.head) !== isFlipped) { |
| 19 | + return allIn(l, l.tail, p, isFlipped) |
| 20 | + } else { |
| 21 | + l = l.tail |
| 22 | + } |
| 23 | + } |
| 24 | + } |
| 25 | +} |
| 26 | + |
| 27 | +function allIn<A>( |
| 28 | + start: List<A>, |
| 29 | + remaining: List<A>, |
| 30 | + p: Predicate<A>, |
| 31 | + isFlipped: boolean |
| 32 | +): List<A> { |
| 33 | + while (true) { |
| 34 | + if (remaining.isNil()) { |
| 35 | + return start |
| 36 | + } else { |
| 37 | + if (p(remaining.head) !== isFlipped) { |
| 38 | + remaining = remaining.tail |
| 39 | + } else { |
| 40 | + return partialFill(start, remaining, p, isFlipped) |
| 41 | + } |
| 42 | + } |
| 43 | + } |
| 44 | +} |
| 45 | + |
| 46 | +function partialFill<A>( |
| 47 | + origStart: List<A>, |
| 48 | + firstMiss: List<A>, |
| 49 | + p: Predicate<A>, |
| 50 | + isFlipped: boolean |
| 51 | +): List<A> { |
| 52 | + const newHead = List.cons<A>(origStart.unsafeHead()!, List.nil()) |
| 53 | + let toProcess = origStart.unsafeTail()! as List.Cons<A> |
| 54 | + let currentLast = newHead |
| 55 | + |
| 56 | + while (!(toProcess === firstMiss)) { |
| 57 | + const newElem = List.cons(toProcess.unsafeHead()!, List.nil()) |
| 58 | + currentLast.tail = newElem |
| 59 | + currentLast = unsafeCoerce(newElem) |
| 60 | + toProcess = unsafeCoerce(toProcess.tail) |
| 61 | + } |
| 62 | + |
| 63 | + let next = firstMiss.tail |
| 64 | + let nextToCopy: List.Cons<A> = unsafeCoerce(next) |
| 65 | + while (!next.isNil()) { |
| 66 | + const head = next.unsafeHead()! |
| 67 | + if (p(head) !== isFlipped) { |
| 68 | + next = next.tail |
| 69 | + } else { |
| 70 | + while (!(nextToCopy === next)) { |
| 71 | + const newElem = List.cons(nextToCopy.unsafeHead()!, List.nil()) |
| 72 | + currentLast.tail = newElem |
| 73 | + currentLast = newElem |
| 74 | + nextToCopy = unsafeCoerce(nextToCopy.tail) |
| 75 | + } |
| 76 | + nextToCopy = unsafeCoerce(next.tail) |
| 77 | + next = next.tail |
| 78 | + } |
| 79 | + } |
| 80 | + |
| 81 | + if (!nextToCopy.isNil()) { |
| 82 | + currentLast.tail = nextToCopy |
| 83 | + } |
| 84 | + |
| 85 | + return newHead |
| 86 | +} |
| 87 | + |
| 88 | +function filterCommon_<A>(list: List<A>, p: Predicate<A>, isFlipped: boolean): List<A> { |
| 89 | + return noneIn(list, p, isFlipped) |
| 90 | +} |
0 commit comments