Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Sentiment Analysis example - without metrics
let senService: SentimentAnalysisService = new SentimentAnalysisService();
while (true) {
let tweetInformation = kafkaConsumer.consume()
let deserializedTweet: { msg: string } = deSerialize(tweetInformation)
let sentimentResult = senService.calculateSentiment(deserializedTweet.msg)
let seriarliedSentimentResult = serialize(sentimentResult)
sentimentStore.store(sentimentResult);
kafkaProducer.produce(seriarliedSentimentResult, 'sentiment_topic', 0);
}
enum SentimentStatus { Happy, Sad, Netural }
interface SentimentResult {
sentiment: SentimentStatus
confidence: number
}
interface SentimentAnalysis {
calculateSentiment(str: String): SentimentResult
}
interface KafkaConsumer {
consume(): string
}
interface KafkaProducer {
produce(msg: string, topic: string, partition: number): boolean
}
interface SentimentStore {
store(sentimentResult: SentimentResult): boolean
}
class SentimentAnalysisService implements SentimentAnalysis {
calculateSentiment(str: String): SentimentResult {
if (str.indexOf(":)") !== -1) {
return { sentiment: SentimentStatus.Happy, confidence: 1 }
} else if (str.indexOf(":(") !== -1) {
return { sentiment: SentimentStatus.Sad, confidence: 1 }
} else return { sentiment: SentimentStatus.Netural, confidence: 1 }
}
}
let kafkaProducer: KafkaProducer = {
produce(msg: string, topic: string, partition: number): boolean {
console.info(`producing ${msg} to ${topic} in ${partition}`);
return true;
}
}
let sentimentStore: SentimentStore = {
store(sentimentResult: SentimentResult): boolean {
console.info(`storing ${JSON.stringify(sentimentResult)} to db`);
return true;
}
}
var count: number = 1
let kafkaConsumer: KafkaConsumer = {
consume(): string {
if (count % 2 == 0) {
count++;
return `{"msg": "I'm sad ${count} :("}`
} else {
count++;
return `{"msg":"I'm happy ${count} :)"}`;
}
}
}
function deSerialize(str: string): any {
return JSON.parse(str);
}
function serialize(str: any): string {
return JSON.stringify(str)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.