Last active
December 22, 2015 15:08
-
-
Save brianswisher/a3bec25f9826b97ab781 to your computer and use it in GitHub Desktop.
Singleton
This file contains hidden or 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
((doc, name)=>{ | |
var store = {}; | |
function memoize(f, cache){ | |
return function(k){ | |
if (k === null) return undefined; | |
if (cache[k]) return cache[k]; | |
return cache[k] = f(k); | |
} | |
} | |
function cnt(){ | |
return doc.getElementById(name) || | |
(()=>{ | |
var div = doc.createElement("div"); | |
div.id = name; | |
doc.body.insertBefore(div, doc.body.childNodes[0]); | |
return div; | |
})(); | |
} | |
var get = memoize(function(name){ | |
if (name === "htm") return htm(); | |
if (name === "cnt") return cnt(); | |
if (name === "log") return log(); | |
return -1; | |
}, store); | |
function htm(){ | |
return ` | |
<div class="-cnt"> | |
<div class="-name">${name}</div> | |
<pre class="-log">${get("log")}</pre> | |
</div> | |
<style> | |
#${name} .-cnt { | |
background-color: #ededed; | |
} | |
#${name} .-log { | |
text-align: left; | |
} | |
</style> | |
`; | |
} | |
function render(){ | |
if (get("cnt").innerHTML !== get("htm")) | |
get("cnt").innerHTML = get("htm"); | |
return true; | |
} | |
const Singleton = (()=>{ | |
var instance; | |
return { | |
get: ()=> instance || (()=>{ | |
return instance = new Date() | |
})() | |
}; | |
})(); | |
function log(){ | |
function assert(val, expect){ | |
if (!expect) return val; | |
return val === expect; | |
} | |
function it(describe, test) { | |
try { | |
var result = test(); | |
} catch (e) { | |
return e; | |
} | |
if (result) { | |
return `✓ ${describe}`; | |
} else { | |
return `:( ${describe}`; | |
} | |
} | |
var readyStatus = () => 1; | |
var test = ()=>{ | |
var a, b; | |
a = Singleton.get(); | |
b = Singleton.get(); | |
return [a, b]; | |
} | |
return ` | |
${it("is ready", function() { | |
return assert(readyStatus() , 1); | |
})} | |
${test.toString()} | |
${it("has 'a' equal to 'b'", function() { | |
var result = test(); | |
return assert(result[0], result[0]); | |
})} | |
`; | |
} | |
return render(); | |
})(document, "Singleton"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment