Sentiment analysis is usually a task that requires a specialised dataset and machine-learning techniques to implement properly. However, I thought it might be a nice exercise to try and implement sentiment analysis with TypeScript without training models.
// Define a type for the sentiment result type Sentiment = 'positive' | 'neutral' | 'negative'; // Class to perform sentiment analysis on a given text class SentimentAnalysis { // Arrays of positive and negative words to use in the analysis private positiveWords = ["love", "like", "great", "good", "happy", "awesome"]; private negativeWords = ["hate", "dislike", "bad", "angry", "sad", "terrible"]; // Method to perform sentiment analysis on a given text public getSentiment(text: string): { sentiment: Sentiment, positiveWords: number, negativeWords: number, neutralWords: number } { // Convert the text to lowercase to make the analysis case-insensitive const lowerText = text.toLowerCase(); // Sum up the number of times each positive word appears in the text let positiveScore = this.positiveWords.reduce((acc, word) => { // Use a regular expression to match the word in the text return acc + (lowerText.match(new RegExp(word, 'g')) || []).length; }, 0); // Sum up the number of times each negative word appears in the text let negativeScore = this.negativeWords.reduce((acc, word) => { // Use a regular expression to match the word in the text return acc + (lowerText.match(new RegExp(word, 'g')) || []).length; }, 0); // Calculate the number of neutral words by subtracting the positive and negative words from the total number of words let neutralScore = lowerText.split(' ').length - positiveScore - negativeScore; // Compare the number of positive and negative words and return the sentiment result if (positiveScore > negativeScore) { return { sentiment: "positive", positiveWords: positiveScore, negativeWords: negativeScore, neutralWords: neutralScore }; } else if (positiveScore < negativeScore) { return { sentiment: "negative", positiveWords: positiveScore, negativeWords: negativeScore, neutralWords: neutralScore }; } else { return { sentiment: "neutral", positiveWords: positiveScore, negativeWords: negativeScore, neutralWords: neutralScore }; } } } // Create an instance of the SentimentAnalysis class const sentimentAnalysis = new SentimentAnalysis(); // Analyze some sample text const result = sentimentAnalysis.getSentiment("I love this code and think it is great!"); // Log the result console.log(result); This code uses a class called SentimentAnalysis to perform sentiment analysis on a given text. The class has two arrays of positive and negative words and a method called getSentiment that performs the analysis.
The Fetch API is a modern and efficient way to retrieve resources from a server. It is an interface that provides a unified way to fetch resources from different sources. Fetch makes sending HTTP requests, including GET and POST, easy and handles responses asynchronously.
However, handling errors properly is important when working with the Fetch API. Errors can occur for various reasons, such as a network error, a server-side error, or an invalid URL. Failing to handle these errors can result in unexpected behaviour and break your application.
I tend to get excited about virtual reality and have wanted to see it succeed for over a decade. While VR has undoubtedly grown, it’s not mainstream due to the barrier to entry. Most notably, requiring beefy PC setups or locked down (like the original PSVR headset). Adding to my growing collection of VR headsets, I preordered the PSVR 2 headset for the PlayStation 5.
There has been work done on untethered VR headsets, failed beginnings with Samsung creating phone VR headsets before Meta struck gold with the Meta Quest. Not only does it support using it by itself, but it can also be connected to a computer. Then you have the heavy, expensive hitters like the HTC Vive Pro 2 for powerful computer VR experiences.
Harry Potter fans have waited for an open-world Harry Potter game for almost two decades, and it’s crazy to think that we may have finally got what we have been asking for. After a lengthy wait and fear of delays, it’s finally here.
So, the question is: does Hogwarts Legacy live up to the expectations, or do we have another No Man’s Sky and Cyberpunk 2077 situation on our hands?
I have never understood why FizzBuzz was deemed a means of screening developers. The idea is for multiples of 3; you print Fizz. For multiples of 5, you print Buzz, and for multiples of 3 and 5 (15), you print FizzBuzz.
While this kind of prescreening question might have worked 15 years ago when information wasn’t as accessible as it is now (smartphones, smartwatches. etc.), it seems strange that some companies still ask developers how to write FizzBuzz.
ChatGPT is an AI-powered conversational API by Open AI that generates a lot of hype and fear amongst consumers, professionals and experts alike. Depending on who you talk to, ChatGPT will either revolutionise how we work, or it’s coming for our jobs and will taint academia.
You might have seen some news stories, including the impressive feats of ChatGPT passing prestigious law and business exams. And while these stories are understandably concerning, AI is based on learning and is no different from people reading books and learning materials available online to do the same thing.
Have you ever stopped to think about the impact social media has on your peace of mind? It was a realisation that came too late towards the end of 2022. The constant arguing, negativity, and drama on platforms like Facebook and LinkedIn took a toll on my mental health and well-being. I realised I needed to step back and break free from the negative echo chamber.
You might not realise it, but even seemingly harmless platforms like LinkedIn can have a negative impact on your life. What started as a professional networking platform has fallen prey to the negativity that plagues other social media platforms like Facebook. The constant barrage of conflicts and drama was too much for me to handle.
Well, it’s 2023, and many experts are predicting a recession on the horizon. And while no one knows how bad it will be or if many countries will avoid recession, one thing is sure: companies that can weather the storm will be the ones that can adapt quickly and efficiently.
Despite this pending threat of economic meltdown, many companies persist with anti-WFH policies, offering ultimatums to employees: return to the office or quit.
It’s 2023, and we still have no simple way to insert Gutenberg blocks into WordPress using wp_insert_post. You’re out of luck if you want to pull content from an API and insert it dynamically with ease. There are methods like parse_blocks and render_blocks but they still require a lot of messing around to work with.
The way Gutenberg blocks work is strange. They’re not stored as an array or structured data in the database. They are stored in the HTML as HTML comments.
I recently worked with GitHub Actions, where I generated a JSON file and then needed to add it to the repository. I parsed some Markdown files and then dynamically created a manifest JSON file of them, committing it into the repo every time a push was made.
I hit a permissions roadblock I embarrassingly spent over an hour solving, and I hope you don’t make the same mistake.
name: Build Blog JSON on: push: paths: - 'blog-posts/\*\*/\*.md' jobs: build: runs-on: ubuntu-latest steps: - name: Checkout repository uses: actions/checkout@v3 - name: Get list of Markdown files run: | cd blog-posts files=($(ls \*.md)) json\_array=() for file in "${files[@]}" do date\_string=$(grep -E '^date: ' "$file" | cut -d' ' -f2) # Use the date command to extract the year, month, and date year=$(date -d "$date\_string" +%Y) month=$(date -d "$date\_string" +%m) day=$(date -d "$date\_string" +%d) json\_array+=($(echo "{\\"file\\":\\"$file\\",\\"date\\":\\"$date\_string\\",\\"year\\":\\"$year\\",\\"month\\":\\"$month\\",\\"day\\":\\"$day\\"}")) done echo "[$(IFS=,; echo "${json\_array[\*]}" | jq -s -c 'sort\_by(.date)')]" > ../static/blog.json - name: Remove trailing comma run: | sed -i '$ s/,$//' static/blog.json - name: Commit changes run: | git config --global user.email "no-reply@github.com" git config --global user.name "GitHub Actions" git add static/blog.json git commit -m "Update blog.json" git remote set-url origin https://x-access-token:${{ secrets.GITHUB\_TOKEN }}@github.com/${{ github.repository }} git push env: GITHUB\_TOKEN: ${{ secrets.GITHUB\_TOKEN }} Now, the important part of my action is the Commit changes action. You need to supply an email and name for the committer. In this instance, I just made up something generic. The first important line is setting the origin URL. We are referencing some variables GitHub creates for us automatically. Notably, GITHUB_TOKEN and repository.