Skip to content

Instantly share code, notes, and snippets.

@190n
Forked from 140bytes/LICENSE.txt
Last active February 1, 2018 13:44
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 190n/2488b40dda507722f77f to your computer and use it in GitHub Desktop.
Save 190n/2488b40dda507722f77f to your computer and use it in GitHub Desktop.

moduleLoader

A basic module loader in 65 bytes

How to use

Add the code:

var moduleLoader = (function(a){return function(b,c){return c?(a[b]=c()):a[b]}})({});

Define a module:

moduleLoader('die', function() {
    // modules are functions that return what people will get when they ask for your module
    return function() {
        Math.floor(Math.random() * 5) + 1;
    };
});

Use your module:

var getRoll = moduleLoader('die');
console.log(getRoll());
(function(a) { // a is defined modules
return function(b, c) { // b is module name, c is definer function
return c // are we defining a new one?
? (a[b] = c()) // if so, call the definer function and save its return value
:a[b] // otherwise, return the named module
}})({}) // initialize defined modules as empty object
(function(a){return function(b,c){return c?(a[b]=c()):a[b]}})({})
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
Version 2, December 2004
Copyright (C) 2011 YOUR_NAME_HERE <YOUR_URL_HERE>
Everyone is permitted to copy and distribute verbatim or modified
copies of this license document, and changing it is allowed as long
as the name is changed.
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. You just DO WHAT THE FUCK YOU WANT TO.
{
"name": "moduleLoader",
"description": "A basic module loader in 65 bytes",
"keywords": [
"module",
"loader",
"module-loader",
"require"
]
}
<!doctype html>
<html lang="en">
<head>
<title>moduleLoader</title>
</head>
<body>
<h1>Your fortune:</h1>
<p id="fortune">
</p>
<script>
var moduleLoader = (function(a){return function(b,c){return c?(a[b]=c()):a[b]}})({});
// define 'fortune' module
moduleLoader('fortune', function() {
var fortunes = [
'bad luck',
'good luck',
'okay luck',
'your lucky number is 1337'
];
return function() {
return fortunes[Math.floor(Math.random() * fortunes.length)];
};
});
// load it
var getFortune = moduleLoader('fortune');
// get a fortune
var fortune = getFortune();
// output it
document.querySelector('#fortune').innerHTML = fortune;
</script>
</body>
</html>
@atk
Copy link

atk commented Jun 11, 2015

Smaller version:

(function(a){return function(b,c){return c?(a[b]=c()):a[b]}})({})

@190n
Copy link
Author

190n commented Jun 12, 2015

Thanks. I'm not super great at making code tiny.

@atk
Copy link

atk commented Jun 15, 2015

You're welcome. Just think of me as your caddy for this code golf ;-)

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