Skip to content
TheChatArchiveThe Chat Archive
o1-mini-2024-09-12· OpenAIAi2 WildChat-4.8M (AI2)

Popraw poniższy kod zgodnie z uwagą z code review. /// rules-utils.ts import…

  1. User

    Popraw poniższy kod zgodnie z uwagą z code review.

    /// rules-utils.ts

    import ValidatePolish from "@/lib/validate-polish"; import Util from "@/lib/util";

    export class RulesUtils { public static NotEmpty = [v => !!v || "Pole wymagane"]; public static NotEmptyAllowZero = [v => v === 0 || !!v || "Pole wymagane"]; public static NotEmptyArray = [v => (!!v && v.length > 0) || "Pole wymagane"];

    public static OptionalPrice = [ v => v === null || (ValidatePolish.amount(v) && Number(v) >= 0 && Number(v) < 100000) || "Niepoprawna wartość" ];

    public static Price = [ v => (v !== "" && v !== null) || "Pole jest wymagane", ...RulesUtils.OptionalPrice ];

    public static OptionalEmail = [ v => !v || (!!v && ValidatePolish.email(v)) || "Niepoprawny adres e-mail" ]; public static MandatoryEmail = [ v => (!!v && ValidatePolish.email(v)) || "Niepoprawny adres e-mail" ];

    public static OptionalPhoneNumber = [ v => !v || (!!v && ValidatePolish.phoneNumber(v)) || "Niepoprawny numer telefonu" ];

    public static MandatoryPesel = [ ...RulesUtils.NotEmpty, v => !v || (!!v && ValidatePolish.pesel(v)) || "Niepoprawny numer Pesel" ]; public static OptionalPesel = [ v => !v || (!!v && ValidatePolish.pesel(v)) || "Niepoprawny numer Pesel" ];

    public static OptionalRegon = [ v => !v || (!!v && (v.length === 7 || v.length === 9 || v.length === 14) && Number.isInteger(Number(v))) || "Niepoprawny Regon" ];

    public static RequiredRegon = [v => !!v || "Pole wymagane", ...RulesUtils.OptionalRegon];

    public static IPAddress = [ v => /^(25[0-5]|2[0-4]\d|[01]?\d\d?).(25[0-5]|2[0-4]\d|[01]?\d\d?).(25[0-5]|2[0-4]\d|[01]?\d\d?).(25[0-5]|2[0-4]\d|[01]?\d\d?)$/.test(v) || "Niepoprawny adres IP" ];

    public static NonNullNumber() { return [v => !!v || v === 0 || "Wartość nie może byś pusta"]; }

    public static IntegerNumber() { return [v => (!v && v !== 0) || Number.isInteger(Number(v)) || "Wartość musi być całkowita"]; }

    public static MinNumber(min: number) { return [ v => (!v && v !== 0) || Number(v) >= min || Wartość musi być więsza bądź równa ${min} ]; }

    public static MaxNumber(max: number) { return [ v => (!v && v !== 0) || Number(v) <= max || Wartość musi być mniejsza bądź równa ${max} ]; }

    public static OptionalInteger(min: number, max: number) { return [ ...RulesUtils.IntegerNumber(), ...RulesUtils.MinNumber(min), ...RulesUtils.MaxNumber(max) ]; }

    public static MandatoryInteger(min: number, max: number) { return [...RulesUtils.NonNullNumber(), ...RulesUtils.OptionalInteger(min, max)]; } public static MandatoryString(maxChars: number, minChars?: number) { const minCharsRules = minChars ? [v => !v || v.length >= minChars || Pole musi mieć przynajmniej ${minChars} znaki] : []; return [ v => !!v || "Pole wymagane", v => (!!v && v.length >= 0) || "Pusta wartość", v => (!!v && v.length >= 0 && v.length < maxChars) || "Nazwa za długa", ...minCharsRules ]; }

    public static OptionalString(maxChars: number, minChars?: number) { const minCharsRules = minChars ? [v => !v || v.length >= minChars || Pole musi mieć przynajmniej ${minChars} znaki] : []; return [ v => !v || (!!v && v.length >= 0 && v.length < maxChars) || "Nazwa za długa", ...minCharsRules ]; }

    public static PostalCode() { return [v => (!!v && /^[0-9]{2}-[0-9]{3}$/.test(v)) || "Niepoprawny kod pocztowy"]; }

    public static ExcludedHtmlControlSequences() { return RulesUtils.ExcludedStrings([""]); }

    public static ExcludedStrings(vals: string[]) { return vals.map( exV => v => !${v}.includes(exV) || Tekst zawiera niedozwolone sekwencje znaków: ${exV} ); }

    public static isValidPercent(v: any) { return Number.isInteger(Number(v * 100)) && Number(v) >= 0 && Number(v) <= 100; }

    public static isValidAmount(v: any, max: number) { return ValidatePolish.amount(v) && Number(v) >= 0 && Number(v) < max; }

    public static OptionalPercentRules = [ v => (!v && v !== 0) || RulesUtils.isValidPercent(v) || "Niepoprawna wartość" ];

    public static OptionalAmountRules(max?: number) { return [ v => (!v && v !== 0) || RulesUtils.isValidAmount(v, max || 100000) || "Niepoprawna wartość" ]; }

    public static MandatoryPercentRules = [ v => v !== "" || "Pole jest wymagane", v => RulesUtils.isValidPercent(v) || "Niepoprawna wartość" ];

    public static MandatoryAmountRules(max?: number) { return [ v => v !== "" || "Pole jest wymagane", v => RulesUtils.isValidAmount(v, max || 100000) || "Niepoprawna wartość" ]; }

    public static MandatoryFile(maxSize: number) { return [ v => { if (!v) return "Pole obowiązkowe"; if (v.size > maxSize) { return Załączony plik musi mieć rozmiar mniejszy od ${Util.formatBytes( maxSize )}; } return true; } ]; }

    public static optionalBankAccount = [ v => !v || (!!v && RulesUtils.isBankAccountValid(v)) || "Podaj prawidłowy numer konta bankowego" ]; public static mandatoryBankAccount = [ ...RulesUtils.NotEmpty, ...RulesUtils.optionalBankAccount ];

    private static isBankAccountValid(nrb: string) { nrb = nrb.replace(/[^0-9]+/g, ""); const weights = [ 1, 10, 3, 30, 9, 90, 27, 76, 81, 34, 49, 5, 50, 15, 53, 45, 62, 38, 89, 17, 73, 51, 25, 56, 75, 71, 31, 19, 93, 57 ];

    if (nrb.length !== 26) {
      return false;
    }
    nrb = nrb + "2521";
    nrb = nrb.substring(2) + nrb.substring(0, 2);
    let Z = 0;
    for (let i = 0; i < 30; i++) {
      Z += parseInt(nrb[29 - i]) * weights[i];
    }
    return Z % 97 === 1;
    

    }

    public static BonusAmountRules = [ ...RulesUtils.NotEmpty, v => (ValidatePolish.amount(v) && Number(v) >= 0 && Number(v) < 100000) || "Niepoprawna wartość" ];

    public static NonNegativeNumber = [ v => Number(v) >= 0 || "Liczba musi być nieujemna" ]; }

    /// CODE REVIEW - UWAGA

    ' BonusAmountRules' to jest to samo co 'Price' wyżej I można uwspólnić

  2. Assistant

    Aby zastosować się do uwagi z code review, musimy usunąć duplikację pomiędzy BonusAmountRules a Price. Ponieważ oba te zestawy reguł walidacji są identyczne, możemy je zjednoczyć, używając Price w miejscu BonusAmountRules. Poniżej przedstawiam poprawiony kod:

    /// rules-utils.ts
    
    import ValidatePolish from "@/lib/validate-polish";
    import Util from "@/lib/util";
    
    export class RulesUtils {
      public static NotEmpty = [v => !!v || "Pole wymagane"];
      public static NotEmptyAllowZero = [v => v === 0 || !!v || "Pole wymagane"];
      public static NotEmptyArray = [v => (!!v && v.length > 0) || "Pole wymagane"];
    
      public static OptionalPrice = [
        v =>
          v === null ||
          (ValidatePolish.amount(v) && Number(v) >= 0 && Number(v) < 100000) ||
          "Niepoprawna wartość"
      ];
    
      public static Price = [
        v => (v !== "" && v !== null) || "Pole jest wymagane",
        ...RulesUtils.OptionalPrice
      ];
    
      // Usuń BonusAmountRules i używaj Price zamiast niego
      public static BonusAmountRules = RulesUtils.Price;
    
      public static OptionalEmail = [
        v => !v || (!!v && ValidatePolish.email(v)) || "Niepoprawny adres e-mail"
      ];
      public static MandatoryEmail = [
        v => (!!v && ValidatePolish.email(v)) || "Niepoprawny adres e-mail"
      ];
    
      public static OptionalPhoneNumber = [
        v => !v || (!!v && ValidatePolish.phoneNumber(v)) || "Niepoprawny numer telefonu"
      ];
    
      public static MandatoryPesel = [
        ...RulesUtils.NotEmpty,
        v => !v || (!!v && ValidatePolish.pesel(v)) || "Niepoprawny numer Pesel"
      ];
      public static OptionalPesel = [
        v => !v || (!!v && ValidatePolish.pesel(v)) || "Niepoprawny numer Pesel"
      ];
    
      public static OptionalRegon = [
        v =>
          !v ||
          (!!v &&
            (v.length === 7 || v.length === 9 || v.length === 14) &&
            Number.isInteger(Number(v))) ||
          "Niepoprawny Regon"
      ];
    
      public static RequiredRegon = [v => !!v || "Pole wymagane", ...RulesUtils.OptionalRegon];
    
      public static IPAddress = [
        v =>
          /^(25[0-5]|2[0-4]\d|[01]?\d\d?)\.(25[0-5]|2[0-4]\d|[01]?\d\d?)\.(25[0-5]|2[0-4]\d|[01]?\d\d?)\.(25[0-5]|2[0-4]\d|[01]?\d\d?)$/.test(v) ||
          "Niepoprawny adres IP"
      ];
    
      public static NonNullNumber() {
        return [v => !!v || v === 0 || "Wartość nie może byś pusta"];
      }
    
      public static IntegerNumber() {
        return [v => (!v && v !== 0) || Number.isInteger(Number(v)) || "Wartość musi być całkowita"];
      }
    
      public static MinNumber(min: number) {
        return [
          v => (!v && v !== 0) || Number(v) >= min || `Wartość musi być więsza bądź równa ${min}`
        ];
      }
    
      public static MaxNumber(max: number) {
        return [
          v => (!v && v !== 0) || Number(v) <= max || `Wartość musi być mniejsza bądź równa ${max}`
        ];
      }
    
      public static OptionalInteger(min: number, max: number) {
        return [
          ...RulesUtils.IntegerNumber(),
          ...RulesUtils.MinNumber(min),
          ...RulesUtils.MaxNumber(max)
        ];
      }
    
      public static MandatoryInteger(min: number, max: number) {
        return [...RulesUtils.NonNullNumber(), ...RulesUtils.OptionalInteger(min, max)];
      }
      
      public static MandatoryString(maxChars: number, minChars?: number) {
        const minCharsRules = minChars
          ? [v => !v || v.length >= minChars || `Pole musi mieć przynajmniej ${minChars} znaki`]
          : [];
        return [
          v => !!v || "Pole wymagane",
          v => (!!v && v.length >= 0) || "Pusta wartość",
          v => (!!v && v.length >= 0 && v.length < maxChars) || "Nazwa za długa",
          ...minCharsRules
        ];
      }
    
      public static OptionalString(maxChars: number, minChars?: number) {
        const minCharsRules = minChars
          ? [v => !v || v.length >= minChars || `Pole musi mieć przynajmniej ${minChars} znaki`]
          : [];
        return [
          v => !v || (!!v && v.length >= 0 && v.length < maxChars) || "Nazwa za długa",
          ...minCharsRules
        ];
      }
    
      public static PostalCode() {
        return [v => (!!v && /^[0-9]{2}-[0-9]{3}$/.test(v)) || "Niepoprawny kod pocztowy"];
      }
    
      public static ExcludedHtmlControlSequences() {
        return RulesUtils.ExcludedStrings(["<!--", "-->"]);
      }
    
      public static ExcludedStrings(vals: string[]) {
        return vals.map(
          exV => v => !`${v}`.includes(exV) || `Tekst zawiera niedozwolone sekwencje znaków: ${exV}`
        );
      }
    
      public static isValidPercent(v: any) {
        return Number.isInteger(Number(v * 100)) && Number(v) >= 0 && Number(v) <= 100;
      }
    
      public static isValidAmount(v: any, max: number) {
        return ValidatePolish.amount(v) && Number(v) >= 0 && Number(v) < max;
      }
    
      public static OptionalPercentRules = [
        v => (!v && v !== 0) || RulesUtils.isValidPercent(v) || "Niepoprawna wartość"
      ];
    
      public static OptionalAmountRules(max?: number) {
        return [
          v => (!v && v !== 0) || RulesUtils.isValidAmount(v, max || 100000) || "Niepoprawna wartość"
        ];
      }
    
      public static MandatoryPercentRules = [
        v => v !== "" || "Pole jest wymagane",
        v => RulesUtils.isValidPercent(v) || "Niepoprawna wartość"
      ];
    
      public static MandatoryAmountRules(max?: number) {
        return [
          v => v !== "" || "Pole jest wymagane",
          v => RulesUtils.isValidAmount(v, max || 100000) || "Niepoprawna wartość"
        ];
      }
    
      public static MandatoryFile(maxSize: number) {
        return [
          v => {
            if (!v) return "Pole obowiązkowe";
            if (v.size > maxSize) {
              return `Załączony plik musi mieć rozmiar mniejszy od ${Util.formatBytes(
                maxSize
              )}`;
            }
            return true;
          }
        ];
      }
    
      public static optionalBankAccount = [
        v => !v || (!!v && RulesUtils.isBankAccountValid(v)) || "Podaj prawidłowy numer konta bankowego"
      ];
      public static mandatoryBankAccount = [
        ...RulesUtils.NotEmpty,
        ...RulesUtils.optionalBankAccount
      ];
    
      private static isBankAccountValid(nrb: string) {
        nrb = nrb.replace(/[^0-9]+/g, "");
        const weights = [
          1, 10, 3, 30, 9, 90, 27, 76, 81, 34, 49, 5, 50, 15, 53, 45, 62, 38, 89, 17, 73, 51, 25, 56,
          75, 71, 31, 19, 93, 57
        ];
    
        if (nrb.length !== 26) {
          return false;
        }
        nrb = nrb + "2521";
        nrb = nrb.substring(2) + nrb.substring(0, 2);
        let Z = 0;
        for (let i = 0; i < 30; i++) {
          Z += parseInt(nrb[29 - i]) * weights[i];
        }
        return Z % 97 === 1;
      }
    
      // BonusAmountRules teraz korzysta z Price, eliminując duplikację
      // public static BonusAmountRules = [
      //   ...RulesUtils.NotEmpty,
      //   v => (ValidatePolish.amount(v) && Number(v) >= 0 && Number(v) < 100000) || "Niepoprawna wartość"
      // ];
    
      public static BonusAmountRules = RulesUtils.Price;
    
      public static NonNegativeNumber = [
        v => Number(v) >= 0 || "Liczba musi być nieujemna"
      ];
    }
    

    Zmiany wprowadzone:

    1. Usunięto duplikację: BonusAmountRules zostało zastąpione przez Price, eliminując tym samym powtarzanie tych samych reguł walidacyjnych.

      // Usunięto duplikację
      // public static BonusAmountRules = [
      //   ...RulesUtils.NotEmpty,
      //   v => (ValidatePolish.amount(v) && Number(v) >= 0 && Number(v) < 100000) || "Niepoprawna wartość"
      // ];
      
      // Teraz BonusAmountRules korzysta z Price
      public static BonusAmountRules = RulesUtils.Price;
      
    2. Użycie RulesUtils.Price w BonusAmountRules: Dzięki temu, jeśli w przyszłości zmienią się reguły dla Price, BonusAmountRules automatycznie odziedziczy te zmiany, zapewniając spójność walidacji.

    3. Komentarze: Dodano komentarze wskazujące na usunięcie duplikacji i wyjaśnienie, dlaczego BonusAmountRules korzysta z Price.

    Dzięki tym zmianom kod jest bardziej przejrzysty, łatwiejszy w utrzymaniu i zgodny z zasadą DRY (Don't Repeat Yourself).