Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add micro-blog exercise #118

Merged
merged 1 commit into from
Jul 16, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions config.json
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,14 @@
"prerequisites": [],
"difficulty": 1
},
{
"slug": "micro-blog",
"name": "Micro Blog",
"uuid": "45dc52f5-2e84-4a52-8272-bb4b1e36b43b",
"practices": [],
"prerequisites": [],
"difficulty": 2
},
{
"slug": "collatz-conjecture",
"name": "Collatz Conjecture",
Expand Down
5 changes: 5 additions & 0 deletions exercises/practice/micro-blog/.docs/instructions.append.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
## Reserved Memory

The buffer for the UTF-8 input string uses bytes 64-319 of linear memory.

The input string can be modified in place if desired.
37 changes: 37 additions & 0 deletions exercises/practice/micro-blog/.docs/instructions.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
# Instructions

You have identified a gap in the social media market for very very short posts.
Now that Twitter allows 280 character posts, people wanting quick social media updates aren't being served.
You decide to create your own social media network.

To make your product noteworthy, you make it extreme and only allow posts of 5 or less characters.
Any posts of more than 5 characters should be truncated to 5.

To allow your users to express themselves fully, you allow Emoji and other Unicode.

The task is to truncate input strings to 5 characters.

## Text Encodings

Text stored digitally has to be converted to a series of bytes.
There are 3 ways to map characters to bytes in common use.

- **ASCII** can encode English language characters.
All characters are precisely 1 byte long.
- **UTF-8** is a Unicode text encoding.
Characters take between 1 and 4 bytes.
- **UTF-16** is a Unicode text encoding.
Characters are either 2 or 4 bytes long.

UTF-8 and UTF-16 are both Unicode encodings which means they're capable of representing a massive range of characters including:

- Text in most of the world's languages and scripts
- Historic text
- Emoji

UTF-8 and UTF-16 are both variable length encodings, which means that different characters take up different amounts of space.

Consider the letter 'a' and the emoji '😛'.
In UTF-16 the letter takes 2 bytes but the emoji takes 4 bytes.

The trick to this exercise is to use APIs designed around Unicode characters (codepoints) instead of Unicode codeunits.
18 changes: 18 additions & 0 deletions exercises/practice/micro-blog/.eslintrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
{
"root": true,
"extends": "@exercism/eslint-config-javascript",
"env": {
"jest": true
},
"overrides": [
{
"files": [
"*.spec.js"
],
"excludedFiles": [
"custom.spec.js"
],
"extends": "@exercism/eslint-config-javascript/maintainers"
}
]
}
26 changes: 26 additions & 0 deletions exercises/practice/micro-blog/.meta/config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
{
"authors": [
"keiravillekode"
],
"files": {
"solution": [
"micro-blog.wat"
],
"test": [
"micro-blog.spec.js"
],
"example": [
".meta/proof.ci.wat"
],
"invalidator": [
"package.json"
]
},
"blurb": "Given an input string, truncate it to 5 characters.",
"custom": {
"version.tests.compatibility": "jest-27",
"flag.tests.task-per-describe": false,
"flag.tests.may-run-long": false,
"flag.tests.includes-optional": false
}
}
82 changes: 82 additions & 0 deletions exercises/practice/micro-blog/.meta/proof.ci.wat
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
(module
(memory (export "mem") 1)

;;
;; Truncate UTF-8 input string to 5 characters
;;
;; @param {i32} offset - The offset of the input string in linear memory
;; @param {i32} length - The length of the input string in linear memory
;;
;; @returns {(i32,i32)} - The offset and length of the truncated string in linear memory
;;
(func (export "truncate") (param $offset i32) (param $length i32) (result i32 i32)

(local $index i32)
(local $stop i32)
(local $remaining i32)
(local $byte i32)
(local $step i32)

(local.set $index (local.get $offset))
(local.set $stop
(i32.add
(local.get $offset)
(local.get $length)
)
)
(local.set $remaining (i32.const 5))

(loop
(if (i32.or (i32.eqz (local.get $remaining))
(i32.eq (local.get $index) (local.get $stop)))
(then (return (local.get $offset)
(i32.sub (local.get $index) (local.get $offset)))
)
)

(local.set
$remaining
(i32.sub
(local.get $remaining)
(i32.const 1)
)
)

(local.set $byte (i32.load8_u (local.get $index)))

(if (i32.eq (i32.const 0xf0) (i32.and (i32.const 0xf0) (local.get $byte)))
(then
(local.set $step (i32.const 4))
)
(else
(if (i32.eq (i32.const 0xe0) (i32.and (i32.const 0xe0) (local.get $byte)))
(then
(local.set $step (i32.const 3))
)
(else
(if (i32.eq (i32.const 0xc0) (i32.and (i32.const 0xc0) (local.get $byte)))
(then
(local.set $step (i32.const 2))
)
(else
(local.set $step (i32.const 1))
)
)
)
)
)
)

(local.set
$index
(i32.add
(local.get $index)
(local.get $step)
)
)

(br 0)
)
(unreachable)
)
)
46 changes: 46 additions & 0 deletions exercises/practice/micro-blog/.meta/tests.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
# This is an auto-generated file.
#
# Regenerating this file via `configlet sync` will:
# - Recreate every `description` key/value pair
# - Recreate every `reimplements` key/value pair, where they exist in problem-specifications
# - Remove any `include = true` key/value pair (an omitted `include` key implies inclusion)
# - Preserve any other key/value pair
#
# As user-added comments (using the # character) will be removed when this file
# is regenerated, comments can be added via a `comment` key.

[b927b57f-7c98-42fd-8f33-fae091dc1efc]
description = "English language short"

[a3fcdc5b-0ed4-4f49-80f5-b1a293eac2a0]
description = "English language long"

[01910864-8e15-4007-9c7c-ac956c686e60]
description = "German language short (broth)"

[f263e488-aefb-478f-a671-b6ba99722543]
description = "German language long (bear carpet → beards)"

[0916e8f1-41d7-4402-a110-b08aa000342c]
description = "Bulgarian language short (good)"

[bed6b89c-03df-4154-98e6-a61a74f61b7d]
description = "Greek language short (health)"

[485a6a70-2edb-424d-b999-5529dbc8e002]
description = "Maths short"

[8b4b7b51-8f48-4fbe-964e-6e4e6438be28]
description = "Maths long"

[71f4a192-0566-4402-a512-fe12878be523]
description = "English and emoji short"

[6f0f71f3-9806-4759-a844-fa182f7bc203]
description = "Emoji short"

[ce71fb92-5214-46d0-a7f8-d5ba56b4cc6e]
description = "Emoji long"

[5dee98d2-d56e-468a-a1f2-121c3f7c5a0b]
description = "Royal Flush?"
1 change: 1 addition & 0 deletions exercises/practice/micro-blog/.npmrc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
audit=false
21 changes: 21 additions & 0 deletions exercises/practice/micro-blog/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2021 Exercism

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
4 changes: 4 additions & 0 deletions exercises/practice/micro-blog/babel.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export default {
presets: ["@exercism/babel-preset-javascript"],
plugins: [],
};
126 changes: 126 additions & 0 deletions exercises/practice/micro-blog/micro-blog.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
import { compileWat, WasmRunner } from "@exercism/wasm-lib";

let wasmModule;
let currentInstance;

beforeAll(async () => {
try {
const watPath = new URL("./micro-blog.wat", import.meta.url);
const { buffer } = await compileWat(watPath);
wasmModule = await WebAssembly.compile(buffer);
} catch (err) {
console.log(`Error compiling *.wat: \n${err}`);
process.exit(1);
}
});

function truncate(input) {
const inputBufferOffset = 64;
const inputBufferCapacity = 256;

const inputLengthEncoded = new TextEncoder().encode(input).length;
if (inputLengthEncoded > inputBufferCapacity) {
throw new Error(
`String is too large for buffer of size ${inputBufferCapacity} bytes`
);
}

currentInstance.set_mem_as_utf8(inputBufferOffset, inputLengthEncoded, input);

// Pass offset and length to WebAssembly function
const [outputOffset, outputLength] = currentInstance.exports.truncate(
inputBufferOffset,
inputLengthEncoded
);

// Decode JS string from returned offset and length
return currentInstance.get_mem_as_utf8(outputOffset, outputLength);
}

describe("Truncate", () => {
beforeEach(async () => {
currentInstance = null;
if (!wasmModule) {
return Promise.reject();
}
try {
currentInstance = await new WasmRunner(wasmModule);
return Promise.resolve();
} catch (err) {
console.log(`Error instantiating WebAssembly module: ${err}`);
return Promise.reject();
}
});

test("English language short", () => {
const expected = "Hi";
const actual = truncate("Hi");
expect(actual).toEqual(expected);
});

xtest("English language long", () => {
const expected = "Hello";
const actual = truncate("Hello there");
expect(actual).toEqual(expected);
});

xtest("German language short (broth)", () => {
const expected = "brühe";
const actual = truncate("brühe");
expect(actual).toEqual(expected);
});

xtest("German language long (bear carpet → beards)", () => {
const expected = "Bärte";
const actual = truncate("Bärteppich");
expect(actual).toEqual(expected);
});

xtest("Bulgarian language short (good)", () => {
const expected = "Добър";
const actual = truncate("Добър");
expect(actual).toEqual(expected);
});

xtest("Greek language short (health)", () => {
const expected = "υγειά";
const actual = truncate("υγειά");
expect(actual).toEqual(expected);
});

xtest("Maths short", () => {
const expected = "a=πr²";
const actual = truncate("a=πr²");
expect(actual).toEqual(expected);
});

xtest("Maths long", () => {
const expected = "∅⊊ℕ⊊ℤ";
const actual = truncate("∅⊊ℕ⊊ℤ⊊ℚ⊊ℝ⊊ℂ");
expect(actual).toEqual(expected);
});

xtest("English and emoji short", () => {
const expected = "Fly 🛫";
const actual = truncate("Fly 🛫");
expect(actual).toEqual(expected);
});

xtest("Emoji short", () => {
const expected = "💇";
const actual = truncate("💇");
expect(actual).toEqual(expected);
});

xtest("Emoji long", () => {
const expected = "❄🌡🤧🤒🏥";
const actual = truncate("❄🌡🤧🤒🏥🕰😀");
expect(actual).toEqual(expected);
});

xtest("Royal Flush?", () => {
const expected = "🃎🂸🃅🃋🃍";
const actual = truncate("🃎🂸🃅🃋🃍🃁🃊");
expect(actual).toEqual(expected);
});
});
Loading
Loading