Try   HackMD

Day 1

/*
The Yeti is on the way home to family, but the lights along the path are all
broken due to coding bugs. To fix them, a series of JavaScript challenges need
to be solved. The first light won't turn on until two ingredients are correctly
combined for the Elixir of Eternal Snow, ensuring both are properly capitalized
and joined with a dash.
*/

function brewPotion(ingredient1, ingredient2) {
    // Ensure both ingredients are provided
    if (!ingredient1 || !ingredient2) {
        throw new Error("Both ingredients are required.");
    }
    
    console.log("ingredient1", ingredient1);
    console.log("ingredient2", ingredient2);

    // Combine the ingredients with a dash and capitalize them correctly
    return 
        ingredient1.charAt(0).toUpperCase() + ingredient1.slice(1).toLowerCase() 
        + "-" 
        + ingredient2.charAt(0).toUpperCase() + ingredient2.slice(1).toLowerCase();
}

潛在問題

  • paramaters 可能不是 string
  • string 可能為空
  • string 可能含空白,若字首為空白則可能出錯

Answer

function brewPotion(ingredient1, ingredient2) {
    if ( typeof ingredient1 !== 'string' || typeof ingredient2 !== 'string') {
        throw new Error('Both ingredients must be string')
    }
    ingredient1 = ingredient1.trim();
    ingredient2 = ingredient2.trim();

    if (!ingredient1 || !ingredient2) {
        throw new Error("Both ingredients are required.");
    }
    
    console.log("ingredient1", ingredient1);
    console.log("ingredient2", ingredient2);

    return ingredient1.charAt(0).toUpperCase() + ingredient1.slice(1).toLowerCase() 
        + "-" 
        + ingredient2.charAt(0).toUpperCase() + ingredient2.slice(1).toLowerCase();
}

Day 2

/*
A fork in the road presents two paths - one leads home and the other leads to
a cliff. The light post is switched on, but no light is being emitted. A
sneaky bug in the code must be keeping the light from turning on properly. The
Yeti needs help solving the puzzle to avoid tumbling down the mountain.
*/

async function turnOnLights(lights) {
  const results = [];

  // Process each light in sequence
  for (const i = 0; i < lights.length; i++) {
    const currentLight = lights[i];

    // Skip if light is already on
    if (currentLight.isOn === true) continue;

    // Check if this light depends on other lights
    if (currentLight.dependsOn) {
      const dependencies = lights.filter((l) =>
        currentLight.dependsOn.includes(l.id),
      );

      // Verify all dependent lights are on
      const canTurnOn = dependencies.every((d) => d.isOn === true);

      if (!canTurnOn) continue;
    }

    // Turn on the light
    currentLight.isOn = true;

    // Add to results
    results.push("Light " + currentLight.id + " turned on");
  }

  return results;
}