Skip to content

Instantly share code, notes, and snippets.

@dorsev
Last active March 28, 2020 06:42
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dorsev/387800acee8d1b8e6af29c86101fedb8 to your computer and use it in GitHub Desktop.
Save dorsev/387800acee8d1b8e6af29c86101fedb8 to your computer and use it in GitHub Desktop.
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