Back to Freecodecamp

Challenge 197: Blood Type Compatibility

curriculum/challenges/english/blocks/daily-coding-challenges-javascript/698a1a73ade5ac0e19180fa0.md

latest2.3 KB
Original Source

--description--

Given a donor blood type and a recipient blood type, determine whether the donor can give blood to the recipient.

Each blood type consists of:

  • A letter: "A", "B", "AB", or "O"
  • And an Rh factor: "+" or "-"

Blood types will be one of the valid letters followed by an Rh factor. For example, "AB+" and "O-" are valid blood types.

Letter Rules:

  • "O" can donate to other letter type.
  • "A" can donate to "A" and "AB".
  • "B" can donate to "B" and "AB".
  • "AB" can donate only to "AB".

Rh Rules:

  • Negative ("-") can donate to both "-" and "+".
  • Positive ("+") can donate only to "+".

Both letter and Rh rule must pass for a donor to be able to donate to the recipient.

--hints--

canDonate("B+", "B+") should return true.

js
assert.isTrue(canDonate("B+", "B+"));

canDonate("O-", "AB-") should return true.

js
assert.isTrue(canDonate("O-", "AB-"));

canDonate("O+", "A-") should return false.

js
assert.isFalse(canDonate("O+", "A-"));

canDonate("A+", "AB+") should return true.

js
assert.isTrue(canDonate("A+", "AB+"));

canDonate("A-", "B-") should return false.

js
assert.isFalse(canDonate("A-", "B-"));

canDonate("B-", "AB+") should return true.

js
assert.isTrue(canDonate("B-", "AB+"));

canDonate("B-", "A+") should return false.

js
assert.isFalse(canDonate("B-", "A+"));

canDonate("O-", "O+") should return true.

js
assert.isTrue(canDonate("O-", "O+"));

canDonate("O+", "O-") should return false.

js
assert.isFalse(canDonate("O+", "O-"));

canDonate("AB+", "AB-") should return false.

js
assert.isFalse(canDonate("AB+", "AB-"));

--seed--

--seed-contents--

js
function canDonate(donor, recipient) {

  return donor;
}

--solutions--

js
function canDonate(donor, recipient) {
  const donorType = donor.slice(0, -1);
  const donorRh = donor.slice(-1);

  const recipientType = recipient.slice(0, -1);
  const recipientRh = recipient.slice(-1);

  const aboCompatibility = {
    "O": ["A", "B", "AB", "O"],
    "A": ["A", "AB"],
    "B": ["B", "AB"],
    "AB": ["AB"]
  };

  const aboMatch = aboCompatibility[donorType].includes(recipientType);
  const rhMatch =
    donorRh === "-" || (donorRh === "+" && recipientRh === "+");

  return aboMatch && rhMatch;
}