-
-
Save slacktracer/5c5d107585b1da516195074fb049231c to your computer and use it in GitHub Desktop.
context.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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