Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Auto Save

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                  <input type="text" id="searchInput" placeholder="Enter your search query" />
  <button class="search-btn">Search</button>
  <div id="searchResults"></div>
              
            
!

CSS

              
                
              
            
!

JS

              
                // Sample data
let documents = [
  "August Host is a tech company based in Taunggyi, Myanmar, uses advanced technology to help clients achieve their software and hardware solutions.",
  "August Host is located at No 13/13, Myat Lay Street, Taunggyi; Myanmar.",
  "August Host Dev Team use Git, Trello, React, Javascript, Typescript, GraphQL, Laravel, Nextjs, Wordpress, Vue, Cockpit CMS, Headless CMS, Serverless, SSG, SSR.",
  "August Host was founded in 2018 by tech enthusiasts Ronald Aug and Kyaw Swar Aye, August Host emerged as the first web agency in Taunggyi, Myanmar. Ronald, with a background in tech and a passion for remote work culture, decided to establish the agency in his hometown, where he met Kyaw Swar Aye, a budding programmer eager to learn app development. Together, they envisioned filling the gap in the market by becoming pioneers in web development in the region.",
  "Success Story: While August Host is still on its journey to success, the agency has made significant strides in the industry. Despite facing challenges such as the political instability in Myanmar, the team remains dedicated to their vision of delivering top-quality digital solutions to clients across South East Asia.",
  "Vision: August Host aspires to become a renowned web agency not only in Myanmar but also in the wider South East Asia region. By consistently providing innovative and exceptional services, the agency aims to establish itself as a leader in the industry, setting new standards for digital excellence.",
  "The mission of August Host is to help clients transform their tasks from paper to digital, enhancing efficiency and speeding up daily operations. By offering high-quality digital services from Taunggyi to clients across South East Asia, the agency aims to make a positive impact on businesses seeking to thrive in the digital age.",
  "August Host has had the privilege of working with esteemed clients such as Plan International, Myanmar Private Equity and Venture Capital Association (MPEVCA), and others. One notable project includes the development of the Yangon Evacuation Map for Plan International, providing vital safety information for residents in Myanmar.",
  "The talented team at August Host includes Ronald Aug, Kyaw Swar Aye, Poe Eain, and Thura, each bringing a unique set of skills and expertise to the table. From full stack development to app programming and design, the team collaborates to deliver tailored digital solutions to meet client needs.",
  "Challenges: Despite facing challenges in the form of political instability and other obstacles, August Host remains committed to pushing boundaries and overcoming hurdles to achieve success. The agency continues to strive for excellence in the face of adversity, demonstrating resilience and determination in their pursuit of digital innovation.",
  "August Host offers a range of services including web development, app programming, digital marketing, SEO, and tech consulting. Using modern tools and technologies such as PHP, JS, Typescript, and Serverless, the agency creates custom websites and applications for clients, while also providing consultation on advertising, SEO, and domain email creation."
];

// Transform data
documents = documents.map((d, i) => {
  return { id: i + 1, content: d };
});

const searchBtn = document.querySelector('.search-btn');

searchBtn.addEventListener('click', () => {
  const queryInput = document.getElementById('searchInput');
  const query = queryInput.value.toLowerCase();
  const results = performSearch(query);

  // Display the search results
  const searchResults = document.getElementById('searchResults');
  searchResults.innerHTML = '';
  results.forEach((result) => {
    const doc = documents.find((d) => d.id === result.id);
    const resultElement = document.createElement('div');
    resultElement.textContent = `${doc.content} (Similarity: ${result.similarity.toFixed(2)})`;
    searchResults.appendChild(resultElement);
  });
});

function performSearch(query) {
  // Preprocess the documents
  const docTokensArray = documents.map((doc) => tokenize(doc.content.toLowerCase()));
  
  console.log(docTokensArray);
  
  // Calculate TF-IDF vectors for documents
  const tfidfVectors = docTokensArray.map((tokens) => calculateTfIdf(tokens, docTokensArray));
  
  // Tokenize the query and calculate its TF-IDF vector
  const queryTokens = tokenize(query);
  console.log(queryTokens);
  const queryTfIdf = calculateTfIdf(queryTokens, docTokensArray);
  
  // Calculate the cosine similarity between the query and each document
  const results = tfidfVectors.map((tfidfVector, index) => {
    const cosineSimilarity = calculateCosineSimilarity(queryTfIdf, tfidfVector);
    return { id: documents[index].id, similarity: cosineSimilarity };
  });

  // Sort the results by similarity in descending order
  results.sort((a, b) => b.similarity - a.similarity);

  return results;
}

function tokenize(text) {
  return text.split(/\W+/).filter(token => token.length > 0);
}

function calculateTfIdf(tokens, docTokensArray) {
  const tf = {};
  const df = {};
  const idf = {};

  tokens.forEach((token) => {
    tf[token] = (tf[token] || 0) + 1;
  });

  docTokensArray.forEach((docTokens) => {
    const uniqueTokens = new Set(docTokens);
    uniqueTokens.forEach((token) => {
      df[token] = (df[token] || 0) + 1;
    });
  });

  Object.keys(tf).forEach((token) => {
    idf[token] = Math.log(docTokensArray.length / (df[token] || 1));
  });

  const tfidf = {};
  Object.keys(tf).forEach((token) => {
    tfidf[token] = tf[token] * idf[token];
  });

  return tfidf;
}

function calculateCosineSimilarity(vectorA, vectorB) {
  const dotProduct = Object.keys(vectorA).reduce((sum, key) => sum + (vectorA[key] * (vectorB[key] || 0)), 0);
  const magnitudeA = Math.sqrt(Object.values(vectorA).reduce((sum, value) => sum + value ** 2, 0));
  const magnitudeB = Math.sqrt(Object.values(vectorB).reduce((sum, value) => sum + value ** 2, 0));
  return dotProduct / (magnitudeA * magnitudeB);
}

              
            
!
999px

Console