how to make a peanut butter sandwich in typescript

Here's how you can create a function in TypeScript to make a peanut butter sandwich:

index.ts
function makePeanutButterSandwich(bread: number, peanutButter: string, jelly: string = ""): string {
  let sandwich: string[] = [];

  // check if we have bread
  if (bread < 2) {
    return "Not enough bread to make a sandwich";
  }

  // add bread
  sandwich.push("bread");

  // add peanut butter
  for (let i = 0; i < bread; i++) {
    sandwich.push(peanutButter);
  }

  // add jelly, if available
  if (jelly !== "") {
    sandwich.push(jelly);
  }

  // add bread
  sandwich.push("bread");

  return sandwich.join(" and ");
}

// example usage
console.log(makePeanutButterSandwich(2, "peanut butter"));
// expected output: "bread and peanut butter and peanut butter and bread"

console.log(makePeanutButterSandwich(1, "peanut butter, "jelly"));
// expected output: "Not enough bread to make a sandwich"
810 chars
34 lines

This function takes in a number of bread slices, a string of peanut butter, and an optional string of jelly. It then validates if there is enough bread to make the sandwich and constructs an array of the sandwich ingredients. Finally, it joins the sandwich array into a readable string and returns it.

gistlibby LogSnag