Skip to content

Instantly share code, notes, and snippets.

@huytd
Last active August 16, 2016 23:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save huytd/3b038bbd33650ab9a93ea9fd4638af70 to your computer and use it in GitHub Desktop.
Save huytd/3b038bbd33650ab9a93ea9fd4638af70 to your computer and use it in GitHub Desktop.
DIY assertion library
let ___expect_finish_timer = null;
const expect = function(input) {
if (___expect_finish_timer) {
clearTimeout(___expect_finish_timer);
}
___expect_finish_timer = setTimeout(() => {
console.log('\n\x1b[32m✓ All tests passed!\x1b[0m\n');
}, 200);
return {
to: {
equals(value) {
if (input != value) {
throw `Expected: ${value}\nActual: ${input}`
}
},
contains(item) {
if (Array.isArray(input)) {
if (input.indexOf(item) == -1) {
throw `Expected to found ${item} in ${input}\nActual: not found`
}
} else {
throw `Input is not an array`
}
},
be: {
true() {
if (input != true) {
throw `Expected: ${true}\nActual: ${input}`
}
},
false() {
if (input != false) {
throw `Expected: ${false}\nActual: ${input}`
}
},
less: {
than(value) {
if (input >= value) {
throw `Expected: ${input} to be less than ${value}\nActual: ${input} is greater than ${value}`
}
}
},
greater: {
than(value) {
if (input <= value) {
throw `Expected: ${input} to be greater than ${value}\nActual: ${input} is less than ${value}`
}
}
}
}
}
}
}
module.exports = expect;
const expect = require('./expect');
// Palindrome algorithm
const palindrome = (input) => {
for (let i = 0, n = input.length; i < n / 2; i++) {
if (input[i] != input[(n - 1) - i]) return false;
}
return true;
}
expect(palindrome('aba')).to.be.true();
expect(palindrome('a')).to.be.true();
expect(palindrome('ab')).to.be.false();
expect(palindrome('a0ba')).to.be.false();
expect(palindrome('abba')).to.be.true();
expect(palindrome('aabaa')).to.be.true();
expect(palindrome('aa')).to.be.true();
// Permutation algorithm
const swap = (input, x, y) => {
let s = Array.from(input);
let t = s[x];
s[x] = s[y];
s[y] = t;
return s.join('');
}
const permutation = (input) => {
let output = [];
for (let i = 0; i < input.length; i++) {
for (let j = 0; j < input.length; j++) {
let per = swap(input, i, j);
if (output.indexOf(per) == -1) {
output.push(per);
}
}
}
return output;
}
expect(permutation('abc').length).to.equals(4);
expect(permutation('abc')).to.contains('abc');
expect(permutation('abc')).to.contains('bac');
expect(permutation('abc')).to.contains('acb');
expect(permutation('abc')).to.contains('cba');
@huytd
Copy link
Author

huytd commented Aug 16, 2016

Minimal assertion library with auto report after passed all the tests.

Demo:

➜  node demo.js

✓ All tests passed!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment