Skip to content

New Exercise: Promises #932

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

Merged
merged 15 commits into from
Apr 10, 2021
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
10 changes: 10 additions & 0 deletions config.json
Original file line number Diff line number Diff line change
Expand Up @@ -906,6 +906,16 @@
"strings"
]
},
{
"slug": "promises",
"name": "Promises",
"uuid": "ad21018c-e538-4ce5-a33a-949b4293df8c",
"core": false,
"practices": [],
"prerequisites": [],
"difficulty": 4,
"topics": ["promises", "error_handling", "higher_order_functions"]
},
{
"slug": "yacht",
"name": "Yacht",
Expand Down
11 changes: 11 additions & 0 deletions exercises/practice/promises/.docs/instructions.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# Instructions

Given the basic `Promise`, implement the following functions:

- `promisify`: takes a callback that is turned into a function that returns a `Promise`
- `all`: takes an array of promises and resolves when _all_ of them are resolved, or rejects when _one_ of them rejects.
- `allSettled`: takes an array of promises and resolves when _all_ of them either resolve or reject.
- `race`: takes an array of promises and resolves or rejects with the value of the _first_ promise that resolves or rejects.
- `any`: takes an array of promises and resolves when _one_ of them resolves, or rejects when _all_ of them reject.

Do not use built-in `Promise` functions other than creating a `Promise`, `then` and `catch`.
29 changes: 29 additions & 0 deletions exercises/practice/promises/.eslintrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
{
"root": true,
"parser": "babel-eslint",
"parserOptions": {
"ecmaVersion": 7,
"sourceType": "module"
},
"globals": {
"BigInt": true
},
"env": {
"es6": true,
"node": true,
"jest": true
},
"extends": [
"eslint:recommended",
"plugin:import/errors",
"plugin:import/warnings"
],
"rules": {
"linebreak-style": "off",

"import/extensions": "off",
"import/no-default-export": "off",
"import/no-unresolved": "off",
"import/prefer-default-export": "off"
}
}
10 changes: 10 additions & 0 deletions exercises/practice/promises/.meta/config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"blurb": "Compute the prime factors of a given natural number.",
"authors": ["slaymance"],
"contributors": ["SleeplessByte"],
"files": {
"solution": ["promises.js"],
"test": ["promises.spec.js"],
"example": [".meta/proof.ci.js"]
}
}
28 changes: 28 additions & 0 deletions exercises/practice/promises/.meta/proof.ci.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
export const promisify = (fn) => (...args) =>
new Promise((resolve, reject) =>
fn(...args, (err, result) => (err ? reject(err) : resolve(result)))
);

export const all = (promises) =>
promises.reduce(
async (acc, promise) => (await acc).concat(await promise),
Promise.resolve([])
);

export const allSettled = (promises) =>
promises.reduce(
async (acc, promise) =>
(await acc).concat(await promise.catch((err) => err)),
Promise.resolve([])
);

export const race = (promises) =>
new Promise((resolve, reject) =>
promises.forEach((promise) => promise.then(resolve, reject))
);

export const any = (promises) =>
new Promise((resolve, reject) => {
promises.forEach((promise) => promise.then(resolve).catch(() => null));
allSettled(promises).then(reject);
});
1 change: 1 addition & 0 deletions exercises/practice/promises/.npmrc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
audit=false
21 changes: 21 additions & 0 deletions exercises/practice/promises/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2019 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.
15 changes: 15 additions & 0 deletions exercises/practice/promises/babel.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
module.exports = {
presets: [
[
'@babel/preset-env',
{
targets: {
node: 'current',
},
useBuiltIns: 'entry',
corejs: 3,
},
],
],
plugins: ['@babel/plugin-syntax-bigint'],
};
31 changes: 31 additions & 0 deletions exercises/practice/promises/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
{
"name": "@exercism/javascript-promises",
"description": "Exercism exercises in Javascript.",
"author": "Katrina Owen",
"private": true,
"repository": {
"type": "git",
"url": "https://github.com/exercism/javascript"
},
"devDependencies": {
"@babel/cli": "^7.13.14",
"@babel/core": "^7.13.15",
"@babel/plugin-syntax-bigint": "^7.8.3",
"@babel/preset-env": "^7.13.15",
"@types/jest": "^26.0.22",
"@types/node": "^14.14.37",
"babel-eslint": "^10.1.0",
"babel-jest": "^26.6.3",
"core-js": "^3.10.1",
"eslint": "^7.23.0",
"eslint-plugin-import": "^2.22.1",
"jest": "^26.6.3"
},
"scripts": {
"test": "jest --no-cache ./*",
"watch": "jest --no-cache --watch ./*",
"lint": "eslint ."
},
"license": "MIT",
"dependencies": {}
}
24 changes: 24 additions & 0 deletions exercises/practice/promises/promises.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
//
// This is only a SKELETON file for the 'Pascals Triangle' exercise. It's been provided as a
// convenience to get you started writing code faster.
//

export const promisify = () => {
throw new Error('Remove this statement and implement this function');
};

export const all = () => {
throw new Error('Remove this statement and implement this function');
};

export const allSettled = () => {
throw new Error('Remove this statement and implement this function');
};

export const race = () => {
throw new Error('Remove this statement and implement this function');
};

export const any = () => {
throw new Error('Remove this statement and implement this function');
};
180 changes: 180 additions & 0 deletions exercises/practice/promises/promises.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,180 @@
import { promisify, all, allSettled, race, any } from './promises';

describe('promises', () => {
const failedCallback = new Error('Failed callback');

const createCallbackFn = (speed) => (value, callback) =>
setTimeout(() => callback(null, value), speed);
const createFailedCallback = (speed) => (_, callback) =>
setTimeout(() => callback(failedCallback), speed);

const slowestCallbackFn = createCallbackFn(20);
const slowerCallbackFn = createCallbackFn(10);
const fastCallbackFn = createCallbackFn(0);
const failedCallbackFn = createFailedCallback(10);

describe('promisify', () => {
test('returns a function', () => {
expect(typeof promisify(fastCallbackFn)).toBe('function');
});

xtest('promisified function call returns a Promise', () => {
const fastPromise = promisify(fastCallbackFn);
expect(fastPromise('fast')).toBeInstanceOf(Promise);
});

xtest("promisified function resolves to a callback's success value", () => {
const SUCCESS = 'success';
const fastPromise = promisify(fastCallbackFn);
expect(fastPromise(SUCCESS)).resolves.toEqual(SUCCESS);
});

xtest("promisified function rejects a callback's error", () => {
const failedPromise = promisify(failedCallbackFn);
expect(failedPromise(null)).rejects.toEqual(failedCallback);
});
});

describe('all', () => {
const [slowestPromise, slowerPromise, fastPromise, failedPromise] = [
slowestCallbackFn,
slowerCallbackFn,
fastCallbackFn,
failedCallbackFn,
].map((fn) => promisify(fn));

xtest('returns a Promise', () => {
expect(all([])).toBeInstanceOf(Promise);
});

xtest('resolved values appear in the order they are passed in', () => {
const FIRST = 'FIRST';
const SECOND = 'SECOND';
const THIRD = 'THIRD';
const result = all([
slowestPromise(FIRST),
slowerPromise(SECOND),
fastPromise(THIRD),
]);
expect(result).resolves.toEqual([FIRST, SECOND, THIRD]);
});

xtest('rejects if any promises fail', () => {
const result = all([fastPromise('fast'), failedPromise(null)]);
expect(result).rejects.toEqual(failedCallback);
});
});

describe('allSettled', () => {
const [slowestPromise, slowerPromise, fastPromise, failedPromise] = [
slowestCallbackFn,
slowerCallbackFn,
fastCallbackFn,
failedCallbackFn,
].map((fn) => promisify(fn));

xtest('returns a Promise', () => {
expect(allSettled([])).toBeInstanceOf(Promise);
});

xtest('resolved values appear in the order they are passed in', () => {
const FIRST = 'FIRST';
const SECOND = 'SECOND';
const THIRD = 'THIRD';
const result = allSettled([
slowestPromise(FIRST),
slowerPromise(SECOND),
fastPromise(THIRD),
]);
expect(result).resolves.toEqual([FIRST, SECOND, THIRD]);
});

xtest('resolves even if some promises fail', () => {
const FIRST = 'FIRST';
const result = all([fastPromise(FIRST), failedPromise(null)]);
expect(result).resolves.toEqual([FIRST, failedCallback]);
});
});

describe('race', () => {
const [slowestPromise, slowerPromise, fastPromise, failedPromise] = [
slowestCallbackFn,
slowerCallbackFn,
fastCallbackFn,
failedCallbackFn,
].map((fn) => promisify(fn));

xtest('returns a Promise', () => {
expect(race([])).toBeInstanceOf(Promise);
});

xtest('resolves with value of the fastest successful promise', () => {
const FAST = 'FAST';
expect(
race([
slowestPromise('SLOWEST'),
slowerPromise('SLOWER'),
fastPromise(FAST),
])
).resolves.toEqual(FAST);
});

xtest('resolves with value of the fastest promise even if other slower promises fail', () => {
const FAST = 'FAST';
expect(race([failedPromise(null), fastPromise(FAST)])).resolves.toEqual(
FAST
);
});

xtest('rejects if the fastest promise fails even if other slower promises succeed', () => {
expect(
race([slowestPromise('SLOWEST'), failedPromise(null)])
).rejects.toEqual(failedCallback);
});
});

describe('any', () => {
const [slowestPromise, slowerPromise, fastPromise, failedPromise] = [
slowestCallbackFn,
slowerCallbackFn,
fastCallbackFn,
failedCallbackFn,
].map((fn) => promisify(fn));

xtest('returns a Promise', () => {
expect(any([]).catch(() => null)).toBeInstanceOf(Promise);
});

xtest('resolves with value of fastest successful promise', () => {
const FAST = 'FAST';
expect(
race([
slowestPromise('SLOWEST'),
slowerPromise('SLOWER'),
fastPromise(FAST),
])
).resolves.toEqual(FAST);
});

xtest('resolves with value of the fastest successful promise even if slower promises fail', () => {
const FAST = 'FAST';
expect(race([failedPromise(null), fastPromise(FAST)])).resolves.toEqual(
FAST
);
});

xtest('resolves with value of fastest successful promise even if faster promises fail', () => {
const SLOWEST = 'SLOWEST';
expect(
race([failedPromise(null), slowestPromise(SLOWEST)])
).resolves.toEqual(SLOWEST);
});

xtest('rejects with array of errors if all promises fail', () => {
expect(race([failedPromise(null), failedPromise(null)])).rejects.toEqual([
failedCallback,
failedCallback,
]);
});
});
});