JavaScript: Determinism
Functions in any programming language have fundamental properties. They help us understand how a function will behave in different situations, how to test it, and where to use it. One such property is determinism.
A deterministic function always returns the same result for the same input data. For example, a function that counts the number of characters can be called deterministic:
import { length } from 'hexlet-basics/string';
length('hexlet'); // 6
length('hexlet'); // 6
length('wow'); // 3
length('wow'); // 3No matter how many times we call this function with the argument 'hexlet', it will always return 6.
Non-deterministic functions
The opposite type is non-deterministic functions. They can return different results for the same input data or in its absence (functions without parameters). A good example is a function that returns a random number:
Math.random(); // 0.09856613113197676
Math.random(); // 0.8839904367241888This function has no arguments, but the result is different every time. If even one call out of a million produces a different result, the function is considered non-deterministic.
Deterministic: Non-deterministic:
length('abc') → always 3 Math.random() → 0.42
length('abc') → always 3 Math.random() → 0.91
length('abc') → always 3 Math.random() → 0.07Why this matters
Determinism affects how we work with functions:
- deterministic functions are easy to test and predict;
- they are easier to optimize and reuse;
- non-deterministic functions are harder to verify because the result changes.
That is why, where possible, it is better to strive to make a function deterministic.
Instructions
Generate a random integer from 0 to 10 (inclusive) and print it to the screen.
Use Math.random() (returns a number from 0 to 1) and Math.round() (rounds to an integer).
Tips
If you've reached a deadlock it's time to ask your question in the «Discussions». How ask a question correctly:
- Be sure to attach the test output, without it it's almost impossible to figure out what went wrong, even if you show your code. It's complicated for developers to execute code in their heads, but having a mistake before their eyes most probably will be helpful.
Tests are designed so that they test the solution in different ways and against different data. Often the solution works with one kind of input data but doesn't work with others. Check the «Tests» tab to figure this out, you can find hints at the error output.
It's fine. 🙆 One task in programming can be solved in many different ways. If your code passed all tests, it complies with the task conditions.
In some rare cases, the solution may be adjusted to the tests, but this can be seen immediately.
It's hard to make educational materials that will suit everyone. We do our best but there is always something to improve. If you see a material that is not clear to you, describe the problem in “Discussions”. It will be great if you'll write unclear points in the question form. Usually, we need a few days for corrections.
By the way, you can participate in courses improvement. There is a link below to the lessons course code which you can edit right in your browser.
Создавать обучающие материалы, понятные для всех без исключения, довольно сложно. Мы очень стараемся, но всегда есть что улучшать. Если вы встретили материал, который вам непонятен, опишите проблему в обратной связи нашего сообщества
Your exercise will be checked with these tests:
// @ts-check
import { expect, test, vi } from 'vitest';
test('hello world', async () => {
const consoleLogSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
await import('./index.js');
const firstArg = consoleLogSpy.mock.calls.join('\n');
expect(firstArg).not.toEqual('');
const value = Number(firstArg);
expect(Number.isInteger(value)).toEqual(true);
expect(value).toBeGreaterThanOrEqual(0);
expect(value).toBeLessThanOrEqual(10);
});Teacher's solution will be available in:
20:00
