index.js
/**
 * Respond with HTML document worker
 * @param {Request} request
 */
Respond with HTML document worker
@param {Request} request
Respond with HTML document worker @param { Request } request
async function handleRequest(request) {
  let cookie = request.headers.get('Cookie'); 
  let variant_url = '';
  if(cookie) {
    variant_url = getCookie(cookie, 'variant');
  }
  else {
    let selected_variant = Math.round(Math.random()); 
    let res = await fetch('https://cfw-takehome.developers.workers.dev/api/variants');
    let variant_obj = await res.json();
    variant_url = variant_obj.variants[selected_variant];
  }
  let result = await fetch(variant_url);
  let custom_page = new HTMLRewriter()
    .on('title, h1#title, p#description, a#url', new ElementHandler())
    .transform(result);
  const reply = await custom_page.text();
  return new Response(reply, {
    headers: { 'content-type': 'text/html', 'Set-Cookie': [`variant=${variant_url}`] },
  })
}
async function handleRequest ( request ) { let cookie = request . headers . get ( 'Cookie' ) ; let variant_url = '' ; if ( cookie ) { variant_url = getCookie ( cookie , 'variant' ) ; } else { let selected_variant = Math . round ( Math . random ( ) ) ; let res = await fetch ( 'https://cfw-takehome.developers.workers.dev/api/variants' ) ; let variant_obj = await res . json ( ) ; variant_url = variant_obj . variants [ selected_variant ] ; } let result = await fetch ( variant_url ) ; let custom_page = new HTMLRewriter ( ) . on ( 'title, h1#title, p#description, a#url' , new ElementHandler ( ) ) . transform ( result ) ; const reply = await custom_page . text ( ) ; return new Response ( reply , { headers : { 'content-type' : 'text/html' , 'Set-Cookie' : [ ` ${ variant_url } ` ] } , } ) }
Respond with HTML document worker
 @param {Request} request
Respond with HTML document worker @param { Request } request
// read the cookie from the headers. //if the cookie read is not null (follow up request) //read the variant url // select a random variant from 0 or 1 with uniform probability // console.log(variant_obj.variants[0]);