Compare commits

..

19 Commits

Author SHA1 Message Date
Michael Frank d1c9c98366
Merge pull request #218 from trekitch/jest-solutions 2022-01-27 10:07:16 +13:00
Trevon Kitchen d091aef25d
Update calculator/calculator.js
accepted

Co-authored-by: Michael Frank <mfra109@gmail.com>
2022-01-26 16:04:46 -05:00
trekitch db4255dc92 changed right name this time 2022-01-26 15:04:37 -05:00
trekitch 10199f35a9 change to alternate solutions name 2022-01-26 15:03:53 -05:00
trekitch 894ae2d4ce added alternate solution to multiply using Exponentiation operator 2022-01-26 14:15:16 -05:00
Kevin Mulhern fda681965e
Merge branch 'chore/switch-to-jest' into jest-solutions 2021-05-18 00:45:34 +01:00
Kevin Mulhern a1c56276ea Merge branch 'chore/switch-to-jest' into jest-solutions 2021-05-18 00:42:57 +01:00
Michael Frank 085fd89ec8 added new lines at end of file 2021-05-12 21:38:10 +12:00
Michael Frank 06e90f66c8 pulled eslint files from jester-tester and updated exercise numbers 2021-05-12 21:37:19 +12:00
Michael Frank 8546794b47 Remove lint script and add .DS_Store to .gitignore 2021-05-11 14:34:12 +12:00
Michael Frank ac4d2a94e5 Grammar cleanups, trailing semicolon for function expressions 2021-05-10 20:08:31 +12:00
Michael Frank 276b60a3c3 .eslitrc.json: Added support for airbnb-base linting 2021-05-10 19:03:38 +12:00
Michael Frank 435c1d3779 package(-lock).json: Update to include version and repsitory data based on old solution branch 2021-05-10 16:22:10 +12:00
Michael Frank 9916e343a3 repeatString/README.md: Rewrite hints to refer to Jest "skipped" tests. 2021-05-10 16:20:47 +12:00
Michael Frank cced031981 helloWorld/README.md: Remove mention of Jasmine in favour of Jest 2021-05-10 16:19:53 +12:00
Michael Frank 2d6c505096 calculator/README.md: Removed references to Jasmine.
calculator.spec.js: Set all tests except the first to test.skip
2021-05-10 14:57:23 +12:00
Michael Frank a5a0284ac1 update var to const in function declarations 2021-05-10 00:06:18 +12:00
Michael Frank ce0b9fade1 Revert package-lock.json back to node lts version 2021-05-08 23:54:40 +12:00
Michael Frank 749a48adee Tweak matchers in removeFromArray, pull pigLatin solution from old branch 2021-04-30 22:12:52 +12:00
101 changed files with 11129 additions and 4379 deletions

View File

@ -1,20 +0,0 @@
version: 2.1
orbs:
node: circleci/node@5.1.0
jobs:
test-solutions:
executor: node/default
steps:
- checkout
- node/install-packages:
pkg-manager: npm
- run:
command: npm run test solution
name: Run tests in **/solution/*.spec.js
workflows:
test-solutions:
jobs:
- test-solutions

View File

@ -1,54 +0,0 @@
---
name: Bug Report
about: Create a report to help us improve something that is not working correctly
title: "Bug - :"
labels: "Status: Needs Review, Type: Bug"
assignees: ""
---
<!-- Thank you for taking the time to submit a bug report to The Odin Project. In order to get issues closed in a reasonable amount of time, you must include a baseline of information about the bug in question. Please read this template in its entirety before filling it out to ensure that it is filled out correctly. -->
Complete the following REQUIRED checkboxes:
- [ ] I have thoroughly read and understand [The Odin Project Contributing Guide](https://github.com/TheOdinProject/.github/blob/main/CONTRIBUTING.md)
- [ ] The title of this issue follows the `Bug - location of bug: brief description of bug` format, e.g. `Bug - Exercises: File type incorrect for all test files`
The following checkbox is OPTIONAL:
<!-- Completing this checkbox does not guarantee you will be assigned this issue, but rather lets us know you are interested in working on it. -->
- [ ] I would like to be assigned this issue to work on it
<hr>
**1. Description of the Bug:**
<!-- A clear and concise description of what the bug is. Include any screenshots that may help show the bug in action. -->
**2. How To Reproduce:**
<!--
What steps one might need to take in order to reproduce this bug, e.g.:
1. Log in
2. Visit a lesson page
3. Click the complete button
4. The complete button does not update
-->
**3. Expected Behavior:**
<!--
A brief description of what you expected to happen, e.g.:
1. Log in
2. Visit a lesson page
3. Click the complete button
4. The complete button updates correctly
-->
**4. Desktop/Device:**
<!-- The more information you are able to provide, the better. -->
- Device: <!-- [e.g. iPhone6] -->
- OS: <!-- [e.g. iOS] -->
- Browser: <!-- [e.g. chrome, safari] -->
- Version: <!-- [e.g. 22] -->
**5. Additional Information:**
<!-- Any additional information about the bug. -->

View File

@ -1,38 +0,0 @@
---
name: Feature Request
about: Suggest a new feature or enhancement for this project
title: ""
labels: "Status: Needs Review"
assignees: ""
---
<!-- Thank you for taking the time to submit a new feature request to The Odin Project. In order to get issues closed in a reasonable amount of time, you must include a baseline of information about the feature/enhancement you are proposing. Please read this template in its entirety before filling it out to ensure that it is filled out correctly. -->
Complete the following REQUIRED checkboxes:
- [ ] I have thoroughly read and understand [The Odin Project Contributing Guide](https://github.com/TheOdinProject/.github/blob/main/CONTRIBUTING.md)
- [ ] The title of this issue follows the `location for request: brief description of request` format, e.g. `Exercises: Add exercise on XYZ`
The following checkbox is OPTIONAL:
<!-- Completing this checkbox does not guarantee you will be assigned this issue, but rather lets us know you are interested in working on it. -->
- [ ] I would like to be assigned this issue to work on it
<hr>
**1. Description of the Feature Request:**
<!--
A clear and concise description of what the feature or enhancement is, including how it would be useful/beneficial or what problem(s) it would solve.
-->
**2. Acceptance Criteria:**
<!--
A list of checkbox items that explain the requirements needed to be met to resolve this request, e.g.:
- [ ] A theme toggle is present on the dashboard
- [ ] Clicking the theme toggle changes between light and dark
- [ ] A user's theme choice persists after leaving the website
-->
**3. Additional Information:**
<!-- Any additional information about the feature request, such as a link to a Discord discussion, screenshots, etc. -->

View File

@ -1,32 +0,0 @@
<!-- Thank you for taking the time to contribute to The Odin Project. In order to get this pull request (PR) merged in a reasonable amount of time, you must complete this entire template. -->
## Because
<!-- Summarize the purpose or reasons for this PR, e.g. what problem it solves or what benefit it provides. -->
## This PR
<!-- A bullet point list of one or more items describing the specific changes. -->
## Issue
<!--
If this PR closes an open issue in this repo, replace the XXXXX below with the issue number, e.g. Closes #2013.
If this PR closes an open issue in another TOP repo, replace the #XXXXX with the URL of the issue, e.g. Closes https://github.com/TheOdinProject/curriculum/issues/XXXXX
If this PR does not close, but is related to another issue or PR, you can link it as above without the 'Closes' keyword, e.g. 'Related to #2013'.
-->
Closes #XXXXX
## Additional Information
<!-- Any other information about this PR, such as a link to a Discord discussion. -->
## Pull Request Requirements
<!-- Replace the whitespace between the square brackets with an 'x', e.g. [x]. After you create the PR, they will become checkboxes that you can click on. -->
- [ ] I have thoroughly read and understand [The Odin Project Contributing Guide](https://github.com/TheOdinProject/.github/blob/main/CONTRIBUTING.md)
- [ ] The title of this PR follows the `location of change: brief description of change` format, e.g. `01_helloWorld: Update test cases`
- [ ] The `Because` section summarizes the reason for this PR
- [ ] The `This PR` section has a bullet point list describing the changes in this PR
- [ ] If this PR addresses an open issue, it is linked in the `Issue` section
- [ ] If this PR includes any changes that affect the solution of an exercise, I've also updated the solution in the `/solutions` folder

View File

@ -1,7 +0,0 @@
const helloWorld = require('./helloWorld');
describe('Hello World', function() {
test('says "Hello, World!"', function() {
expect(helloWorld()).toEqual('Hello, World!');
});
});

View File

@ -1,5 +0,0 @@
const helloWorld = function () {
return "Hello, World!";
};
module.exports = helloWorld;

View File

@ -1,7 +0,0 @@
const helloWorld = require('./helloWorld-solution');
describe('Hello World', function () {
test('says "Hello, World!"', function () {
expect(helloWorld()).toEqual('Hello, World!');
});
});

View File

@ -1,6 +0,0 @@
const repeatString = function() {
};
// Do not edit below this line
module.exports = repeatString;

View File

@ -1,10 +0,0 @@
const repeatString = function (word, times) {
if (times < 0) return "ERROR";
let string = "";
for (let i = 0; i < times; i++) {
string += word;
}
return string;
};
module.exports = repeatString;

View File

@ -1,39 +0,0 @@
const repeatString = require('./repeatString-solution');
describe('repeatString', () => {
test('repeats the string', () => {
expect(repeatString('hey', 3)).toEqual('heyheyhey');
});
test('repeats the string many times', () => {
expect(repeatString('hey', 10)).toEqual('heyheyheyheyheyheyheyheyheyhey');
});
test('repeats the string 1 times', () => {
expect(repeatString('hey', 1)).toEqual('hey');
});
test('repeats the string 0 times', () => {
expect(repeatString('hey', 0)).toEqual('');
});
test('returns ERROR with negative numbers', () => {
expect(repeatString('hey', -1)).toEqual('ERROR');
});
test('repeats the string a random amount of times', function () {
/*The number is generated by using Math.random to get a value from between
0 to 1, when this is multiplied by 1000 and rounded down with Math.floor it
equals a number between 0 to 999 (this number will change everytime you run
the test).*/
// DO NOT use Math.floor(Math.random() * 1000) in your code,
// this test generates a random number, then passes it into your code with a function parameter.
// If this doesn't make sense, you should go read about functions here: https://www.theodinproject.com/paths/foundations/courses/foundations/lessons/fundamentals-part-3
const number = Math.floor(Math.random() * 1000);
/*The .match(/((hey))/g).length is a regex that will count the number of heys
in the result, which if your function works correctly will equal the number that
was randomaly generated. */
expect(repeatString('hey', number).match(/((hey))/g).length).toEqual(
number
);
});
test('works with blank strings', () => {
expect(repeatString('', 10)).toEqual('');
});
});

View File

@ -1,6 +0,0 @@
const reverseString = function() {
};
// Do not edit below this line
module.exports = reverseString;

View File

@ -1,5 +0,0 @@
const reverseString = function (string) {
return string.split("").reverse().join("");
};
module.exports = reverseString;

View File

@ -1,18 +0,0 @@
const reverseString = require('./reverseString-solution');
describe('reverseString', () => {
test('reverses single word', () => {
expect(reverseString('hello')).toEqual('olleh');
});
test('reverses multiple words', () => {
expect(reverseString('hello there')).toEqual('ereht olleh');
});
test('works with numbers and punctuation', () => {
expect(reverseString('123! abc!')).toEqual('!cba !321');
});
test('works with blank strings', () => {
expect(reverseString('')).toEqual('');
});
});

View File

@ -1,6 +0,0 @@
const removeFromArray = function() {
};
// Do not edit below this line
module.exports = removeFromArray;

View File

@ -1,25 +0,0 @@
const removeFromArray = require('./removeFromArray-solution');
describe('removeFromArray', () => {
test('removes a single value', () => {
expect(removeFromArray([1, 2, 3, 4], 3)).toEqual([1, 2, 4]);
});
test('removes multiple values', () => {
expect(removeFromArray([1, 2, 3, 4], 3, 2)).toEqual([1, 4]);
});
test('ignores non present values', () => {
expect(removeFromArray([1, 2, 3, 4], 7, 'tacos')).toEqual([1, 2, 3, 4]);
});
test('ignores non present values, but still works', () => {
expect(removeFromArray([1, 2, 3, 4], 7, 2)).toEqual([1, 3, 4]);
});
test('can remove all values', () => {
expect(removeFromArray([1, 2, 3, 4], 1, 2, 3, 4)).toEqual([]);
});
test('works with strings', () => {
expect(removeFromArray(['hey', 2, 3, 'ho'], 'hey', 3)).toEqual([2, 'ho']);
});
test('only removes same type', () => {
expect(removeFromArray([1, 2, 3], '1', 3)).toEqual([1, 2]);
});
});

View File

@ -1,21 +0,0 @@
const sumAll = function (min, max) {
if (!Number.isInteger(min) || !Number.isInteger(max)) return "ERROR";
if (min < 0 || max < 0) return "ERROR";
if (min > max) {
const temp = min;
min = max;
max = temp;
}
// An alternative way to swap the values of min and max like above is to use the array destructuring syntax.
// Here's an optional article on it: https://www.freecodecamp.org/news/array-destructuring-in-es6-30e398f21d10/
// if (min > max) [min, max] = [max, min];
let sum = 0;
for (let i = min; i <= max; i++) {
sum += i;
}
return sum;
};
module.exports = sumAll;

View File

@ -1,25 +0,0 @@
const sumAll = require('./sumAll-solution');
describe('sumAll', () => {
test('sums numbers within the range', () => {
expect(sumAll(1, 4)).toEqual(10);
});
test('works with large numbers', () => {
expect(sumAll(1, 4000)).toEqual(8002000);
});
test('works with larger number first', () => {
expect(sumAll(123, 1)).toEqual(7626);
});
test('returns ERROR with negative numbers', () => {
expect(sumAll(-10, 4)).toEqual('ERROR');
});
test('returns ERROR with non-integer parameters', () => {
expect(sumAll(2.5, 4)).toEqual('ERROR');
});
test('returns ERROR with non-number parameters', () => {
expect(sumAll(10, '90')).toEqual('ERROR');
});
test('returns ERROR with non-number parameters', () => {
expect(sumAll(10, [90, 1])).toEqual('ERROR');
});
});

View File

@ -1,6 +0,0 @@
const sumAll = function() {
};
// Do not edit below this line
module.exports = sumAll;

View File

@ -1,6 +0,0 @@
const leapYears = function() {
};
// Do not edit below this line
module.exports = leapYears;

View File

@ -1,5 +0,0 @@
const leapYears = function (year) {
return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
};
module.exports = leapYears;

View File

@ -1,22 +0,0 @@
const leapYears = require('./leapYears-solution');
describe('leapYears', () => {
test('works with non century years', () => {
expect(leapYears(1996)).toBe(true);
});
test('works with non century years', () => {
expect(leapYears(1997)).toBe(false);
});
test('works with ridiculously futuristic non century years', () => {
expect(leapYears(34992)).toBe(true);
});
test('works with century years', () => {
expect(leapYears(1900)).toBe(false);
});
test('works with century years', () => {
expect(leapYears(1600)).toBe(true);
});
test('works with century years', () => {
expect(leapYears(700)).toBe(false);
});
});

View File

@ -1,12 +0,0 @@
const convertToCelsius = function (fahrenheit) {
return Math.round((fahrenheit - 32) * (5 / 9) * 10) / 10;
};
const convertToFahrenheit = function (celsius) {
return Math.round(((celsius * 9) / 5 + 32) * 10) / 10;
};
module.exports = {
convertToCelsius,
convertToFahrenheit,
};

View File

@ -1,28 +0,0 @@
const {
convertToCelsius,
convertToFahrenheit,
} = require('./tempConversion-solution');
describe('convertToCelsius', () => {
test('works', () => {
expect(convertToCelsius(32)).toEqual(0);
});
test('rounds to 1 decimal', () => {
expect(convertToCelsius(100)).toEqual(37.8);
});
test('works with negatives', () => {
expect(convertToCelsius(-100)).toEqual(-73.3);
});
});
describe('convertToFahrenheit', () => {
test('works', () => {
expect(convertToFahrenheit(0)).toEqual(32);
});
test('rounds to 1 decimal', () => {
expect(convertToFahrenheit(73.2)).toEqual(163.8);
});
test('works with negatives', () => {
expect(convertToFahrenheit(-10)).toEqual(14);
});
});

View File

@ -1,11 +0,0 @@
const convertToCelsius = function() {
};
const convertToFahrenheit = function() {
};
// Do not edit below this line
module.exports = {
convertToCelsius,
convertToFahrenheit
};

View File

@ -1,25 +0,0 @@
const {convertToCelsius, convertToFahrenheit} = require('./tempConversion')
describe('convertToCelsius', () => {
test('works', () => {
expect(convertToCelsius(32)).toEqual(0);
});
test.skip('rounds to 1 decimal', () => {
expect(convertToCelsius(100)).toEqual(37.8);
});
test.skip('works with negatives', () => {
expect(convertToCelsius(-100)).toEqual(-73.3);
});
});
describe('convertToFahrenheit', () => {
test.skip('works', () => {
expect(convertToFahrenheit(0)).toEqual(32);
});
test.skip('rounds to 1 decimal', () => {
expect(convertToFahrenheit(73.2)).toEqual(163.8);
});
test.skip('works with negatives', () => {
expect(convertToFahrenheit(-10)).toEqual(14);
});
});

View File

@ -1,33 +0,0 @@
const add = function() {
};
const subtract = function() {
};
const sum = function() {
};
const multiply = function() {
};
const power = function() {
};
const factorial = function() {
};
// Do not edit below this line
module.exports = {
add,
subtract,
sum,
multiply,
power,
factorial
};

View File

@ -1,77 +0,0 @@
const calculator = require('./calculator');
describe('add', () => {
test('adds 0 and 0', () => {
expect(calculator.add(0, 0)).toBe(0);
});
test.skip('adds 2 and 2', () => {
expect(calculator.add(2, 2)).toBe(4);
});
test.skip('adds positive numbers', () => {
expect(calculator.add(2, 6)).toBe(8);
});
});
describe('subtract', () => {
test.skip('subtracts numbers', () => {
expect(calculator.subtract(10, 4)).toBe(6);
});
});
describe('sum', () => {
test.skip('computes the sum of an empty array', () => {
expect(calculator.sum([])).toBe(0);
});
test.skip('computes the sum of an array of one number', () => {
expect(calculator.sum([7])).toBe(7);
});
test.skip('computes the sum of an array of two numbers', () => {
expect(calculator.sum([7, 11])).toBe(18);
});
test.skip('computes the sum of an array of many numbers', () => {
expect(calculator.sum([1, 3, 5, 7, 9])).toBe(25);
});
});
describe('multiply', () => {
test.skip('multiplies two numbers', () => {
expect(calculator.multiply([2, 4])).toBe(8);
});
test.skip('multiplies several numbers', () => {
expect(calculator.multiply([2, 4, 6, 8, 10, 12, 14])).toBe(645120);
});
});
describe('power', () => {
test.skip('raises one number to the power of another number', () => {
expect(calculator.power(4, 3)).toBe(64); // 4 to third power is 64
});
});
describe('factorial', () => {
test.skip('computes the factorial of 0', () => {
expect(calculator.factorial(0)).toBe(1); // 0! = 1
});
test.skip('computes the factorial of 1', () => {
expect(calculator.factorial(1)).toBe(1);
});
test.skip('computes the factorial of 2', () => {
expect(calculator.factorial(2)).toBe(2);
});
test.skip('computes the factorial of 5', () => {
expect(calculator.factorial(5)).toBe(120);
});
test.skip('computes the factorial of 10', () => {
expect(calculator.factorial(10)).toBe(3628800);
});
});

View File

@ -1,46 +0,0 @@
const add = function (a, b) {
return a + b;
};
const subtract = function (a, b) {
return a - b;
};
const sum = function (array) {
return array.reduce((total, current) => total + current, 0);
};
const multiply = function (array) {
return array.reduce((product, current) => product * current)
};
const power = function (a, b) {
return Math.pow(a, b);
};
const factorial = function (n) {
if (n === 0) return 1;
let product = 1;
for (let i = n; i > 0; i--) {
product *= i;
}
return product;
};
// This is another implementation of Factorial that uses recursion
// THANKS to @ThirtyThreeB!
const recursiveFactorial = function (n) {
if (n === 0) {
return 1;
}
return n * recursiveFactorial(n - 1);
};
module.exports = {
add,
subtract,
sum,
multiply,
power,
factorial,
};

View File

@ -1,77 +0,0 @@
const calculator = require('./calculator-solution');
describe('add', () => {
test('adds 0 and 0', () => {
expect(calculator.add(0, 0)).toBe(0);
});
test('adds 2 and 2', () => {
expect(calculator.add(2, 2)).toBe(4);
});
test('adds positive numbers', () => {
expect(calculator.add(2, 6)).toBe(8);
});
});
describe('subtract', () => {
test('subtracts numbers', () => {
expect(calculator.subtract(10, 4)).toBe(6);
});
});
describe('sum', () => {
test('computes the sum of an empty array', () => {
expect(calculator.sum([])).toBe(0);
});
test('computes the sum of an array of one number', () => {
expect(calculator.sum([7])).toBe(7);
});
test('computes the sum of an array of two numbers', () => {
expect(calculator.sum([7, 11])).toBe(18);
});
test('computes the sum of an array of many numbers', () => {
expect(calculator.sum([1, 3, 5, 7, 9])).toBe(25);
});
});
describe('multiply', () => {
test('multiplies two numbers', () => {
expect(calculator.multiply([2, 4])).toBe(8);
});
test('multiplies several numbers', () => {
expect(calculator.multiply([2, 4, 6, 8, 10, 12, 14])).toBe(645120);
});
});
describe('power', () => {
test('raises one number to the power of another number', () => {
expect(calculator.power(4, 3)).toBe(64); // 4 to third power is 64
});
});
describe('factorial', () => {
test('computes the factorial of 0', () => {
expect(calculator.factorial(0)).toBe(1); // 0! = 1
});
test('computes the factorial of 1', () => {
expect(calculator.factorial(1)).toBe(1);
});
test('computes the factorial of 2', () => {
expect(calculator.factorial(2)).toBe(2);
});
test('computes the factorial of 5', () => {
expect(calculator.factorial(5)).toBe(120);
});
test('computes the factorial of 10', () => {
expect(calculator.factorial(10)).toBe(3628800);
});
});

View File

@ -1,6 +0,0 @@
const palindromes = function () {
};
// Do not edit below this line
module.exports = palindromes;

View File

@ -1,6 +0,0 @@
const palindromes = function (string) {
const processedString = string.toLowerCase().replace(/[^a-z0-9]/g, "");
return processedString.split("").reverse().join("") == processedString;
};
module.exports = palindromes;

View File

@ -1,30 +0,0 @@
const palindromes = require('./palindromes-solution');
describe('palindromes', () => {
test('works with single words', () => {
expect(palindromes('racecar')).toBe(true);
});
test('works with punctuation ', () => {
expect(palindromes('racecar!')).toBe(true);
});
test('works with upper-case letters ', () => {
expect(palindromes('Racecar!')).toBe(true);
});
test('works with multiple words', () => {
expect(palindromes('A car, a man, a maraca.')).toBe(true);
});
test('works with multiple words', () => {
expect(palindromes('Animal loots foliated detail of stool lamina.')).toBe(
true
);
});
test("doesn't just always return true", () => {
expect(palindromes('ZZZZ car, a man, a maraca.')).toBe(false);
});
test('works with numbers in a string', () => {
expect(palindromes('rac3e3car')).toBe(true);
});
test('works with unevenly spaced numbers in a string', () => {
expect(palindromes('r3ace3car')).toBe(false);
});
});

View File

@ -1,12 +0,0 @@
# Exercise 10 - Fibonacci
Create a function that returns a specific member of the Fibonacci sequence:
> A series of numbers in which each number ( Fibonacci number ) is the sum of the two preceding numbers.
> In this exercise, the Fibonacci sequence used is 1, 1, 2, 3, 5, 8, etc.
> To learn more about Fibonacci sequences, go to: https://en.wikipedia.org/wiki/Fibonacci_sequence
```javascript
fibonacci(4); // returns the 4th member of the series: 3 (1, 1, 2, 3)
fibonacci(6); // returns 8
```

View File

@ -1,6 +0,0 @@
const fibonacci = function() {
};
// Do not edit below this line
module.exports = fibonacci;

View File

@ -1,34 +0,0 @@
const fibonacci = function(countArg) {
// checks argument's type and makes sure we use
// a number throughout rest of function.
let count
if (typeof countArg !== 'number') {
count = parseInt(countArg)
} else {
count = countArg
}
if (count < 0) return "OOPS";
if (count == 0) return 0;
let firstPrev = 1;
let secondPrev = 0;
for (let i = 2; i <= count; i++) {
let current = firstPrev + secondPrev;
secondPrev = firstPrev;
firstPrev = current;
}
return firstPrev;
};
// Another way to do it is by using an iterative approach with an array containing two values, 0 and 1.
// const fib = [0, 1];
// for (let i = 2; i <= count; i++) {
// fib[i] = fib[i - 1] + fib[i - 2];
// }
// return fib[count];
module.exports = fibonacci;

View File

@ -1,37 +0,0 @@
const fibonacci = require('./fibonacci-solution')
describe('fibonacci', () => {
test('4th fibonacci number is 3', () => {
expect(fibonacci(4)).toBe(3);
});
test('6th fibonacci number is 8', () => {
expect(fibonacci(6)).toBe(8);
});
test('10th fibonacci number is 55', () => {
expect(fibonacci(10)).toBe(55);
});
test('15th fibonacci number is 610', () => {
expect(fibonacci(15)).toBe(610);
});
test('25th fibonacci number is 75025', () => {
expect(fibonacci(25)).toBe(75025);
});
test('0th fibonacci number is 0', () => {
expect(fibonacci(0)).toBe(0);
});
test('doesn\'t accept negatives', () => {
expect(fibonacci(-25)).toBe("OOPS");
});
test('DOES accept strings', () => {
expect(fibonacci("0")).toBe(0);
});
test('DOES accept strings', () => {
expect(fibonacci("1")).toBe(1);
});
test('DOES accept strings', () => {
expect(fibonacci("2")).toBe(1);
});
test('DOES accept strings', () => {
expect(fibonacci("8")).toBe(21);
});
});

View File

@ -1,6 +0,0 @@
const getTheTitles = function() {
};
// Do not edit below this line
module.exports = getTheTitles;

View File

@ -1,5 +0,0 @@
const getTheTitles = function (array) {
return array.map((book) => book.title);
};
module.exports = getTheTitles;

View File

@ -1,18 +0,0 @@
const getTheTitles = require('./getTheTitles-solution');
describe('getTheTitles', () => {
const books = [
{
title: 'Book',
author: 'Name',
},
{
title: 'Book2',
author: 'Name2',
},
];
test('gets titles', () => {
expect(getTheTitles(books)).toEqual(['Book', 'Book2']);
});
});

View File

@ -1,6 +0,0 @@
const findTheOldest = function() {
};
// Do not edit below this line
module.exports = findTheOldest;

View File

@ -1,19 +0,0 @@
const findTheOldest = function (array) {
return array.reduce((oldest, currentPerson) => {
const oldestAge = getAge(oldest.yearOfBirth, oldest.yearOfDeath);
const currentAge = getAge(
currentPerson.yearOfBirth,
currentPerson.yearOfDeath
);
return oldestAge < currentAge ? currentPerson : oldest;
});
};
const getAge = function (birth, death) {
if (!death) {
death = new Date().getFullYear();
}
return death - birth;
};
module.exports = findTheOldest;

View File

@ -1,62 +0,0 @@
const findTheOldest = require('./findTheOldest-solution');
describe('findTheOldest', () => {
test('finds the oldest person!', () => {
const people = [
{
name: 'Carly',
yearOfBirth: 1942,
yearOfDeath: 1970,
},
{
name: 'Ray',
yearOfBirth: 1962,
yearOfDeath: 2011,
},
{
name: 'Jane',
yearOfBirth: 1912,
yearOfDeath: 1941,
},
];
expect(findTheOldest(people).name).toBe('Ray');
});
test('finds the oldest person if someone is still living', () => {
const people = [
{
name: 'Carly',
yearOfBirth: 2018,
},
{
name: 'Ray',
yearOfBirth: 1962,
yearOfDeath: 2011,
},
{
name: 'Jane',
yearOfBirth: 1912,
yearOfDeath: 1941,
},
];
expect(findTheOldest(people).name).toBe('Ray');
});
test('finds the oldest person if the OLDEST is still living', () => {
const people = [
{
name: 'Carly',
yearOfBirth: 1066,
},
{
name: 'Ray',
yearOfBirth: 1962,
yearOfDeath: 2011,
},
{
name: 'Jane',
yearOfBirth: 1912,
yearOfDeath: 1941,
},
];
expect(findTheOldest(people).name).toBe('Carly');
});
});

21
LICENSE
View File

@ -1,21 +0,0 @@
MIT License
Copyright (c) 2023 The Odin Project
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.

View File

@ -1,38 +1,27 @@
# JavaScript Exercises
These are a series of JavaScript exercises intended to be used alongside the curriculum at 'The Odin Project'. They start simple and easy but get more complex and involved as you progress through them.
These JavaScript exercises are intended to complement the JavaScript content on The Odin Project (TOP). They should only be done when instructed during the course of the curriculum.
There will eventually be a suggested order of completion, but at this time since we are still in the process of creating more exercises the order is subject to change and has not yet been specified. However, there are a few exercises that make a good "starting point". Feel free to at least start with these:
**Note:** The `generator-exercise` file is not actually an exercise; it is a script that generates exercises. It was created to help efficiently write these exercises.
## Contributing
If you have a suggestion to improve an exercise, an idea for a new exercise, or notice an issue with an exercise, please feel free to open an issue after thoroughly reading our [contributing guide](https://github.com/TheOdinProject/.github/blob/main/CONTRIBUTING.md).
1. Hello World
2. Repeat String
3. Reverse String
## How To Use These Exercises
Before you start you should have a few things installed on your machine:
1. NPM. To check if you have NPM installed, type `npm --version` in your terminal. If you get back `Command 'npm' not found, but can be installed with:`, do NOT follow the instructions in the terminal to install with `apt-get`. (This causes permission issues.) Instead, install Node with NVM by following the instructions [here](https://github.com/TheOdinProject/curriculum/blob/master/foundations/installations/installing_node.md).
2. Jest. Jest is a testing framework for JavaScript. To install it, type `npm install --save-dev jest`. We use `--save-dev` here to specify this module is for development purposes only.
3. A copy of this repository. Copies of repositories on your machine are called clones. If you need help cloning, you can learn how [here](https://docs.github.com/en/github/creating-cloning-and-archiving-repositories/cloning-a-repository).
1. Fork and clone this repository. To learn how to fork a repository, see the GitHub documentation on how to [fork a repo](https://docs.github.com/en/get-started/quickstart/fork-a-repo).
- Copies of repositories on your machine are called clones. If you need help cloning to your local environment you can learn how from the GitHub documentation on [cloning a repository](https://docs.github.com/en/github/creating-cloning-and-archiving-repositories/cloning-a-repository-from-github/cloning-a-repository).
2. Before you start working on any exercises, you should first ensure you have the following installed:
- **NPM**. You should have installed NPM already in our [Installing Node.js](https://www.theodinproject.com/paths/foundations/courses/foundations/lessons/installing-node-js) lesson. Just in case you need to check, type `npm --version` in your terminal. If you get back `Command 'npm' not found, but can be installed with:`, **do not follow the instructions in the terminal** to install with `apt-get` as this causes permission issues. Instead, go back to the installation lesson and install Node with NVM by following the instructions there.
- **Jest**. After cloning this repository to your local machine and installing NPM, go into the newly created directory (`cd javascript-exercises`) and run `npm install`. This will install Jest and set up the testing platform based on our preconfigured settings. (Note: if you get warnings that packages are out of date or contain vulnerabilities, you can safely ignore them for these exercises.)
3. Each exercise includes the following:
- A markdown file with a description of the task, an empty (or mostly empty) JavaScript file, and a set of tests.
- A `solutions` directory that contains a solution and the same test file with all of the tests unskipped.
To complete an exercise, you'll need to go to the exercise directory with `cd exerciseName` in the terminal and run `npm test exerciseName.spec.js`. This should run the test file and show you the output. When you first run a test, it will fail. This is by design! You must open the exercise file and write the code needed to get the test to pass.
4. Some of the exercises have test conditions defined in their spec file as `test.skip` compared to `test`. This is purposeful. After you pass one `test`, you will change the next `test.skip` to `test` and test your code again. You'll do this until all conditions are satisfied. **All tests must pass at the same time**, and you should not have any `test.skip` instances by the time you finish an exercise.
5. Once you successfully finish an exercise, check the `solutions` directory within each exercise to compare it with yours.
- You should not be checking the solution for an exercise until you finish it!
- Keep in mind that TOP's solution is not the only solution. Generally as long as all of the tests pass, your solution should be fine.
6. Do not submit your solutions to this repo, as any PRs that do so will be closed without merging.
Each exercise includes 3 files: a markdown file with a description of the task, an empty (or mostly empty) JavaScript file, and a set of tests. To complete an exercise, you'll need to go to the exercise directory with `cd exerciseName` in the terminal and run `npm test exerciseName.spec.js`. This should run the test file and show you the output. When you first run a test, it will fail. This is by design! You must open the exercise file and write the code needed to get the test to pass. Some of the exercises have test conditions defined in their spec file that are defined as 'test.skip' compared to 'test'. This is purposeful. After you pass your first 'test', you will change the next 'test.skip' to an 'test' and test your code again. You'll do this until all conditions are satisfied.
**Note**: Due to the way Jest handles failed tests, it may return an exit code of 1 if any tests fail. NPM will interpret this as an error and you may see some `npm ERR!` messages after Jest runs. You can ignore these, or run your test with `npm test exerciseName.spec.js --silent` to supress the errors.
The first exercise, `helloWorld`, will walk you through the process in-depth.
## Debugging
## Solutions
To debug functions, you can run the tests in the Visual Studio Code debugger terminal. You can open this by clicking the "Run and Debug" icon on the left or pressing <kbd>Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>D</kbd>, then clicking JavaScript Debug Terminal. You will be able to set breakpoints as you would in the Chrome DevTools debugger. You can run `npm test exerciseName.spec.js` to then execute your code up until your breakpoint and step through your code as necessary. **NOTE**: To take advantage of the debugger, you **MUST** run the script in the debugger terminal, not the bash or zsh terminal.
Solutions for these exercises can be found in this repo on the 'solutions' branch.
## A quick note!
The exercise `generator-exercise` is not actually an exercise; it is a script that generates exercises. It was created to help efficiently write these exercises.

View File

@ -1,6 +0,0 @@
const caesar = function() {
};
// Do not edit below this line
module.exports = caesar;

View File

@ -1,23 +0,0 @@
const caesar = require('./caesar-solution');
test('works with single letters', () => {
expect(caesar('A', 1)).toBe('B');
});
test('works with words', () => {
expect(caesar('Aaa', 1)).toBe('Bbb');
});
test('works with phrases', () => {
expect(caesar('Hello, World!', 5)).toBe('Mjqqt, Btwqi!');
});
test('works with negative shift', () => {
expect(caesar('Mjqqt, Btwqi!', -5)).toBe('Hello, World!');
});
test('wraps', () => {
expect(caesar('Z', 1)).toBe('A');
});
test('works with large shift factors', () => {
expect(caesar('Hello, World!', 75)).toBe('Ebiil, Tloia!');
});
test('works with large negative shift factors', () => {
expect(caesar('Hello, World!', -29)).toBe('Ebiil, Tloia!');
});

View File

@ -1,6 +0,0 @@
function pigLatin(string) {
};
// Do not edit below this line
module.exports = pigLatin;

View File

@ -1,21 +0,0 @@
const pigLatin = function (string) {
return string
.split(" ")
.map((word) => {
const index = firstVowelIndex(word);
const beginning = word.slice(0, index);
const ending = word.slice(index);
return `${ending}${beginning}ay`;
})
.join(" ");
};
const firstVowelIndex = function (string) {
const vowels = string.match(/[aeiou]/g);
if (vowels[0] == "u" && string[string.indexOf(vowels[0]) - 1] == "q") {
return string.indexOf(vowels[1]);
}
return string.indexOf(vowels[0]);
};
module.exports = pigLatin;

View File

@ -1,56 +0,0 @@
const pigLatin = require('./pigLatin-solution');
// Topics
// * modules
// * strings
// Pig Latin
// Pig Latin is a made-up children's language that's intended to be confusing. test obeys a few simple rules (below) but when test's spoken quickly test's really difficult for non-children (and non-native speakers) to understand.
// Rule 1: If a word begins with a vowel sound, add an "ay" sound to the end of the word.
// Rule 2: If a word begins with a consonant sound, move test to the end of the word, and then add an "ay" sound to the end of the word.
// (There are a few more rules for edge cases, and there are regional variants too, but that should be enough to understand the tests.)
// See https://en.wikipedia.org/wiki/Pig_Latin for more details.
describe('translate', () => {
test('translates a word beginning with a vowel', () => {
expect(pigLatin('apple')).toBe('appleay');
});
test('translates a word beginning with a consonant', () => {
expect(pigLatin('banana')).toBe('ananabay');
});
test('translates a word beginning with two consonants', () => {
expect(pigLatin('cherry')).toBe('errychay');
});
test('translates two words', () => {
expect(pigLatin('eat pie')).toBe('eatay iepay');
});
test('translates a word beginning with three consonants', () => {
expect(pigLatin('three')).toBe('eethray');
});
test('counts "sch" as a single phoneme', () => {
expect(pigLatin('school')).toBe('oolschay');
});
test('counts "qu" as a single phoneme', () => {
expect(pigLatin('quiet')).toBe('ietquay');
});
test('counts "qu" as a consonant even when its preceded by a consonant', () => {
expect(pigLatin('square')).toBe('aresquay');
});
test('translates many words', () => {
expect(pigLatin('the quick brown fox')).toBe('ethay ickquay ownbray oxfay');
});
});

View File

@ -1,6 +0,0 @@
const snakeCase = function() {
};
// Do not edit below this line
module.exports = snakeCase;

View File

@ -1,26 +0,0 @@
const snakeCase = require('./snakeCase-solution');
describe('snakeCase', () => {
test('works with simple lowercased phrases', () => {
expect(snakeCase('hello world')).toEqual('hello_world');
});
test('works with Caps and punctuation', () => {
expect(snakeCase('Hello, World???')).toEqual('hello_world');
});
test('works with longer phrases', () => {
expect(snakeCase('This is the song that never ends....')).toEqual(
'this_is_the_song_that_never_ends'
);
});
test('works with camel case', () => {
expect(snakeCase('snakeCase')).toEqual('snake_case');
});
test('works with kebab case', () => {
expect(snakeCase('snake-case')).toEqual('snake_case');
});
test('works with WTF case', () => {
expect(snakeCase('SnAkE..CaSe..Is..AwEsOmE')).toEqual(
'snake_case_is_awesome'
);
});
});

BIN
caesar/.DS_Store vendored Normal file

Binary file not shown.

View File

@ -14,7 +14,7 @@ caesar('A', 1) // simply shifts the letter by 1: returns 'B'
the cipher should retain capitalization:
```javascript
caesar('Hey', 5) // returns 'Mjd'
caesar('Hey', 5) // returns 'Mjd;
```
should _not_ shift punctuation:

View File

@ -1,16 +1,16 @@
const caesar = function (string, shift) {
const caesar = function(string, shift) {
return string
.split("")
.map((char) => shiftChar(char, shift))
.map(char => shiftChar(char, shift))
.join("");
};
const codeSet = (code) => (code < 97 ? 65 : 97);
const codeSet = code => (code < 97 ? 65 : 97);
// this function is just a fancy way of doing % so that it works with negative numbers
// see this link for details:
// https://stackoverflow.com/questions/4467539/javascript-modulo-gives-a-negative-result-for-negative-numbers
const mod = (n, m) => ((n % m) + m) % m;
const mod = (n, m) => (n % m + m) % m;
const shiftChar = (char, shift) => {
const code = char.charCodeAt();

53
calculator/calculator.js Normal file
View File

@ -0,0 +1,53 @@
const add = function(a, b) {
return a + b;
};
const subtract = function(a, b) {
return a - b;
};
const sum = function(array) {
return array.reduce((total, current) => total + current, 0);
};
const multiply = function(array) {
return array.length
? array.reduce((accumulator, nextItem) => accumulator * nextItem)
: 0;
};
const power = function(a, b) {
return Math.pow(a, b);
};
//alternate solution using the Exponentiation operator
const altPower = function(a, b) {
return a ** b;
};
const factorial = function(n) {
if (n === 0) return 1;
let product = 1;
for (let i = n; i > 0; i--) {
product *= i;
}
return product;
};
// This is another implementation of Factorial that uses recursion
// THANKS to @ThirtyThreeB!
const recursiveFactorial = function(n) {
if (n === 0) {
return 1;
}
return n * recursiveFactorial (n-1);
};
module.exports = {
add,
subtract,
sum,
multiply,
power,
factorial
};

View File

@ -0,0 +1,77 @@
const calculator = require('./calculator');
describe('add', () => {
test('adds 0 and 0', () => {
expect(calculator.add(0,0)).toBe(0);
});
test.skip('adds 2 and 2', () => {
expect(calculator.add(2,2)).toBe(4);
});
test.skip('adds positive numbers', () => {
expect(calculator.add(2,6)).toBe(8);
});
});
describe('subtract', () => {
test.skip('subtracts numbers', () => {
expect(calculator.subtract(10,4)).toBe(6);
});
});
describe('sum', () => {
test.skip('computes the sum of an empty array', () => {
expect(calculator.sum([])).toBe(0);
});
test.skip('computes the sum of an array of one number', () => {
expect(calculator.sum([7])).toBe(7);
});
test.skip('computes the sum of an array of two numbers', () => {
expect(calculator.sum([7,11])).toBe(18);
});
test.skip('computes the sum of an array of many numbers', () => {
expect(calculator.sum([1,3,5,7,9])).toBe(25);
});
});
describe('multiply', () => {
test.skip('multiplies two numbers', () => {
expect(calculator.multiply([2,4])).toBe(8);
});
test.skip('multiplies several numbers', () => {
expect(calculator.multiply([2,4,6,8,10,12,14])).toBe(645120);
});
});
describe('power', () => {
test.skip('raises one number to the power of another number', () => {
expect(calculator.power(4,3)).toBe(64); // 4 to third power is 64
});
});
describe('factorial', () => {
test.skip('computes the factorial of 0', () => {
expect(calculator.factorial(0)).toBe(1); // 0! = 1
});
test.skip('computes the factorial of 1', () => {
expect(calculator.factorial(1)).toBe(1);
});
test.skip('computes the factorial of 2', () => {
expect(calculator.factorial(2)).toBe(2);
});
test.skip('computes the factorial of 5', () => {
expect(calculator.factorial(5)).toBe(120);
});
test.skip('computes the factorial of 10', () => {
expect(calculator.factorial(10)).toBe(3628800);
});
});

10
fibonacci/README.md Normal file
View File

@ -0,0 +1,10 @@
# Exercise 10 - Fibonacci
Create a function that returns a specific member of the Fibonacci sequence:
> A series of numbers in which each number ( Fibonacci number ) is the sum of the two preceding numbers. The simplest is the series 1, 1, 2, 3, 5, 8, etc.
```javascript
fibonacci(4) // returns the 4th member of the series: 3 (1, 1, 2, 3)
fibonacci(6) // returns 8
```

14
fibonacci/fibonacci.js Normal file
View File

@ -0,0 +1,14 @@
const fibonacci = function(count) {
if (count < 0) return "OOPS";
if (count === 0) return 0;
let a = 0;
let b = 1;
for (let i = 1; i < count; i++) {
const temp = b;
b = a + b;
a = temp;
}
return b;
};
module.exports = fibonacci;

View File

@ -16,15 +16,9 @@ describe('fibonacci', () => {
test.skip('25th fibonacci number is 75025', () => {
expect(fibonacci(25)).toBe(75025);
});
test.skip('0th fibonacci number is 0', () => {
expect(fibonacci(0)).toBe(0);
});
test.skip('doesn\'t accept negatives', () => {
expect(fibonacci(-25)).toBe("OOPS");
});
test.skip('DOES accept strings', () => {
expect(fibonacci("0")).toBe(0);
});
test.skip('DOES accept strings', () => {
expect(fibonacci("1")).toBe(1);
});

View File

@ -2,9 +2,7 @@
Given an array of objects representing people with a birth and death year, return the oldest person.
Now that you've reached the final exercise, you should be fairly comfortable getting the information you need from test case(s). Take a look at how the array of objects is constructed in this exercise's test cases to help you write your function.
## Hints
- You should return the whole person object, but the tests mostly just check to make sure the name is correct.
- This can be done with a couple of chained array methods, or by using `reduce`.
- this can be done with a couple of chained array methods, or by using `reduce`.
- One of the tests checks for people with no death-date.. use JavaScript's Date function to get their age as of today.

View File

@ -0,0 +1,16 @@
const findTheOldest = function(array) {
return array.reduce((oldest, currentPerson) => {
const oldestAge = getAge(oldest.yearOfBirth, oldest.yearOfDeath)
const currentAge = getAge(currentPerson.yearOfBirth, currentPerson.yearOfDeath)
return oldestAge < currentAge ? currentPerson : oldest
})
};
const getAge = function(birth, death) {
if (!death) {
death = new Date().getFullYear();
}
return death - birth;
};
module.exports = findTheOldest;

View File

@ -1,7 +1,7 @@
const findTheOldest = require('./findTheOldest')
describe('findTheOldest', () => {
test('finds the person with the greatest age!', () => {
test('finds the oldest person!', () => {
const people = [
{
name: "Carly",
@ -21,7 +21,7 @@ describe('findTheOldest', () => {
]
expect(findTheOldest(people).name).toBe('Ray');
});
test.skip('finds the person with the greatest age if someone is still living', () => {
test.skip('finds the oldest person if someone is still living', () => {
const people = [
{
name: "Carly",
@ -40,7 +40,7 @@ describe('findTheOldest', () => {
]
expect(findTheOldest(people).name).toBe('Ray');
});
test.skip('finds the person with the greatest age if the OLDEST is still living', () => {
test.skip('finds the oldest person if the OLDEST is still living', () => {
const people = [
{
name: "Carly",

File diff suppressed because it is too large Load Diff

View File

@ -19,7 +19,7 @@
"devDependencies": {
"yeoman-test": "^1.6.0",
"yeoman-assert": "^3.0.0",
"nsp": "^3.2.1",
"nsp": "^2.6.3",
"eslint": "^4.1.0",
"eslint-config-xo-space": "^0.16.0",
"jest": "^19.0.2",

View File

@ -0,0 +1,5 @@
const getTheTitles = function(array) {
return array.map(book => book.title)
};
module.exports = getTheTitles;

View File

@ -13,7 +13,7 @@ Let's look at the spec file first:
const helloWorld = require('./helloWorld');
describe('Hello World', function() {
test('says "Hello, World!"', function() {
test('says hello world', function() {
expect(helloWorld()).toEqual('Hello, World!');
});
});
@ -38,7 +38,7 @@ Go ahead and see if you can make the test pass by editing the return value of th
Just to make sure, in case you're confused at this point, the test is telling you that running the function `helloWorld` should return the phrase `Hello, World!`. Punctuation and capitalization definitely matter here, so double check that if the test still isn't passing.
This is what the final function should look like:
this is what the final function should look like:
```javascript
const helloWorld = function() {
return 'Hello, World!'

View File

@ -1,5 +1,5 @@
const helloWorld = function() {
return ''
return 'Hello, World!'
};
module.exports = helloWorld;

View File

@ -0,0 +1,5 @@
const helloWorld = require('./helloWorld');
test('says "Hello, World!"', function() {
expect(helloWorld()).toBe("Hello, World!");
});

5
leapYears/leapYears.js Normal file
View File

@ -0,0 +1,5 @@
const leapYears = function(year) {
return year % 4 === 0 && ( year % 100 !== 0 || year % 400 === 0)
};
module.exports = leapYears;

13083
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -14,21 +14,16 @@
},
"homepage": "https://github.com/TheOdinProject/javascript-exercises#readme",
"devDependencies": {
"eslint": "^8.47.0",
"eslint-config-airbnb-base": "^15.0.0",
"eslint-plugin-import": "^2.28.1",
"jest": "^29.6.4",
"jest-cli": "^29.6.4"
"eslint": "^7.26.0",
"eslint-config-airbnb-base": "^14.2.1",
"eslint-plugin-import": "^2.22.1",
"jest": "^26.6.3",
"jest-cli": "^26.6.3"
},
"scripts": {
"test": "jest"
},
"eslintConfig": {
"root": true
},
"jest": {
"testPathIgnorePatterns": [
"generator-exercise/"
]
}
}

View File

@ -0,0 +1,11 @@
const palindromes = function(string) {
processedString = string.toLowerCase().replace(/[^A-Za-z]/g, "");
return (
processedString
.split("")
.reverse()
.join("") == processedString
);
};
module.exports = palindromes;

View File

@ -17,12 +17,6 @@ describe('palindromes', () => {
expect(palindromes('Animal loots foliated detail of stool lamina.')).toBe(true);
});
test.skip('doesn\'t just always return true', () => {
expect(palindromes('ZZZZ car, a man, a maracaz.')).toBe(false);
});
test.skip('works with numbers in a string', () => {
expect(palindromes('rac3e3car')).toBe(true);
});
test.skip('works with unevenly spaced numbers in a string', () => {
expect(palindromes('r3ace3car')).toBe(false);
expect(palindromes('ZZZZ car, a man, a maraca.')).toBe(false);
});
});

21
pigLatin/pigLatin.js Normal file
View File

@ -0,0 +1,21 @@
const pigLatin = function(string) {
return string
.split(" ")
.map(word => {
const index = firstVowelIndex(word);
const beginning = word.slice(0, index);
const ending = word.slice(index);
return `${ending}${beginning}ay`;
})
.join(" ");
};
const firstVowelIndex = function(string) {
const vowels = string.match(/[aeiou]/g);
if (vowels[0] == "u" && string[string.indexOf(vowels[0]) - 1] == "q") {
return string.indexOf(vowels[1]);
}
return string.indexOf(vowels[0]);
};
module.exports = pigLatin;

View File

@ -1,7 +1,9 @@
// we have 2 solutions here, an easier one and a more advanced one.
// The easiest way to get an array of the rest of the arguments that are passed to a function
// is using the rest operator. If this is unfamiliar to you look it up!
const removeFromArray = function (array, ...args) {
// The easiest way to get an array of all of the arguments that are passed to a function
// is using the spread operator. If this is unfamiliar to you look it up!
const removeFromArray = function (...args) {
// the very first item in our list of arguments is the array, we pull it out with args[0]
const array = args[0];
// create a new empty array
const newArray = [];
// use forEach to go through the array
@ -20,7 +22,8 @@ const removeFromArray = function (array, ...args) {
// A simpler, but more advanced way to do it is to use the 'filter' function,
// which basically does what we did with the forEach above.
// var removeFromArray = function(array, ...args) {
// var removeFromArray = function(...args) {
// const array = args[0]
// return array.filter(val => !args.includes(val))
// }
//

View File

@ -6,24 +6,20 @@ Write a function that simply repeats the string a given number of times:
repeatString('hey', 3) // returns 'heyheyhey'
```
This function will take two arguments, `string` and `num`.
*Note:* The exercises after this one will not have arguments provided as this one does - you will need to provide them yourself from now on. So read each exercise's README carefully to see what kinds of arguments will be expected.
You will notice in this exercise that there are multiple tests (see in file `repeatString.spec.js`). Only the first test is currently enabled. So after making sure that this first one passes, enable the others one by one by deleting the `.skip` from the `test.skip()` function.
## Hints
- Take note of the above function call- how exactly is it being called?
- You're going to want to use a loop for this one.
- Create a variable to hold the string you're going to return, create a loop that repeats the given number of times and add the given string to the result on each loop.
- If running `npm test repeatString.spec.js` returns results similar to the below, make sure you have enabled the rest of the tests, as described in the instructions above.
- If running `npm test repeatString.spec.js` returns results similar to the below:
```
Test Suites: 1 passed, 1 total
Tests: 6 skipped, 1 passed, 7 total
```
- Make sure you have enabled the rest of the tests (see above).

View File

@ -0,0 +1,10 @@
const repeatString = function(word, times) {
if (times < 0) return 'ERROR'
let string = ''
for (let i = 0; i < times; i++) {
string += word
}
return string
};
module.exports = repeatString;

View File

@ -28,7 +28,7 @@ describe('repeatString', () => {
const number = Math.floor(Math.random() * 1000)
/*The .match(/((hey))/g).length is a regex that will count the number of heys
in the result, which if your function works correctly will equal the number that
was randomly generated. */
was randomaly generated. */
expect(repeatString('hey', number).match(/((hey))/g).length).toEqual(number);
});
test.skip('works with blank strings', () => {

View File

@ -6,8 +6,7 @@ Pretty simple, write a function called `reverseString` that returns its input, r
reverseString('hello there') // returns 'ereht olleh'
```
You will notice in this exercise that there are multiple tests (in the file `reverseString.spec.js`). Currently, only the first test is enabled. After ensuring that the first test passes, enable the remaining tests one by one by removing the `.skip` from the `test.skip()` function.
You will notice in this exercise that there are multiple tests, after making the first one pass, enable the others one by one by deleting the `.skip` in front the `test.skip()` function.
## Hints
Strings in JavaScript cannot be reversed directly so you're going to have to split it into something else first.. do the reversal and then join it back together into a string.

View File

@ -0,0 +1,5 @@
const reverseString = function(string) {
return string.split('').reverse().join('')
};
module.exports = reverseString;

View File

@ -1,4 +1,4 @@
const snakeCase = function (string) {
const snakeCase = function(string) {
// wtf case
string = string.replace(/\.\./g, " ");

16
sumAll/sumAll.js Normal file
View File

@ -0,0 +1,16 @@
const sumAll = function(min, max) {
if (!Number.isInteger(min) || !Number.isInteger(max)) return "ERROR";
if (min < 0 || max < 0) return "ERROR";
if (min > max) {
const temp = min;
min = max;
max = temp;
}
let sum = 0;
for (let i = min; i < max + 1; i++) {
sum += i;
}
return sum;
};
module.exports = sumAll;

View File

@ -2,12 +2,12 @@
Write two functions that convert temperatures from Fahrenheit to Celsius, and vice versa:
```
convertToCelsius(32) // fahrenheit to celsius, should return 0
ftoc(32) // fahrenheit to celsius, should return 0
convertToFahrenheit(0) // celsius to fahrenheit, should return 32
ctof(0) // celsius to fahrenheit, should return 32
```
Because we are human, we want the result temperature to be rounded to one decimal place: i.e., `convertToCelsius(100)` should return `37.8` and not `37.77777777777778`.
Because we are human, we want the result temperature to be rounded to one decimal place: i.e., `ftoc(100)` should return `37.8` and not `37.77777777777778`.
This exercise asks you to create more than one function so the `module.exports` section of the spec file looks a little different this time. Nothing to worry about, we're just packaging both functions into a single object to be exported.

View File

@ -0,0 +1,13 @@
const ftoc = function(f) {
return Math.round((f - 32) * (5/9) * 10) / 10
};
const ctof = function(c) {
return Math.round(((c * 9/5) + 32) * 10) / 10
};
module.exports = {
ftoc,
ctof
};

Some files were not shown because too many files have changed in this diff Show More