Skip to content

Commit

Permalink
Replace all uses of R.compact with filtering
Browse files Browse the repository at this point in the history
  • Loading branch information
stwlam committed Jun 29, 2024
1 parent 445ece8 commit 8c8f91e
Show file tree
Hide file tree
Showing 80 changed files with 348 additions and 306 deletions.
4 changes: 2 additions & 2 deletions build/lib/level-database.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ class LevelDatabase extends ClassicLevel<string, DBEntry> {

async createPack(docSources: DBEntry[], folders: DBFolder[]): Promise<void> {
const isDoc = (source: unknown): source is EmbeddedEntry => {
return R.isObject(source) && "_id" in source;
return R.isPlainObject(source) && "_id" in source;
};
const docBatch = this.#documentDb.batch();
const embeddedBatch = this.#embeddedDb?.batch();
Expand Down Expand Up @@ -83,7 +83,7 @@ class LevelDatabase extends ClassicLevel<string, DBEntry> {
const embeddedDocs = await this.#embeddedDb.getMany(
source[embeddedKey]?.map((embeddedId) => `${docId}.${embeddedId}`) ?? [],
);
source[embeddedKey] = R.compact(embeddedDocs);
source[embeddedKey] = embeddedDocs.filter(R.isTruthy);
}
packSources.push(source as PackEntry);
}
Expand Down
2 changes: 1 addition & 1 deletion src/module/active-effect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ export class ActiveEffectPF2e<TParent extends ActorPF2e | ItemPF2e | null> exten
duration,
origin: effect.uuid,
transfer: true,
statuses: R.filter([effect.slug], R.isTruthy),
statuses: [effect.slug].filter(R.isTruthy),
flags: fu.deepClone(effect.flags),
_stats: fu.deepClone(effect._stats),
},
Expand Down
24 changes: 14 additions & 10 deletions src/module/actor/army/document.ts
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ class ArmyPF2e<TParent extends TokenDocumentPF2e | null = TokenDocumentPF2e | nu
const acAdjustment = this.system.ac.value - expectedAC;
this.armorClass = new ArmorStatistic(this, {
attribute: null,
modifiers: R.compact([
modifiers: [
new ModifierPF2e({
slug: "base",
label: "PF2E.ModifierTitle",
Expand All @@ -129,7 +129,7 @@ class ArmyPF2e<TParent extends TokenDocumentPF2e | null = TokenDocumentPF2e | nu
}),
this.system.ac.potency &&
new ModifierPF2e({ slug: "potency", label: "Potency", modifier: this.system.ac.potency }),
]),
].filter(R.isTruthy),
}).dc;
this.system.ac.value = this.armorClass.value;

Expand All @@ -139,7 +139,7 @@ class ArmyPF2e<TParent extends TokenDocumentPF2e | null = TokenDocumentPF2e | nu
slug: "scouting",
label: "PF2E.Kingmaker.Army.Scouting",
domains: ["scouting"],
modifiers: R.compact([
modifiers: [
new ModifierPF2e({ slug: "base", label: "PF2E.ModifierTitle", modifier: baseScouting }),
scoutAdjustment
? new ModifierPF2e({
Expand All @@ -148,7 +148,7 @@ class ArmyPF2e<TParent extends TokenDocumentPF2e | null = TokenDocumentPF2e | nu
modifier: scoutAdjustment,
})
: null,
]),
].filter(R.isTruthy),
});
this.system.scouting = this.scouting.mod;

Expand All @@ -163,7 +163,7 @@ class ArmyPF2e<TParent extends TokenDocumentPF2e | null = TokenDocumentPF2e | nu
slug: saveType,
label: `PF2E.Kingmaker.Army.Save.${saveType}`,
domains: ["saving-throw", saveType],
modifiers: R.compact([
modifiers: [
new ModifierPF2e({ slug: "base", label: "PF2E.ModifierTitle", modifier: baseValue }),
adjustment
? new ModifierPF2e({
Expand All @@ -172,14 +172,18 @@ class ArmyPF2e<TParent extends TokenDocumentPF2e | null = TokenDocumentPF2e | nu
modifier: adjustment,
})
: null,
]),
].filter(R.isTruthy),
});
}

const tiebreakPriority = this.hasPlayerOwner ? 2 : 1;
this.initiative = new ActorInitiative(this, { statistic: "scouting", tiebreakPriority });
this.strikes = R.flatMapToObj(["melee", "ranged"] as const, (t) =>
this.system.weapons[t] ? [[t, this.prepareArmyStrike(t)]] : [],
this.strikes = Object.fromEntries(
(["melee", "ranged"] as const)
.map((t): [string, ArmyStrike | null] | null =>
this.system.weapons[t] ? [t, this.prepareArmyStrike(t)] : null,
)
.filter(R.isTruthy),
);

for (const tactic of this.itemTypes.campaignFeature.filter((i) => i.category === "army-tactic")) {
Expand Down Expand Up @@ -253,7 +257,7 @@ class ArmyPF2e<TParent extends TokenDocumentPF2e | null = TokenDocumentPF2e | nu
domains: attackDomains,
rollOptions: [`item:${type}`],
check: { type: "attack-roll" },
modifiers: R.compact([
modifiers: [
new ModifierPF2e({
slug: "base",
label: "PF2E.ModifierTitle",
Expand All @@ -268,7 +272,7 @@ class ArmyPF2e<TParent extends TokenDocumentPF2e | null = TokenDocumentPF2e | nu
predicate: ["target:effect:concealed"],
hideIfDisabled: true,
}),
]),
].filter(R.isTruthy),
});

const dealDamage = async (
Expand Down
5 changes: 3 additions & 2 deletions src/module/actor/base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1200,7 +1200,8 @@ class ActorPF2e<TParent extends TokenDocumentPF2e | null = TokenDocumentPF2e | n
const statements = ((): string => {
const deathMessage =
instantDeath && localize(`InstantDeath.${sluggify(instantDeath, { camel: "bactrian" })}`);
const concatenated = R.compact([hpStatement, shieldStatement, deathMessage])
const concatenated = [hpStatement, shieldStatement, deathMessage]
.filter(R.isTruthy)
.map((s) =>
game.i18n.format(s, {
actor: token.name.replace(/[<>]/g, ""),
Expand Down Expand Up @@ -1246,7 +1247,7 @@ class ActorPF2e<TParent extends TokenDocumentPF2e | null = TokenDocumentPF2e | n
const content = await renderTemplate("systems/pf2e/templates/chat/damage/damage-taken.hbs", {
breakdown,
statements,
persistent: R.compact(persistentCreated.map((p) => p.system.persistent?.damage.formula)),
persistent: persistentCreated.map((p) => p.system.persistent?.damage.formula).filter(R.isTruthy),
iwr: {
applications: result.applications,
visibility: this.hasPlayerOwner ? "all" : "gm",
Expand Down
4 changes: 2 additions & 2 deletions src/module/actor/character/attribute-builder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -218,7 +218,7 @@ class AttributeBuilder extends Application {
if (level < 5 || build.manual || isApex) {
return false;
}
const boosts = R.compact([
const boosts = [
build.boosts.ancestry.find((a) => a === attribute),
build.boosts.background.find((a) => a === attribute),
build.boosts.class === attribute ? attribute : null,
Expand All @@ -227,7 +227,7 @@ class AttributeBuilder extends Application {
level >= 15 ? build.boosts[15].find((a) => a === attribute) : null,
level >= 10 ? build.boosts[10].find((a) => a === attribute) : null,
level >= 5 ? build.boosts[5].find((a) => a === attribute) : null,
]).length;
].filter(R.isTruthy).length;
const flaws = Number(build.flaws.ancestry.some((a) => a === attribute));
const netBoosts = boosts - flaws;

Expand Down
53 changes: 28 additions & 25 deletions src/module/actor/character/document.ts
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,8 @@ class CharacterPF2e<TParent extends TokenDocumentPF2e | null = TokenDocumentPF2e
.sort((a, b) => b.mod - a.mod)
.shift();
return (
R.compact([highestClass, highestSpell])
[highestClass, highestSpell]
.filter(R.isTruthy)
.sort((a, b) => b.mod - a.mod)
.shift() ?? null
);
Expand Down Expand Up @@ -442,7 +443,7 @@ class CharacterPF2e<TParent extends TokenDocumentPF2e | null = TokenDocumentPF2e
// Attack and defense proficiencies
type PartialMartialProficiency = Record<string, Partial<MartialProficiency> | undefined>;
const attacks: PartialMartialProficiency = (system.proficiencies.attacks ??= {});
for (const category of R.keys.strict(CONFIG.PF2E.weaponCategories)) {
for (const category of Object.keys(CONFIG.PF2E.weaponCategories)) {
attacks[category] = {
rank: attacks[category]?.rank ?? 0,
custom: !!attacks[category]?.custom,
Expand Down Expand Up @@ -494,7 +495,9 @@ class CharacterPF2e<TParent extends TokenDocumentPF2e | null = TokenDocumentPF2e
this.system.details.languages.value = R.unique([...sourceLanguages, ...grantedLanguages]);

// When tallying the number of languages taken, make sure Common and its actual language aren't counted twice
const commonAndCommon = R.compact(["common", game.pf2e.settings.campaign.languages.commonLanguage]);
const commonAndCommon = (["common", game.pf2e.settings.campaign.languages.commonLanguage] as const).filter(
R.isTruthy,
);
const hasCommonTwice =
commonAndCommon.length === 2 &&
commonAndCommon.every((l) => this.system.details.languages.value.includes(l));
Expand Down Expand Up @@ -1113,23 +1116,26 @@ class CharacterPF2e<TParent extends TokenDocumentPF2e | null = TokenDocumentPF2e
...itemTypes.weapon.filter((w) => w.system.usage.canBeAmmo),
];
const offensiveCategories = R.keys.strict(CONFIG.PF2E.weaponCategories);
const syntheticWeapons = R.uniqueBy(R.compact(synthetics.strikes.map((s) => s(unarmedRunes))), (w) => w.slug);
const syntheticWeapons = R.uniqueBy(
synthetics.strikes.map((s) => s(unarmedRunes)).filter(R.isTruthy),
(w) => w.slug,
);

// Exclude handwraps as a strike
const weapons = R.compact(
[
itemTypes.weapon.filter((w) => w.slug !== handwrapsSlug),
syntheticWeapons,
basicUnarmed ?? [],
// Generate a shield attacks from the character's shields
this.itemTypes.shield
.filter((s) => !s.isStowed && !s.isBroken && !s.isDestroyed)
.map((s) => s.generateWeapon()),
this.inventory.flatMap((i) =>
i.isEquipped ? i.subitems.filter((i): i is WeaponPF2e<this> => i.isOfType("weapon")) : [],
),
].flat(),
) as WeaponPF2e<this>[];
const weapons = [
itemTypes.weapon.filter((w) => w.slug !== handwrapsSlug),
syntheticWeapons,
basicUnarmed ?? [],
// Generate a shield attacks from the character's shields
this.itemTypes.shield
.filter((s) => !s.isStowed && !s.isBroken && !s.isDestroyed)
.map((s) => s.generateWeapon()),
this.inventory.flatMap((i) =>
i.isEquipped ? i.subitems.filter((i): i is WeaponPF2e<this> => i.isOfType("weapon")) : [],
),
]
.flat()
.filter(R.isTruthy) as WeaponPF2e<this>[];

// Sort alphabetically, force basic unarmed attack to end, move all held items to the beginning, and then move
// all readied strikes to beginning
Expand Down Expand Up @@ -1196,8 +1202,8 @@ class CharacterPF2e<TParent extends TokenDocumentPF2e | null = TokenDocumentPF2e
);
const weaponProficiencyOptions = new Set(weaponRollOptions.concat(equivalentCategories));

const syntheticRanks = R.compact(Object.values(proficiencies.attacks))
.filter((p) => !!p.definition?.test(weaponProficiencyOptions))
const syntheticRanks = Object.values(proficiencies.attacks)
.filter((p): p is MartialProficiency => !!p?.definition?.test(weaponProficiencyOptions))
.map((p) => p.rank);

const proficiencyRank = Math.max(categoryRank, groupRank, baseWeaponRank, ...syntheticRanks) as ZeroToFour;
Expand Down Expand Up @@ -1492,7 +1498,7 @@ class CharacterPF2e<TParent extends TokenDocumentPF2e | null = TokenDocumentPF2e
action.variants = ([0, 1, 2] as const).map((mapIncreases) => ({
get label(): string {
const penalty = createMAPenalty(initialMAPs, mapIncreases);
adjustModifiers(R.filter([penalty], R.isTruthy), initialRollOptions);
adjustModifiers([penalty].filter(R.isTruthy), initialRollOptions);

return penalty
? game.i18n.format("PF2E.MAPAbbreviationValueLabel", {
Expand Down Expand Up @@ -1538,10 +1544,7 @@ class CharacterPF2e<TParent extends TokenDocumentPF2e | null = TokenDocumentPF2e
const statistic = context.origin.statistic ?? action;
const maps = calculateMAPs(context.origin.item, { domains: context.domains, options: context.options });
const maPenalty = createMAPenalty(maps, mapIncreases);
const allModifiers = R.filter(
[maPenalty, params.modifiers, context.origin.modifiers].flat(),
R.isTruthy,
);
const allModifiers = [maPenalty, params.modifiers, context.origin.modifiers].flat().filter(R.isTruthy);
const check = checkModifiers[mapIncreases](statistic, allModifiers);

// Check whether target is out of maximum range; abort early if so
Expand Down
18 changes: 10 additions & 8 deletions src/module/actor/character/elemental-blast.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { ModifierPF2e, StatisticModifier } from "@actor/modifiers.ts";
import { DamageContext } from "@actor/roll-context/damage.ts";
import type { AbilityItemPF2e } from "@item";
import { ActionTrait } from "@item/ability/types.ts";
import { EffectTrait } from "@item/abstract-effect/types.ts";
import { RangeData } from "@item/types.ts";
import { WeaponTrait } from "@item/weapon/types.ts";
import {
Expand Down Expand Up @@ -42,7 +43,6 @@ import type {
StringField,
} from "types/foundry/common/data/fields.d.ts";
import type { CharacterPF2e } from "./document.ts";
import { EffectTrait } from "@item/abstract-effect/types.ts";

class ElementalBlast {
actor: CharacterPF2e;
Expand Down Expand Up @@ -209,7 +209,7 @@ class ElementalBlast {

return blasts.map((blast) => {
const damageTypes: BlastConfigDamageType[] = R.unique(
R.compact([blast.damageTypes, this.infusion?.damageTypes].flat()),
[blast.damageTypes, this.infusion?.damageTypes].flat().filter(R.isTruthy),
)
.map((dt) => ({
value: dt,
Expand Down Expand Up @@ -285,9 +285,9 @@ class ElementalBlast {
const baseTraits = this.item?.system.traits.value ?? [];
const infusionTraits = melee ? this.infusion?.traits.melee : this.infusion?.traits.ranged;
return R.unique(
R.compact([baseTraits, infusionTraits, config?.element, damageType].flat()).filter(
(t): t is ActionTrait => t in CONFIG.PF2E.actionTraits,
),
[baseTraits, infusionTraits, config?.element, damageType]
.flat()
.filter((t): t is ActionTrait => !!t && t in CONFIG.PF2E.actionTraits),
).sort();
})();

Expand Down Expand Up @@ -403,7 +403,7 @@ class ElementalBlast {
outcome,
checkContext: params.checkContext,
options: new Set(
R.compact([
[
`action:${actionSlug}`,
`action:cost:${actionCost}`,
`self:action:slug:${actionSlug}`,
Expand All @@ -414,7 +414,7 @@ class ElementalBlast {
`item:damage:type:${params.damageType}`,
damageCategory ? `item:damage:category:${damageCategory}` : null,
...item.traits,
]),
].filter(R.isTruthy),
),
}).resolve();
if (!context.origin) return null;
Expand All @@ -441,7 +441,9 @@ class ElementalBlast {
}),
test: context.options,
});
const extraModifiers = R.compact([...damageSynthetics.modifiers, this.#strengthModToDamage(item, domains)]);
const extraModifiers = [...damageSynthetics.modifiers, this.#strengthModToDamage(item, domains)].filter(
R.isTruthy,
);
const modifiers = new StatisticModifier("", extraModifiers).modifiers;
const formulaData: DamageFormulaData = {
dice: damageSynthetics.dice,
Expand Down
2 changes: 1 addition & 1 deletion src/module/actor/character/feats.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ class CharacterFeats<TActor extends CharacterPF2e> extends Collection<FeatGroup<
id: "skill",
label: "PF2E.FeatSkillHeader",
supported: ["skill"],
slots: R.compact([backgroundSkillFeats, classFeatSlots?.skill].flat()),
slots: [backgroundSkillFeats, classFeatSlots?.skill].flat().filter(R.isTruthy),
});

this.createGroup({
Expand Down
2 changes: 1 addition & 1 deletion src/module/actor/character/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ class PCAttackTraitHelpers extends AttackTraitHelpers {
const { actor } = item;
if (!actor) throw ErrorPF2e("The weapon must be embedded");

const traitsAndTags = R.compact([item.system.traits.value, item.system.traits.otherTags].flat());
const traitsAndTags = [item.system.traits.value, item.system.traits.otherTags].flat().filter(R.isTruthy);
const synthetics = actor.synthetics.modifierAdjustments;

const pcSpecificModifiers = traitsAndTags.flatMap((trait) => {
Expand Down
4 changes: 2 additions & 2 deletions src/module/actor/character/sheet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ class CharacterSheetPF2e<TActor extends CharacterPF2e> extends CreatureSheetPF2e
// Attacks and defenses
// Prune untrained martial proficiencies
for (const section of ["attacks", "defenses"] as const) {
for (const key of R.keys.strict(sheetData.data.proficiencies[section])) {
for (const key of Object.keys(sheetData.data.proficiencies[section])) {
const proficiency = sheetData.data.proficiencies[section][key];
if (proficiency?.rank === 0 && !proficiency.custom) {
delete sheetData.data.proficiencies[section][key];
Expand Down Expand Up @@ -256,7 +256,7 @@ class CharacterSheetPF2e<TActor extends CharacterPF2e> extends CreatureSheetPF2e
// Spellcasting
const collectionGroups: Record<SpellcastingTabSlug, SpellcastingSheetData[]> = fu.mergeObject(
{ "known-spells": [], rituals: [], activations: [] },
R.groupBy.strict(await this.prepareSpellcasting(), (a) => {
R.groupBy(await this.prepareSpellcasting(), (a) => {
if (a.category === "items") return "activations";
if (a.category === "ritual") return "rituals";
return "known-spells";
Expand Down
4 changes: 2 additions & 2 deletions src/module/actor/creature/document.ts
Original file line number Diff line number Diff line change
Expand Up @@ -387,7 +387,7 @@ abstract class CreaturePF2e<

// Set labels for attributes
if (this.system.abilities) {
for (const [shortForm, data] of R.toPairs.strict(this.system.abilities)) {
for (const [shortForm, data] of R.entries.strict(this.system.abilities)) {
data.label = CONFIG.PF2E.abilities[shortForm];
data.shortLabel = `PF2E.AbilityId.${shortForm}`;
}
Expand Down Expand Up @@ -777,7 +777,7 @@ abstract class CreaturePF2e<
const sourceAlignmentTraits = this._source.system.traits?.value.filter(
(t) => ["good", "evil", "lawful", "chaotic"].includes(t) && !(t in CONFIG.PF2E.creatureTraits),
);
traitChanges.value = R.unique(R.compact([traitChanges.value, sourceAlignmentTraits].flat()).sort());
traitChanges.value = R.unique([traitChanges.value, sourceAlignmentTraits].flat()).filter(R.isTruthy).sort();
}

return super._preUpdate(changed, options, user);
Expand Down
2 changes: 1 addition & 1 deletion src/module/actor/familiar/document.ts
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,7 @@ class FamiliarPF2e<TParent extends TokenDocumentPF2e | null = TokenDocumentPF2e
})
: null;

const statistic = new ArmorStatistic(this, { modifiers: R.compact([masterModifier]) });
const statistic = new ArmorStatistic(this, { modifiers: [masterModifier].filter(R.isTruthy) });
this.armorClass = statistic.dc;
system.attributes.ac = fu.mergeObject(statistic.getTraceData(), { attribute: statistic.attribute ?? "dex" });

Expand Down
Loading

0 comments on commit 8c8f91e

Please sign in to comment.