Skip to content

Instantly share code, notes, and snippets.

@kubarskii
Last active March 24, 2021 22:03
Show Gist options
  • Save kubarskii/8bde082749b0a157b1722dacb16d8b00 to your computer and use it in GitHub Desktop.
Save kubarskii/8bde082749b0a157b1722dacb16d8b00 to your computer and use it in GitHub Desktop.
A try to create some kind of small testing lib that compares expected result and actual (made in educational purposes). Currently tests works properly only with sync functions.
function testExecutor(value) {
const A = function (x) {
this.value = x;
this.success = false;
};
A.prototype.toBe = function (x) {
if (JSON.stringify(x) === JSON.stringify(this.value) && typeof this.value === typeof x) {
this.success = true;
console.log(`%cPassed: ${JSON.stringify(x)} equals ${JSON.stringify(this.value)}`, 'color: green;');
} else {
console.error(
`%cFailed: expected ${JSON.stringify(x)}, but received ${JSON.stringify(this.value)}`,
'color: red;',
);
}
};
return new A(value);
}
const expect = (function expect() {
let testsQuantity = 0;
let successfulTests = 0;
const timer = setTimeout(() => {
console.log(
`\n%cPassed: ${successfulTests} %cFailed: ${testsQuantity - successfulTests} %cTotal: ${testsQuantity}`,
'color: green;',
'color: red;',
'color: black;',
);
}, 0);
return new Proxy(testExecutor, {
apply: (target, thisArgument, argumentArray) => {
testsQuantity += 1;
const self = { called: testsQuantity };
thisArgument = !thisArgument
? self
: {
...thisArgument,
...self,
};
const result = target.call(thisArgument, ...argumentArray);
const proxy = new Proxy(result, {
set(object, property, value) {
if (property === 'success' && value) {
successfulTests += 1;
}
return Reflect.set(...arguments);
},
});
return proxy;
},
});
})();
function fact(n) {
return n ? n * fact(n - 1) : 1;
}
function sum() {
return [...arguments].reduce((accumulator, current) => accumulator + current, 0);
}
function product() {
return [...arguments].reduce((accumulator, current) => accumulator * current, 1);
}
Array.prototype.myMap = function (callback, context) {
const initialArray = this;
const newArray = [];
for (let index = 0; index < initialArray.length; index += 1) {
newArray.push(callback.call(context, initialArray[index], index, initialArray));
}
return newArray;
};
expect(fact(3)).toBe(6);
expect(fact(1)).toBe(1);
expect(fact(0)).toBe(1);
expect(fact(8)).toBe(40320);
expect(sum(1, 3)).toBe(4);
expect(sum(1, 3, 3, 4)).toBe(11);
expect(product(2, 3)).toBe(6);
expect(product(3, 3, 3)).toBe(27);
expect(product(3, 3, 0, 10)).toBe(0);
const array = [1, 2];
const newArray = array.myMap(
function (element, index, array_) {
return { value: element, index, name: this.name };
},
{ name: 'Vasya' },
);
expect(newArray).toBe([
{ value: 1, index: 0, name: 'Vasya' },
{ value: 2, index: 1, name: 'Vasya' },
]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment