Skip to content

Commit 887d319

Browse files
committed
fix: StringModel
write the logic for unique_characters and character_frequency_map properties
1 parent cbbb42a commit 887d319

File tree

2 files changed

+20
-6
lines changed

2 files changed

+20
-6
lines changed

models/string.js

Lines changed: 19 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -14,31 +14,45 @@ const StringSchema = new mongoose.Schema({
1414
properties: {
1515
length: Number,
1616
is_palindrome: Boolean,
17-
// unique_characters: Number,
17+
unique_characters: Number,
1818
word_count: Number,
19-
sha256_hash: String, // TODO
20-
// character_frequency_map: Object,
19+
sha256_hash: String,
20+
character_frequency_map: Object,
2121
},
2222
created_at: {
2323
type: Date,
2424
default: Date.now,
2525
},
2626
});
2727

28-
StringSchema.pre("validate", async function () {
28+
StringSchema.pre("validate", function () {
2929
this._id = crypto.createHash("sha256").update(this.value).digest("hex");
3030
});
3131

3232
StringSchema.pre("save", async function () {
33+
const counts = this.characterFrequencyMap();
34+
const unique_characters = Object.keys(counts).length;
35+
3336
this.properties = {
3437
length: this.value.length,
3538
is_palindrome: this.value === this.value.split("").reverse().join(""),
39+
unique_characters,
3640
word_count: this.value.split(" ").length,
3741
sha256_hash: this._id,
42+
character_frequency_map: counts,
3843
};
3944
});
4045

41-
StringSchema.methods.characterFrequencyMap = function async() {};
46+
StringSchema.methods.characterFrequencyMap = function () {
47+
const counts = {};
48+
const chars = this.value.match(/[a-z]/g);
49+
50+
for (const char of chars) {
51+
counts[char] = (counts[char] || 0) + 1;
52+
}
53+
54+
return counts;
55+
};
4256

4357
StringSchema.set("toJSON", {
4458
transform: (_, ret) => {

swagger.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
"title": "String Analyzer API",
66
"description": "A RESTful API service that analyzes strings and stores their computed properties"
77
},
8-
"host": "node-string-analysis-api-production.up.railway.app/",
8+
"host": "node-string-analysis-api-production.up.railway.app",
99
"basePath": "/",
1010
"tags": [
1111
{

0 commit comments

Comments
 (0)