import {Define} from "./Define"; import {comparable, comparator,comparatorFn} from "./Interface"; import {NullPointerException, RuntimeException} from "./Exception"; import {Collections} from "./Collections"; import {Objects} from "./type/Objects"; /**** * */ //type reversed = { new(compare: comparator): comparator }; type NullComparator = { new(nullFirst:boolean, comparator: comparator): comparator }; /**** * */ export abstract class Comparators { /**** * */ private constructor() { throw new RuntimeException("no usage inside !"); } /**** * */ public static Reversed = class Reversed implements comparator{ readonly comparator: comparator; constructor(comparator:comparator) { this.comparator = comparator;} public compare(o1: T, o2: T): number { return Objects.isNull(this.comparator) ? 0 : -this.comparator.compare(o1,o2); } public reversed(): comparator{return >>Comparators.naturalOrder;} public thenComparing( other: comparator ):Reversed{ return new Reversed( Objects.isNull(other) ? other : this.comparator ); } public thenComparingFn>(comparatorFn: comparatorFn, comparator: comparator = null ): comparator { return undefined; } } /*** * */ public static naturalOrder:comparator> = new class NaturalOrder implements comparator>{ /*** * @throws NullPointerException : when compareTo is not defined */ public compare(o1: comparable, o2: comparable): number { if(Objects.isNull(o1)&&Objects.isNull(o2)||Objects.isNull(o1)||Objects.isNull(o2)) return 0; if(Objects.isNull(o2.compareTo)) throw new NullPointerException(`${o2.getClass().getName()} class doesn't not implement comparable interface`); return o1.compareTo(o2); } public reversed>(): comparator> {return >>Collections.reverseOrder();} /*** * @thenComparing? * @thenComparingFn?> */ }; /**** * */ public static NullComparator:NullComparator = class NullComparators implements comparator{ private readonly nullFirst:boolean; private readonly comparator: comparator; constructor(nullFirst:boolean, comparator:comparator) { this.nullFirst = nullFirst; this.comparator = comparator; } public compare(o1: T, o2: T): number { let a:Define = Define.of(o1), b:Define = Define.of(o2); if(a.isNull()) return b.isNull() ? 0 : ( this.nullFirst ? -1 : 1 ); else if( b.isNull() ){ return this.nullFirst ? 1 : -1; }else{ return Define.of(this.comparator ).isNull() ? 0 : this.comparator.compare(o1,o2); } } public reversed(): comparator{ return new NullComparators(!this.nullFirst, Objects.isNull(this.comparator) ? null : this.comparator.reversed()); } public thenComparing?( other: comparator ):NullComparators{ Objects.requireNotNull(other); return new NullComparators(this.nullFirst, Objects.isNull(other) ? other : this.comparator ); } public thenComparingFn?>(comparatorFn: comparatorFn, comparator: comparator = null): comparator { return undefined; } } /***/ } Object.package(this);