Skip to content

Instantly share code, notes, and snippets.

@slacktracer
Forked from rodrigobranas/context.js
Created January 3, 2018 15:28
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 slacktracer/5c5d107585b1da516195074fb049231c to your computer and use it in GitHub Desktop.
Save slacktracer/5c5d107585b1da516195074fb049231c to your computer and use it in GitHub Desktop.
context.js
let context = {};
context.createContext = function (fn) {
let name = "context" + Math.floor(Math.random() * 10000000);
Object.defineProperty(fn, "name", {value: name});
let params = {};
global[name] = params;
fn(params);
delete global[name];
};
context.getContext = function (fn) {
let context = this.findContext();
fn(global[context]);
};
context.findContext = function () {
let stack = new Error().stack;
let regexp = /context[0-9]+/;
return regexp.exec(stack)[0];
};
module.exports = context;
let context = require("infra/context");
let expect = require("chai").expect;
describe.only("Context Test", function () {
it("Should create and get context", function () {
function a(factor, cb) {
context.createContext(function (params) {
params.x = 1 + factor;
b(factor, cb);
});
}
function b(factor, cb) {
context.getContext(function (params) {
params.y = 2 + factor;
c(factor, cb);
});
}
function c(factor, cb) {
console.trace();
context.getContext(function (params) {
params.z = 3 + factor;
cb(`${params.x} ${params.y} ${params.z}`);
});
}
a(0, function (result) {
expect(result).to.be.equal("1 2 3");
});
a(1, function (result) {
expect(result).to.be.equal("2 3 4");
});
a(2, function (result) {
expect(result).to.be.equal("3 4 5");
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment