code
stringlengths 10
343k
| docstring
stringlengths 36
21.9k
| func_name
stringlengths 1
3.35k
| language
stringclasses 1
value | repo
stringlengths 7
58
| path
stringlengths 4
131
| url
stringlengths 44
195
| license
stringclasses 5
values |
---|---|---|---|---|---|---|---|
const modal = (id) => {
return window.bootstrap.Modal.getOrCreateInstance(document.getElementById(id));
}; | @param {string} id
@returns {ReturnType<typeof bootstrap.Modal>} | modal | javascript | dewanakl/undangan | js/libs/bootstrap.js | https://github.com/dewanakl/undangan/blob/master/js/libs/bootstrap.js | MIT |
const tab = (id) => {
return window.bootstrap.Tab.getOrCreateInstance(document.getElementById(id));
}; | @param {string} id
@returns {ReturnType<typeof bootstrap.Tab>} | tab | javascript | dewanakl/undangan | js/libs/bootstrap.js | https://github.com/dewanakl/undangan/blob/master/js/libs/bootstrap.js | MIT |
return (componentName, data) => ({ testPath: dirname(fileURLToPath(url)), componentName, data }) | @param {string} componentName
@param {Object?} data | dirname ( fileURLToPath ( url ) | javascript | nuejs/nue | packages/nuejs/test/test-utils.js | https://github.com/nuejs/nue/blob/master/packages/nuejs/test/test-utils.js | MIT |
function parseComponents(source) {
try {
const { components } = parse(source)
return components.map(compStr => {
try {
return eval(`(${compStr})`)
} catch (error) {
throw new Error(`Failed to parse component: ${error.message}`)
}
})
} catch (error) {
throw new Error(`Failed to parse source: ${error.message}`)
}
} | Parses component source and returns an array of component objects
@param {string} source - The component source code
@returns {Array<Object>} Array of parsed component objects
@throws {Error} If parsing fails | parseComponents ( source ) | javascript | nuejs/nue | packages/nuejs/test/test-utils.js | https://github.com/nuejs/nue/blob/master/packages/nuejs/test/test-utils.js | MIT |
export async function loadChunks(use_rust) {
const chunks = [await loadChunk()]
const ts = localStorage.getItem('_ts') || 0
if (ts) chunks.push(await loadChunk(ts))
localStorage.setItem('_ts', Date.now())
return chunks
} | Loads event chunks from the server.
This implementation uses a simple timestamp-based approach:
- Initial load fetches the base chunk (chunk-0)
- Subsequent loads fetch incremental events since last sync (chunk-1?ts=timestamp)
In production, a more sophisticated chunking strategy would be used,
typically based on time periods (monthly/quarterly chunks) for better caching.
@returns {Promise<Array>} Array of event chunks | loadChunks ( use_rust ) | javascript | nuejs/nue | packages/examples/simple-mpa/app/model/event-sourcing.js | https://github.com/nuejs/nue/blob/master/packages/examples/simple-mpa/app/model/event-sourcing.js | MIT |
async function loadChunk(ts) {
const base = sessionStorage.rust ? 'big-chunk' : 'chunk'
return await fetchWithAuth(ts ? `${base}-1.json?ts=${ts}` : `${base}-0.json`, true)
} | Loads a single chunk of events.
In production systems, chunk loading would include:
- Retry logic for network failures
- Proper error handling and reporting
- Respect for HTTP caching headers
- Possibly streaming responses for large chunks
@param {number} ts - Timestamp to fetch events after
@returns {Promise<Array>} Array of events in the chunk | loadChunk ( ts ) | javascript | nuejs/nue | packages/examples/simple-mpa/app/model/event-sourcing.js | https://github.com/nuejs/nue/blob/master/packages/examples/simple-mpa/app/model/event-sourcing.js | MIT |
get(id) {
const ret = wasm.engine_get(this.__wbg_ptr, id);
let v1;
if (ret[0] !== 0) {
v1 = getStringFromWasm0(ret[0], ret[1]).slice();
wasm.__wbindgen_free(ret[0], ret[1] * 1, 1);
}
return v1;
} | @param {number} id
@returns {string | undefined} | get ( id ) | javascript | nuejs/nue | packages/examples/simple-mpa/app/model/wasm/engine.js | https://github.com/nuejs/nue/blob/master/packages/examples/simple-mpa/app/model/wasm/engine.js | MIT |
function Verb() {
Template.apply(this, arguments);
Composer.call(this, 'verb');
init(this);
} | Initialize `Verb`
@param {Object} `context`
@api private | Verb ( ) | javascript | verbose/verb | index.js | https://github.com/verbose/verb/blob/master/index.js | MIT |
Verb.prototype.defaults = function(key/*, value*/) {
if (typeof key === 'object') {
arguments[0] = {defaults: arguments[0]};
} else {
arguments[0] = 'defaults.' + arguments[0];
}
this.option.apply(this, arguments);
return this;
}; | Set application defaults that may be overridden by the user.
This is a temporary method and should not be used.
@param {String} `key`
@param {*} `value`
@api private | Verb.prototype.defaults ( key ) | javascript | verbose/verb | index.js | https://github.com/verbose/verb/blob/master/index.js | MIT |
Verb.prototype.src = function(glob, opts) {
return stack.src(this, glob, opts);
}; | Glob patterns or filepaths to source files.
```js
verb.src('src/*.hbs', {layout: 'default'})
```
@param {String|Array} `glob` Glob patterns or file paths to source files.
@param {Object} `options` Options or locals to merge into the context and/or pass to `src` plugins
@api public | Verb.prototype.src ( glob , opts ) | javascript | verbose/verb | index.js | https://github.com/verbose/verb/blob/master/index.js | MIT |
Verb.prototype.dest = function(dest, opts) {
return stack.dest(this, dest, opts);
}; | Specify a destination for processed files.
```js
verb.dest('dist')
```
@param {String|Function} `dest` File path or rename function.
@param {Object} `options` Options and locals to pass to `dest` plugins
@api public | Verb.prototype.dest ( dest , opts ) | javascript | verbose/verb | index.js | https://github.com/verbose/verb/blob/master/index.js | MIT |
Verb.prototype.copy = function(glob, dest, opts) {
return vfs.src(glob, opts).pipe(vfs.dest(dest, opts));
}; | Copy a `glob` of files to the specified `dest`.
```js
verb.task('assets', function() {
verb.copy('assets/**', 'dist');
});
```
@param {String|Array} `glob`
@param {String|Function} `dest`
@return {Stream} Stream, to continue processing if necessary.
@api public | Verb.prototype.copy ( glob , dest , opts ) | javascript | verbose/verb | index.js | https://github.com/verbose/verb/blob/master/index.js | MIT |
Verb.prototype.diff = function(a, b, method) {
method = method || 'diffJson';
a = a || this.env;
b = b || this.cache.data;
diff[method](a, b).forEach(function (res) {
var color = chalk.gray;
if (res.added) {
color = chalk.green;
}
if (res.removed) {
color = chalk.red;
}
process.stderr.write(color(res.value));
});
console.log('\n');
}; | Display a visual representation of the difference between
two objects or strings.
```js
var doc = verb.views.docs['foo.md'];
verb.render(doc, function(err, content) {
verb.diff(doc.orig, content);
});
```
@param {Object|String} `a`
@param {Object|String} `b`
@param {String} `methodName` Optionally pass a [jsdiff] method name to use. The default is `diffJson`
@api public | Verb.prototype.diff ( a , b , method ) | javascript | verbose/verb | index.js | https://github.com/verbose/verb/blob/master/index.js | MIT |
module.exports = function(app) {
app.transform('metadata', init.metadata);
app.transform('ignore', init.ignore);
app.transform('files', env.files);
app.transform('env', env.env);
app.transform('pkg', env.pkg);
app.transform('keys', env.keys);
app.transform('paths', env.paths);
app.transform('cwd', env.cwd);
app.transform('repo', mod.repository);
app.transform('author', env.author);
app.transform('user', env.user);
app.transform('username', env.username);
app.transform('github', env.github);
app.transform('travis', env.travis);
app.transform('fork', env.fork);
app.transform('missing', env.missing);
app.transform('github-url', mod.github_url);
app.transform('twitter-url', mod.twitter_url);
app.once('loaded', function () {
app.transform('defaults', init.defaults);
app.transform('runner', init.runner);
app.transform('argv', init.argv);
app.transform('config', config);
app.transform('loaders', init.loaders);
app.transform('create', init.templates);
app.transform('engines', init.engines);
app.transform('middleware', init.middleware);
app.transform('helpers', init.helpers);
app.transform('load', init.load);
app.transform('plugins', init.plugins);
app.emit('init');
});
app.once('init', function () {
app.transform('helpers', init.helpers);
app.emit('finished');
});
app.once('finished', function () {
app.transform('checkup', init.checkup);
});
}; | Load initialization transforms
| config
| loaders
| templates
| options
| middleware
| plugins
| load
| engines
| helpers - load helpers last | module.exports ( app ) | javascript | verbose/verb | lib/init.js | https://github.com/verbose/verb/blob/master/lib/init.js | MIT |
function createStack(app, plugins) {
if (app.enabled('minimal config')) {
return es.pipe.apply(es, []);
}
function enabled(acc, plugin, name) {
if (plugin == null) {
acc.push(through.obj());
}
if (app.enabled(name + ' plugin')) {
acc.push(plugin);
}
return acc;
}
var arr = _.reduce(plugins, enabled, []);
return es.pipe.apply(es, arr);
} | Create the default plugin stack based on user settings.
Disable a plugin by passing the name of the plugin + ` plugin`
to `app.disable()`,
**Example:**
```js
app.disable('src:foo plugin');
app.disable('src:bar plugin');
``` | createStack ( app , plugins ) | javascript | verbose/verb | lib/stack.js | https://github.com/verbose/verb/blob/master/lib/stack.js | MIT |
module.exports = function props_(file, next) {
file.options = file.options || {};
file.locals = file.locals || {};
file.data = file.data || {};
next();
}; | Prime the `file` object with properties that
can be extended in plugins. | props_ ( file , next ) | javascript | verbose/verb | lib/middleware/props.js | https://github.com/verbose/verb/blob/master/lib/middleware/props.js | MIT |
module.exports = function multitoc_(file, next) {
var str = file.content;
var i = str.indexOf('<!-- toc(');
if (i === -1) return next();
var tag = str.slice(i, str.indexOf('-->') + 3);
var pattern = strip(tag);
var args = toArgs(pattern);
var files = [];
if (args.length && args[1]) {
var opts = args[1] || {};
files = glob.sync(args[0], opts).map(function (fp) {
return path.join(opts.cwd || process.cwd(), fp);
});
} else {
files = glob.sync(args[0]);
}
if (!files.length) return next();
var res = files.map(generate).join('\n');
file.content = str.split(tag).join(res);
next();
}; | Generate a Table of Contents for a glob of files. | multitoc_ ( file , next ) | javascript | verbose/verb | lib/middleware/multi-toc.js | https://github.com/verbose/verb/blob/master/lib/middleware/multi-toc.js | MIT |
module.exports = function (app) {
return function(file, next) {
file.data.debug = file.data.debug || {};
file.data.debug = function (prop) {
var segs, root, type = typeof prop;
if (type !== 'undefined') {
segs = prop.split('.');
root = segs.shift();
segs = segs.join('.');
}
// get the (pseudo) context
if (root === 'this' || root === 'context' || type === 'undefined') {
var ctx = app.cache.data;
_.merge(ctx, file.data);
return filter(ctx, segs);
}
// get the file object
if (root === 'file') {
return filter(file, segs);
}
// get the app
if (root === 'app') {
return filter(app, segs);
}
};
next();
};
}; | Convenience method for debugging.
**Examples**
```js
{%= log(debug("app")) %}
{%= log(debug("app.cache.data")) %}
{%= log(debug("file")) %}
{%= log(debug("file.data")) %}
{%= log(debug()) %}
{%= log(debug("this")) %}
{%= log(debug("this.dest")) %}
```
@todo move to a helper | module.exports ( app ) | javascript | verbose/verb | lib/middleware/debug.js | https://github.com/verbose/verb/blob/master/lib/middleware/debug.js | MIT |
module.exports = function copyright_(verb) {
var copyright = verb.get('data.copyright');
var readme = verb.files('README.md');
var parsed = false;
if (!parsed && !copyright && readme.length) {
var str = fs.readFileSync(readme[0], 'utf8');
var res = update(str);
if (res) {
parsed = true;
verb.set('data.copyright.statement', res);
}
}
return function (file, next) {
if (typeof copyright === 'string') return next();
if (typeof copyright === 'object' && Object.keys(copyright).length) {
return next();
}
copyright = verb.get('data.copyright') || parse(file.content)[0] || {};
verb.set('data.copyright', copyright);
file.data.copyright = copyright;
next();
};
}; | Add copyright information to the context.
```js
// get
console.log(verb.get('data.copyright'));
// or directly
console.log(verb.cache.data.copyright);
// used by the copyright helper
{%= copyright() %}
``` | copyright_ ( verb ) | javascript | verbose/verb | lib/middleware/copyright.js | https://github.com/verbose/verb/blob/master/lib/middleware/copyright.js | MIT |
module.exports = function (app) {
return function (file, next) {
var opts = extend({}, file.options, app.option('matter'));
parser.parse(file, opts, function (err) {
if (err) return next(err);
next();
});
};
}; | Default middleware for parsing front-matter | module.exports ( app ) | javascript | verbose/verb | lib/middleware/matter.js | https://github.com/verbose/verb/blob/master/lib/middleware/matter.js | MIT |
module.exports = function(app) {
return function (file, next) {
var diff = app.get('argv.diff');
if (!diff) return next();
console.log();
console.log('- end -');
console.log('---------------------------------------------------------------');
console.log(relative(file.path));
console.log();
if (file.content === '') {
console.log(chalk.gray(' no content.'));
} else if (file.content === file.orig) {
console.log(chalk.gray(' content is unchanged.'));
} else {
app.diff(file.orig, file.content, 'diffLines');
}
next();
};
}; | Show a diff comparison of pre- and post-render content. | module.exports ( app ) | javascript | verbose/verb | lib/middleware/diff.js | https://github.com/verbose/verb/blob/master/lib/middleware/diff.js | MIT |
module.exports = function(app) {
var config = extend({}, app.options, app.get('argv'));
var diff = config.diff;
var lint = config.lint;
return function (file, next) {
if (!lint) return next();
var str = file.content, error = {};
if (/\[object Object\]/.test(str)) {
// only show the last one or two path segments
error.path = file.path.split(/[\\\/]/).slice(-2).join('/');
error.message = '`[object Object]`';
error.content = str;
if (diff) {
app.diff(str, file.orig);
}
app.union('messages.errors', error);
}
next();
};
}; | Lints post-render content to find potential errors
or incorrect content. | module.exports ( app ) | javascript | verbose/verb | lib/middleware/lint-after.js | https://github.com/verbose/verb/blob/master/lib/middleware/lint-after.js | MIT |
module.exports = function(file, next) {
var orig = file.options.originalPath;
file.data.src = file.data.src || {};
file.data.src.path = orig;
// look for native `path.parse` method first
var parsed = typeof path.parse === 'function'
? path.parse(orig)
: parse(orig);
file.data.src.dirname = parsed.dir;
file.data.src.filename = parsed.name;
file.data.src.basename = parsed.base;
file.data.src.extname = parsed.ext;
file.data.src.ext = parsed.ext;
file.data.process = {};
file.data.process.cwd = function () {
return process.cwd();
};
file.data.resolve = path.resolve;
next();
}; | Set properties on `file.data.src` to use in plugins,
other middleware, helpers, templates etc. | module.exports ( file , next ) | javascript | verbose/verb | lib/middleware/src.js | https://github.com/verbose/verb/blob/master/lib/middleware/src.js | MIT |
module.exports = function(file, next) {
if (!file.hasOwnProperty('data')) {
throw new Error('ext middleware: file object should have a `data` property.');
}
if (!file.data.hasOwnProperty('src')) {
throw new Error('ext middleware: file.data object should have a `src` property.');
}
file.ext = file.ext ? utils.formatExt(file.ext) : (file.data.src.ext || path.extname(file.path));
next();
}; | Ensure that `ext` is on the file object. | module.exports ( file , next ) | javascript | verbose/verb | lib/middleware/ext.js | https://github.com/verbose/verb/blob/master/lib/middleware/ext.js | MIT |
module.exports = function conflict_(app) {
var config = extend({}, app.options, app.get('argv'));
if (config.verbose) {
console.log();
console.log(chalk.bold.underline('Checking for conflicts…'));
console.log();
}
return function (file, next) {
if (config.nolint === true) {
return next();
}
var str = file.content;
var res = helpers(str);
var conflicting = problematic(app, file, res, config.verbose);
var h = {};
if (!conflicting.length) {
return next();
}
var ctx = {};
ctx.options = _.extend({}, app.options, file.options);
ctx.context = _.merge({}, app.cache.data, file.data, file.locals);
ctx.app = app;
file.locals = file.locals || {};
file.locals.__ = file.locals.__ || {};
// console.log('actual:', app._.helpers.sync)
for (var i = 0; i < conflicting.length; i++) {
var name = conflicting[i];
file.content = namespace(file.content, name);
var syncFn = function () {
return app._.helpers.sync[name].apply(this, arguments);
};
if (syncFn) {
h[name] = _.bind(syncFn, ctx);
file.locals.__[name] = _.bind(syncFn, ctx);
app.helpers({__: h});
delete app._.helpers.sync[name];
}
var asyncFn = app._.helpers.async[name];
if (asyncFn) {
h[name] = _.bind(asyncFn, ctx);
file.locals.__[name] = _.bind(asyncFn, ctx);
app.asyncHelpers({__: h});
delete app._.helpers.async[name];
}
if (!asyncFn && !syncFn) {
h[name] = noop(name);
file.locals.__[name] = noop(name);
app.helpers({__: h});
}
}
next();
};
}; | Resolve conflicts between helpers and data
properties before rendering. | conflict_ ( app ) | javascript | verbose/verb | lib/middleware/conflict.js | https://github.com/verbose/verb/blob/master/lib/middleware/conflict.js | MIT |
module.exports = function(app) {
return function(file, next) {
if (app.isFalse('readme') || app.isTrue('noreadme')) {
return next();
}
if (file.readme === false || file.noreadme === true) {
return next();
}
if (/\.(?:verb(rc)?|readme)\.md$/i.test(file.path)) {
file.path = 'README.md';
}
next();
};
}; | Set the dest path to `README.md` for `.verb.md` templates | module.exports ( app ) | javascript | verbose/verb | lib/middleware/readme.js | https://github.com/verbose/verb/blob/master/lib/middleware/readme.js | MIT |
module.exports = function(app) {
return function (file, next) {
file.content += app.get('data.append') || '';
next();
};
}; | `append` post-render middleware.
If a string is defined on `verb.cache.data.append`,
it will be appended to the content of every file
that matches the route. | module.exports ( app ) | javascript | verbose/verb | lib/middleware/append.js | https://github.com/verbose/verb/blob/master/lib/middleware/append.js | MIT |
module.exports = function(assemble) {
return function assetsPath(file, next) {
calculate(assemble, file, 'assets');
calculate(assemble, file, 'public');
next();
};
}; | Calculate the path from the `assets` or `public`
path define on the options to the destination
file. | module.exports ( assemble ) | javascript | verbose/verb | lib/middleware/assets.js | https://github.com/verbose/verb/blob/master/lib/middleware/assets.js | MIT |
utils.linkify = function linkify(domain, https) {
return function (author) {
if (typeof author !== 'object') {
throw new TypeError('utils.linkify expects author to be an object.');
}
var username = author.username;
if (typeof username === 'undefined') {
username = this.context[domain] && this.context[domain].username;
}
if (typeof username === 'undefined') {
username = this.config.get(domain + '.username');
}
if (typeof username === 'object') {
var o = username;
username = o.username;
}
if (!username) return '';
var protocol = https ? 'https://' : 'http://';
var res = mdu.link(domain + '/' + username, protocol + domain + '.com/' + username);
return '+ ' + res;
};
}; | Create a url from the given `domain`, optionally pass `true`
as the second argument to use `https` as the protocol.
@param {String} `domain`
@param {String} `https`
@return {String} | linkify ( domain , https ) | javascript | verbose/verb | lib/utils/index.js | https://github.com/verbose/verb/blob/master/lib/utils/index.js | MIT |
utils.files = function files(arr) {
return function(pattern, options) {
return mm(arr, pattern, options);
};
}; | Returns a matching function to use against
the list of given files.
@param {Array} `files` The list of files to match against.
@return {Array} Array of matching files | files ( arr ) | javascript | verbose/verb | lib/utils/index.js | https://github.com/verbose/verb/blob/master/lib/utils/index.js | MIT |
utils.tryRequire = function tryRequire(fp) {
if (typeof fp !== 'string') {
throw new Error('utils.tryRequire() expects a string.');
}
var key = 'tryRequire:' + fp;
if (cache.hasOwnProperty(key)) return cache[key];
try {
return (cache[key] = require(fp));
} catch(err) {}
try {
return (cache[key] = require(path.resolve(fp)));
} catch(err) {}
return null;
}; | Try to require a file, fail silently. Encapsulating try-catches
also helps with v8 optimizations. | tryRequire ( fp ) | javascript | verbose/verb | lib/utils/index.js | https://github.com/verbose/verb/blob/master/lib/utils/index.js | MIT |
utils.basename = function basename(fp, ext) {
if (typeof fp === 'undefined') {
throw new Error('utils.basename() expects a string.');
}
return fp.substr(0, fp.length - (ext || path.extname(fp)).length);
}; | Get the basename of a file path, excluding extension.
@param {String} `fp`
@param {String} `ext` Optionally pass the extension. | basename ( fp , ext ) | javascript | verbose/verb | lib/utils/index.js | https://github.com/verbose/verb/blob/master/lib/utils/index.js | MIT |
utils.formatExt = function formatExt(ext) {
// could be filepath with no ext, e.g. `LICENSE`
if (typeof ext === 'undefined') return;
if (Array.isArray(ext)) return ext.map(utils.formatExt);
if (ext.charAt(0) !== '.') ext = '.' + ext;
return ext;
}; | Ensure that a file extension is formatted properly.
@param {String} `ext` | formatExt ( ext ) | javascript | verbose/verb | lib/utils/index.js | https://github.com/verbose/verb/blob/master/lib/utils/index.js | MIT |
utils.norender = function norender(verb, file, locals) {
var ext = file && file.ext ? utils.formatExt(ext) : null;
if (ext && !verb.engines.hasOwnProperty(ext)) {
return false;
}
return verb.isTrue('norender') || verb.isFalse('render')
|| file.norender === true || file.render === false
|| locals.norender === true || locals.render === false;
}; | Detect if the user has specfied not to render a file. | norender ( verb , file , locals ) | javascript | verbose/verb | lib/utils/index.js | https://github.com/verbose/verb/blob/master/lib/utils/index.js | MIT |
module.exports = function(app) {
var del = app.get('argv.del');
var config = app.config;
var keys = mm(Object.keys(config.data), del);
if (keys.length) {
config.omit.apply(config, keys);
console.log('deleted:', bold(keys.join(', ')));
}
}; | Delete a value from the config store.
```sh
$ --del foo
# delete multiple values
$ --del foo,bar,baz
``` | module.exports ( app ) | javascript | verbose/verb | lib/transforms/config/del.js | https://github.com/verbose/verb/blob/master/lib/transforms/config/del.js | MIT |
module.exports = function(app) {
var arr = app.get('argv.union');
var config = app.config;
var args;
if (arr) {
args = arr.split('=');
if (args.length > 1) {
var val = config.get(args[1]);
args[2] = args[2].split(',');
config.set(args[1], union(val, args[2]));
}
}
}; | Get a value from the config store.
```sh
$ --union one=a,b,c
#=> {one: ['a', 'b', 'c']}
$ --union one=d
#=> {one: ['a', 'b', 'c', 'd']}
``` | module.exports ( app ) | javascript | verbose/verb | lib/transforms/config/union.js | https://github.com/verbose/verb/blob/master/lib/transforms/config/union.js | MIT |
module.exports = function(app) {
var config = app.config;
var args;
var set = app.get('argv.set');
if (set) {
args = set.split('=');
if (args.length === 2) {
config.set(args[0], args[1]);
} else {
config.set(args[0], true);
}
}
}; | Persist a value on the config store.
```sh
$ --set one=abc
#=> {one: 'abc'}
$ --set one
#=> {one: true}
``` | module.exports ( app ) | javascript | verbose/verb | lib/transforms/config/set.js | https://github.com/verbose/verb/blob/master/lib/transforms/config/set.js | MIT |
module.exports = function(app) {
var config = app.config;
var get = app.get('argv.get');
if (get) {
if (get === true || get === 'true') {
console.log(cyan('config config:'), stringify(config.data));
} else if (get.indexOf(',') !== -1) {
get.split(',').forEach(function (val) {
console.log(val, '=', stringify(config.get(val)));
});
} else {
console.log(get, '=', stringify(config.get(get)));
}
}
}; | Get a value from the config store.
```sh
$ --get one
# or
$ --get one,two,three
``` | module.exports ( app ) | javascript | verbose/verb | lib/transforms/config/get.js | https://github.com/verbose/verb/blob/master/lib/transforms/config/get.js | MIT |
module.exports = function(app) {
var config = app.config;
var args;
var option = app.get('argv.option');
if (option) {
args = option.split('=');
if (args.length === 2) {
config.set(args[0], args[1]);
} else {
config.set(args[0], true);
}
}
var enable = app.get('argv.enable');
if (enable) {
config.set(enable, true);
}
var disable = app.get('argv.disable');
if (disable) {
config.set(disable, false);
}
}; | Persist a value on the config store.
```sh
$ --option one=abc
#=> {one: 'abc'}
$ --option one
#=> {one: true}
``` | module.exports ( app ) | javascript | verbose/verb | lib/transforms/config/option.js | https://github.com/verbose/verb/blob/master/lib/transforms/config/option.js | MIT |
module.exports = function(verb) {
verb.config = new Config('verb');
verb.transform('set', config.set);
verb.transform('get', config.get);
verb.transform('del', config.del);
verb.transform('option', config.option);
verb.transform('union', config.union);
}; | Initialize a global config store, for persisting data
that may be reused across projects.
Initialized in the `init` transform. | module.exports ( verb ) | javascript | verbose/verb | lib/transforms/config/index.js | https://github.com/verbose/verb/blob/master/lib/transforms/config/index.js | MIT |
module.exports = function(app) {
app.data({
runner: {
name: 'verb-cli',
url: 'https://github.com/assemble/verb-cli'
}
});
}; | Adds data to the context for the current `verb.runner`. | module.exports ( app ) | javascript | verbose/verb | lib/transforms/init/runner.js | https://github.com/verbose/verb/blob/master/lib/transforms/init/runner.js | MIT |
module.exports = function(app) {
app.create('example', {isRenderable: true}, ['base']);
app.create('include', {isRenderable: true}, ['base']);
app.create('badge', {isRenderable: true}, ['base']);
app.create('doc', {isRenderable: true}, ['base']);
}; | Create built-in template types, using the `base` loader | module.exports ( app ) | javascript | verbose/verb | lib/transforms/init/templates.js | https://github.com/verbose/verb/blob/master/lib/transforms/init/templates.js | MIT |
module.exports = function(app) {
app.data('../../pkg.json', function (fp) {
return utils.tryRequire(path.resolve(__dirname, fp)) || {};
});
}; | Prime `verb.cache.data` with empty package.json fields that
will be over-written by the user's environment. | module.exports ( app ) | javascript | verbose/verb | lib/transforms/init/data.js | https://github.com/verbose/verb/blob/master/lib/transforms/init/data.js | MIT |
module.exports = function(app) {
app.cache.argv = app.cache.argv || {};
}; | Prime the `verb.cache.argv` object. Used for setting values
that are passed from the command line. | module.exports ( app ) | javascript | verbose/verb | lib/transforms/init/argv.js | https://github.com/verbose/verb/blob/master/lib/transforms/init/argv.js | MIT |
module.exports = function(app) {
Object.defineProperty(app, 'metadata', {
get: function () {
return require(path.resolve(__dirname, '../../..', 'package.json'));
},
set: function () {
console.log('`verb.metadata` is read-only and cannot be modified.');
}
});
}; | Called in the `init` transform. Adds Verb's package.json
data to `verb.metadata`.
@param {Object} `app` | module.exports ( app ) | javascript | verbose/verb | lib/transforms/init/metadata.js | https://github.com/verbose/verb/blob/master/lib/transforms/init/metadata.js | MIT |
module.exports = function github_(verb) {
var username = verb.get('data.github.username');
if (username) {
verb.set('data.github.url', 'https://github/' + username);
}
}; | Modifier to add a github URl if a github username
exists on the context. | github_ ( verb ) | javascript | verbose/verb | lib/transforms/modifiers/github_url.js | https://github.com/verbose/verb/blob/master/lib/transforms/modifiers/github_url.js | MIT |
module.exports = function(app) {
var repo = app.get('data.repository');
if (typeof repo === 'string') {
repo = 'git://github.com/' + repo + '.git';
app.data({repository: {url: repo}});
}
}; | Called in the `init` transform. Normalizes the
`repository` field. | module.exports ( app ) | javascript | verbose/verb | lib/transforms/modifiers/repository.js | https://github.com/verbose/verb/blob/master/lib/transforms/modifiers/repository.js | MIT |
module.exports = function twitter_(verb) {
var username = verb.get('data.twitter.username');
if (username) {
verb.set('data.twitter.url', 'http://twitter/' + username);
}
}; | Modifier to add a twitter URl if a twitter username
exists on the context. | twitter_ ( verb ) | javascript | verbose/verb | lib/transforms/modifiers/twitter_url.js | https://github.com/verbose/verb/blob/master/lib/transforms/modifiers/twitter_url.js | MIT |
module.exports = function(verb) {
verb.cache.missing = verb.cache.missing || {};
if (!verb.cache.data.hasOwnProperty('licenses')) {
verb.union('messages.missing.data', ['licenses']);
}
if (!verb.cache.data.hasOwnProperty('license')) {
verb.union('messages.missing.data', ['license']);
}
}; | Called in the `init` transform to ensure that certain
fields are on the context.
@param {Object} `verb` | module.exports ( verb ) | javascript | verbose/verb | lib/transforms/env/missing.js | https://github.com/verbose/verb/blob/master/lib/transforms/env/missing.js | MIT |
module.exports = function(app) {
app.set('data.username', app.get('data.github.username'));
}; | Called in the `init` transform. Adds `user` and `username`
for the current project to the context. | module.exports ( app ) | javascript | verbose/verb | lib/transforms/env/user.js | https://github.com/verbose/verb/blob/master/lib/transforms/env/user.js | MIT |
module.exports = function(app) {
if (!app.get('data.github.username')) {
var author = app.get('data.author');
if (typeof author.url === 'string' && /\/github/.test(author.url)) {
var parsed = github(author.url);
var user = (parsed && parsed.user) || '';
app.set('data.github.username', user);
app.set('data.username', user);
}
}
}; | Called in the `username` transform, if the `git` transform
was not able to find anything, this attempts to generate a
username from other fields. | module.exports ( app ) | javascript | verbose/verb | lib/transforms/env/username.js | https://github.com/verbose/verb/blob/master/lib/transforms/env/username.js | MIT |
module.exports = function(app) {
var dir = app.option('templates');
if (typeof dir === 'undefined') {
dir = path.join(process.cwd(), 'templates');
}
app.set('paths.templates');
}; | Get/set the current working directory
```js
console.log(verb.templates);
//=> /dev/foo/bar/
```
Or set:
```js
verb.templates = 'foo';
``` | module.exports ( app ) | javascript | verbose/verb | lib/transforms/env/templates.js | https://github.com/verbose/verb/blob/master/lib/transforms/env/templates.js | MIT |
module.exports = function(verb) {
if (!verb.get('data.git.username')) {
verb.set('data.git.username', username());
}
}; | Called in the `username` transform, if a `username`
cannot be determined from easier means, this attempts
to get the `user.name` from global `.git config` | module.exports ( verb ) | javascript | verbose/verb | lib/transforms/env/git.js | https://github.com/verbose/verb/blob/master/lib/transforms/env/git.js | MIT |
module.exports = function(verb) {
var patterns = ['*', 'lib/*', 'test/*'];
var files = glob.sync(patterns, {dot: true});
verb.files = function (pattern, options) {
return mm(files, pattern, options);
};
verb.fileExists = function (pattern, options) {
var res = verb.files(pattern, options);
return !!(res && res.length);
};
}; | Loads files from the root of the current project.
Returns matching function bound to the list of files.
```js
console.log(verb.files('*.js'));
//=> ['foo.js', 'bar.js']
``` | module.exports ( verb ) | javascript | verbose/verb | lib/transforms/env/files.js | https://github.com/verbose/verb/blob/master/lib/transforms/env/files.js | MIT |
module.exports = function(verb) {
if (!verb.cache.data.hasOwnProperty('keys')) {
verb.cache.data.keys = Object.keys(verb.env);
}
}; | Adds `Object.keys()` to `verb.cache.data`. Can be used
for conflict resolution between helpers and context properties. | module.exports ( verb ) | javascript | verbose/verb | lib/transforms/env/keys.js | https://github.com/verbose/verb/blob/master/lib/transforms/env/keys.js | MIT |
module.exports = function(verb) {
var filename = verb.option('config') || 'package.json';
verb.data(filename, function (fp) {
return cache[fp] || (cache[fp] = utils.tryRequire(fp) || {});
});
}; | Called in the `init` transform. A read-only copy of this data is also
stored on `verb.env`
@param {Object} `verb` | module.exports ( verb ) | javascript | verbose/verb | lib/transforms/env/pkg.js | https://github.com/verbose/verb/blob/master/lib/transforms/env/pkg.js | MIT |
module.exports = function(verb) {
var repo = verb.get('data.repository');
var url = (repo && typeof repo === 'object')
? repo.url
: repo;
var github = parse(url);
if (github && Object.keys(github).length) {
verb.data({github: github});
}
}; | Called in the `init` transform. Adds a `github`
property to the context.
@param {Object} `verb` | module.exports ( verb ) | javascript | verbose/verb | lib/transforms/env/github.js | https://github.com/verbose/verb/blob/master/lib/transforms/env/github.js | MIT |
module.exports = function(app) {
var cwd = app.option('cwd') || process.cwd();
Object.defineProperty(app, 'cwd', {
configurable: true,
get: function () {
return cwd;
},
set: function (val) {
cwd = val;
}
});
}; | Get/set the current working directory
```js
console.log(verb.cwd);
//=> /dev/foo/bar/
```
Or set:
```js
verb.cwd = 'foo';
``` | module.exports ( app ) | javascript | verbose/verb | lib/transforms/env/cwd.js | https://github.com/verbose/verb/blob/master/lib/transforms/env/cwd.js | MIT |
module.exports = function(app) {
var github = app.get('data.github');
if (! github) {
return;
}
var travis = stringify(github.user, github.repo);
app.set('data.travis_url', travis);
}; | Called in the `init` transform. Adds a `travis_url`
property to the context. | module.exports ( app ) | javascript | verbose/verb | lib/transforms/env/travis.js | https://github.com/verbose/verb/blob/master/lib/transforms/env/travis.js | MIT |
function gitignore(cwd, fp, arr) {
fp = path.resolve(cwd, fp);
if (!fs.existsSync(fp)) {
return utils.defaultIgnores;
}
var str = fs.readFileSync(fp, 'utf8');
return parse(str, arr);
} | Parse the local `.gitignore` file and add
the resulting ignore patterns. | gitignore ( cwd , fp , arr ) | javascript | verbose/verb | lib/transforms/env/ignore.js | https://github.com/verbose/verb/blob/master/lib/transforms/env/ignore.js | MIT |
module.exports = function(app) {
var env = app.env || app.option('env') || require(path.resolve('package.json'));
merge(env, (env.verb && env.verb.data) || {});
Object.defineProperty(app, 'env', {
get: function () {
return env;
},
set: function () {
console.log('verb.env is read-only and cannot be modified.');
}
});
}; | Getter for getting stored values from `verb.env`, a read-only
object that stores the project's package.json before it's modified.
```js
console.log(verb.env.name);
//=> 'my-project'
```
@return {*} The value of specified property.
@api public | module.exports ( app ) | javascript | verbose/verb | lib/transforms/env/env.js | https://github.com/verbose/verb/blob/master/lib/transforms/env/env.js | MIT |
module.exports = function(app) {
app.helper('date', require('helper-date'));
app.helper('apidocs', require('template-helper-apidocs'));
app.helper('multiToc', require('helper-toc')(app.option('toc')));
app.helper('codelinks', require('helper-codelinks')(app));
app.helper('changelog', require('helper-changelog')(app));
app.helper('copyright', require('helper-copyright'));
app.helper('coverage', require('helper-coverage'));
app.helper('license', require('helper-license'));
app.helper('relative', require('relative'));
app.helper('year', require('year'));
}; | Transform for loading default sync helpers | module.exports ( app ) | javascript | verbose/verb | lib/helpers/sync.js | https://github.com/verbose/verb/blob/master/lib/helpers/sync.js | MIT |
module.exports = function(app) {
app.asyncHelper('reflinks', reflinks);
app.asyncHelper('related', related());
app.asyncHelper('example', helper('example', example));
app.asyncHelper('include', helper('include'));
app.asyncHelper('badge', helper('badge'));
app.asyncHelper('docs', helper('doc'));
}; | Transform for loading default async helpers | module.exports ( app ) | javascript | verbose/verb | lib/helpers/async.js | https://github.com/verbose/verb/blob/master/lib/helpers/async.js | MIT |
module.exports = function resolve_(name, key) {
return resolve.sync(name)[typeof key === 'string' ? key : 'main'];
}; | Return a property from the package.json of the specified module.
_(The module must be installed in `node_modules`)_.
```js
{%%= resolve("micromatch") %}
//=> 'node_modules/micromatch/index.js'
{%%= resolve("micromatch", "version") %}
//=> '2.2.0'
```
@param {String} `fp` The path of the file to include.
@param {String} `options`
@option {String} `name` Replace `./` in `require('./')` with the given name.
@return {String} | resolve_ ( name , key ) | javascript | verbose/verb | lib/helpers/custom/resolve.js | https://github.com/verbose/verb/blob/master/lib/helpers/custom/resolve.js | MIT |
module.exports = function example(str, opts) {
if (typeof str !== 'string') {
throw new TypeError('example-helper expects a string.');
}
opts = opts || {};
if (opts.name) {
str = str.split(/\(['"]\.\/['"]\)/).join('(\'' + opts.name + '\')');
}
return str;
}; | Create a code example from the contents of the specified
JavaScript file.
```js
{%%= example("foo", {name: "my-module"}) %}
```
@param {String} `fp` The path of the file to include.
@param {String} `options`
@option {String} `name` Replace `./` in `require('./')` with the given name.
@return {String} | example ( str , opts ) | javascript | verbose/verb | lib/helpers/custom/example.js | https://github.com/verbose/verb/blob/master/lib/helpers/custom/example.js | MIT |
module.exports = function (verb) {
verb.badge('npm', '[](https://www.npmjs.org/package/{%= name %})');
verb.badge('npm2', '[](https://www.npmjs.org/package/{%= name %})');
verb.badge('nodei', '[](https://nodei.co/npm/{%= name %})');
verb.badge('travis', '[](https://travis-ci.org/{%= name %})');
return function shield(name, locals) {
var ctx = _.extend({}, this.context, locals);
return this.app.render(verb.views.badges[name], ctx);
};
}; | Transform for loading the `{%= shield() %}` helper
These aren't really implemented yet. this is a
placeholder for better logic | module.exports ( verb ) | javascript | verbose/verb | lib/helpers/custom/shield.js | https://github.com/verbose/verb/blob/master/lib/helpers/custom/shield.js | MIT |
function pretty(str, options) {
return new Remarkable(options)
.use(prettify)
.render(str);
} | Instantiate `Remarkable` and use the `prettify` plugin
on the given `str`.
@param {String} `str`
@param {Object} `options`
@return {String} | pretty ( str , options ) | javascript | verbose/verb | lib/plugins/format.js | https://github.com/verbose/verb/blob/master/lib/plugins/format.js | MIT |
function noformat(app, file, locals, argv) {
return app.isTrue('noformat') || app.isFalse('format')
|| file.noformat === true || file.format === false
|| locals.noformat === true || locals.format === false
|| argv.noformat === true || argv.format === false;
} | Push the `file` through if the user has specfied
not to format it. | noformat ( app , file , locals , argv ) | javascript | verbose/verb | lib/plugins/format.js | https://github.com/verbose/verb/blob/master/lib/plugins/format.js | MIT |
function enabled(app, file, options, argv) {
var template = extend({}, file.locals, file.options, file.data);
return isTrue(argv, 'reflinks')
|| isTrue(template, 'reflinks')
|| isTrue(options, 'reflinks')
|| isTrue(app.options, 'reflinks');
} | Push the `file` through if the user has specfied
not to generate reflinks. | enabled ( app , file , options , argv ) | javascript | verbose/verb | lib/plugins/reflinks.js | https://github.com/verbose/verb/blob/master/lib/plugins/reflinks.js | MIT |
function set(a, b, c) {
// do stuff
} | Assign `value` to `key`
@param {String} a
@param {*} b
@api public | set ( a , b , c ) | javascript | verbose/verb | test/fixtures/apidocs-comments.js | https://github.com/verbose/verb/blob/master/test/fixtures/apidocs-comments.js | MIT |
function bar() {} | @TODO: this is todo #1 -->
some random text
@todo:this is todo #2 -->
@todo: this is todo #3 --> | bar ( ) | javascript | verbose/verb | test/fixtures/middleware/todo.js | https://github.com/verbose/verb/blob/master/test/fixtures/middleware/todo.js | MIT |
var deinterlace = function deinterlace(pixels, width) {
var newPixels = new Array(pixels.length);
var rows = pixels.length / width;
var cpRow = function cpRow(toRow, fromRow) {
var fromPixels = pixels.slice(fromRow * width, (fromRow + 1) * width);
newPixels.splice.apply(newPixels, [toRow * width, width].concat(fromPixels));
}; // See appendix E.
var offsets = [0, 4, 2, 1];
var steps = [8, 8, 4, 2];
var fromRow = 0;
for (var pass = 0; pass < 4; pass++) {
for (var toRow = offsets[pass]; toRow < rows; toRow += steps[pass]) {
cpRow(toRow, fromRow);
fromRow++;
}
}
return newPixels;
}; | Deinterlace function from https://github.com/shachaf/jsgif | deinterlace ( pixels , width ) | javascript | matt-way/gifuct-js | demo/demo.build.js | https://github.com/matt-way/gifuct-js/blob/master/demo/demo.build.js | MIT |
var lzw = function lzw(minCodeSize, data, pixelCount) {
var MAX_STACK_SIZE = 4096;
var nullCode = -1;
var npix = pixelCount;
var available, clear, code_mask, code_size, end_of_information, in_code, old_code, bits, code, i, datum, data_size, first, top, bi, pi;
var dstPixels = new Array(pixelCount);
var prefix = new Array(MAX_STACK_SIZE);
var suffix = new Array(MAX_STACK_SIZE);
var pixelStack = new Array(MAX_STACK_SIZE + 1); // Initialize GIF data stream decoder.
data_size = minCodeSize;
clear = 1 << data_size;
end_of_information = clear + 1;
available = clear + 2;
old_code = nullCode;
code_size = data_size + 1;
code_mask = (1 << code_size) - 1;
for (code = 0; code < clear; code++) {
prefix[code] = 0;
suffix[code] = code;
} // Decode GIF pixel stream.
var datum, bits, count, first, top, pi, bi;
datum = bits = count = first = top = pi = bi = 0;
for (i = 0; i < npix;) {
if (top === 0) {
if (bits < code_size) {
// get the next byte
datum += data[bi] << bits;
bits += 8;
bi++;
continue;
} // Get the next code.
code = datum & code_mask;
datum >>= code_size;
bits -= code_size; // Interpret the code
if (code > available || code == end_of_information) {
break;
}
if (code == clear) {
// Reset decoder.
code_size = data_size + 1;
code_mask = (1 << code_size) - 1;
available = clear + 2;
old_code = nullCode;
continue;
}
if (old_code == nullCode) {
pixelStack[top++] = suffix[code];
old_code = code;
first = code;
continue;
}
in_code = code;
if (code == available) {
pixelStack[top++] = first;
code = old_code;
}
while (code > clear) {
pixelStack[top++] = suffix[code];
code = prefix[code];
}
first = suffix[code] & 0xff;
pixelStack[top++] = first; // add a new string to the table, but only if space is available
// if not, just continue with current table until a clear code is found
// (deferred clear code implementation as per GIF spec)
if (available < MAX_STACK_SIZE) {
prefix[available] = old_code;
suffix[available] = first;
available++;
if ((available & code_mask) === 0 && available < MAX_STACK_SIZE) {
code_size++;
code_mask += available;
}
}
old_code = in_code;
} // Pop a pixel off the pixel stack.
top--;
dstPixels[pi++] = pixelStack[top];
i++;
}
for (i = pi; i < npix; i++) {
dstPixels[i] = 0; // clear missing pixels
}
return dstPixels;
}; | javascript port of java LZW decompression
Original java author url: https://gist.github.com/devunwired/4479231 | lzw ( minCodeSize , data , pixelCount ) | javascript | matt-way/gifuct-js | demo/demo.build.js | https://github.com/matt-way/gifuct-js/blob/master/demo/demo.build.js | MIT |
const inRange = (x, a, b) => {
const [min, max] = [Math.min(a, b), Math.max(a, b)];
return x >= min && x <= max;
} | Checks if a value is within the specified range.
@function
@param {number} x - The value to check.
@param {number} a - The start of the range.
@param {number} b - The end of the range.
@returns {boolean} Returns true if the value is within the range [a, b], otherwise false. | inRange | javascript | zakarialaoui10/ziko.js | src/math/utils/checkers.js | https://github.com/zakarialaoui10/ziko.js/blob/master/src/math/utils/checkers.js | MIT |
const isApproximatlyEqual = (a, b, Err = 0.0001) => {
return Math.abs(a - b) <= Err;
} | Checks if two numbers are approximately equal within a given error margin.
@param {number} a - The first number.
@param {number} b - The second number.
@param {number} [Err=0.0001] - The maximum acceptable difference between the two numbers.
@returns {boolean} Returns true if the two numbers are approximately equal within the specified error margin, otherwise false. | isApproximatlyEqual | javascript | zakarialaoui10/ziko.js | src/math/utils/checkers.js | https://github.com/zakarialaoui10/ziko.js/blob/master/src/math/utils/checkers.js | MIT |
const deg2rad = (...deg) => mapfun(x => x * Math.PI / 180, ...deg); | Converts degrees to radians.
@param {...number} deg - Degrees to convert.
@returns {number|number[]} Returns an array of radians corresponding to the input degrees. | (anonymous) | javascript | zakarialaoui10/ziko.js | src/math/utils/conversions.js | https://github.com/zakarialaoui10/ziko.js/blob/master/src/math/utils/conversions.js | MIT |
const rad2deg = (...rad) => mapfun(x => x / Math.PI * 180, ...rad); | Converts radians to degrees.
@param {...number} rad - Radians to convert.
@returns {number|number[]} Returns an array of degrees corresponding to the input radians. | (anonymous) | javascript | zakarialaoui10/ziko.js | src/math/utils/conversions.js | https://github.com/zakarialaoui10/ziko.js/blob/master/src/math/utils/conversions.js | MIT |
const mapfun=(fun,...X)=>{
const Y=X.map(x=>{
if(x===null)return fun(null);
if(["number","string","boolean","bigint","undefined"].includes(typeof x))return fun(x);
if(x instanceof Array)return x.map(n=>mapfun(fun,n));
if(ArrayBuffer.isView(x))return x.map(n=>fun(n));
if(x instanceof Set)return new Set(mapfun(fun,...[...x]));
if(x instanceof Map)return new Map([...x].map(n=>[n[0],mapfun(fun,n[1])]));
if(x instanceof Matrix){
return new Matrix(x.rows,x.cols,mapfun(x.arr.flat(1)))
}
if(x instanceof Complex){
const [a,b,z,phi]=[x.a,x.b,x.z,x.phi];
switch(fun){
case Math.log:return complex(ln(z),phi); // Done
case Math.exp:return complex(e(a)*cos(b),e(a)*sin(b)); // Done
case Math.abs:return z; // Done
case Math.sqrt:return complex(sqrt(z)*cos(phi/2),sqrt(z)*sin(phi/2)); // Done
case Fixed.cos:return complex(cos(a)*cosh(b),-(sin(a)*sinh(b)));
case Fixed.sin:return complex(sin(a)*cosh(b),cos(a)*sinh(b));
case Fixed.tan:{
const DEN=cos(2*a)+cosh(2*b);
return complex(sin(2*a)/DEN,sinh(2*b)/DEN);
}
case Fixed.cosh:return complex(cosh(a)*cos(b),sinh(a)*sin(b));
case Fixed.sinh:return complex(sinh(a)*cos(b),cosh(a)*sin(b));
case Fixed.tanh:{
const DEN=cosh(2*a)+cos(2*b);
return complex(sinh(2*a)/DEN,sin(2*b)/DEN)
}
default : return fun(x)
}
}
else if(x instanceof Object){
return fun(Object) || Object.fromEntries(Object.entries(x).map(n=>n=[n[0],mapfun(fun,n[1])]))
}
});
return Y.length==1?Y[0]:Y;
} | map a function to ...X
@param {function} fun
@param {...any} X
@returns {any|any[]} | mapfun | javascript | zakarialaoui10/ziko.js | src/math/utils/mapfun.js | https://github.com/zakarialaoui10/ziko.js/blob/master/src/math/utils/mapfun.js | MIT |
const cartesianProduct = (a, b) => a.reduce((p, x) => [...p, ...b.map((y) => [x, y])], []); | Computes the cartesian product of two arrays.
@param {Array} a - The first array.
@param {Array} b - The second array.
@returns {Array} Returns an array representing the cartesian product of the input arrays. | (anonymous) | javascript | zakarialaoui10/ziko.js | src/math/utils/discret.js | https://github.com/zakarialaoui10/ziko.js/blob/master/src/math/utils/discret.js | MIT |
const pgcd = (n1, n2) => {
let i,
pgcd = 1;
if (n1 == floor(n1) && n2 == floor(n2)) {
for (i = 2; i <= n1 && i <= n2; ++i) {
if (n1 % i == 0 && n2 % i == 0) pgcd = i;
}
return pgcd;
} else console.log("error");
} | Computes the greatest common divisor (GCD) of two numbers.
@param {number} n1 - The first number.
@param {number} n2 - The second number.
@returns {number} Returns the greatest common divisor of the two input numbers. | pgcd | javascript | zakarialaoui10/ziko.js | src/math/utils/discret.js | https://github.com/zakarialaoui10/ziko.js/blob/master/src/math/utils/discret.js | MIT |
const ppcm = (n1, n2) => {
let ppcm;
if (n1 == floor(n1) && n2 == floor(n2)) {
ppcm = n1 > n2 ? n1 : n2;
while (true) {
if (ppcm % n1 == 0 && ppcm % n2 == 0) break;
++ppcm;
}
return ppcm;
} else console.log("error");
} | Computes the least common multiple (LCM) of two numbers.
@param {number} n1 - The first number.
@param {number} n2 - The second number.
@returns {number} Returns the least common multiple of the two input numbers. | ppcm | javascript | zakarialaoui10/ziko.js | src/math/utils/discret.js | https://github.com/zakarialaoui10/ziko.js/blob/master/src/math/utils/discret.js | MIT |
updateFastBootManifest(manifest) {
manifest.vendorFiles.push('assets/node-asset-manifest.js');
return manifest;
}, | When using ember-engines in conjunction with ember-cli-fastboot, this will
load the Node.js version of the asset-manifest into the FastBoot sandbox.
@override | updateFastBootManifest ( manifest ) | javascript | ember-engines/ember-engines | packages/ember-engines/index.js | https://github.com/ember-engines/ember-engines/blob/master/packages/ember-engines/index.js | MIT |
function moduleMatcher(moduleName) {
return new RegExp(`define\\(['"]${moduleName}['"]`);
} | Creates a regex that matches the definition for the specified module name.
@param {String} moduleName
@return {RegExp} | moduleMatcher ( moduleName ) | javascript | ember-engines/ember-engines | packages/ember-engines/node-tests/helpers/matchers.js | https://github.com/ember-engines/ember-engines/blob/master/packages/ember-engines/node-tests/helpers/matchers.js | MIT |
function reexportMatcher(moduleName, alias) {
return new RegExp(`define.alias\\(['"]${moduleName}['"], ['"]${alias}['"]`);
} | Creates a regex that matches the alias definition for the specified reexport.
@param {String} moduleName
@param {String} alias
@return {RegExp} | reexportMatcher ( moduleName , alias ) | javascript | ember-engines/ember-engines | packages/ember-engines/node-tests/helpers/matchers.js | https://github.com/ember-engines/ember-engines/blob/master/packages/ember-engines/node-tests/helpers/matchers.js | MIT |
function cssCommentMatcher(comment) {
return new RegExp(`/\\* ${comment} \\*/`);
} | Creates a regex that matches a CSS comment with the specified content.
@param {String} moduleName
@return {RegExp} | cssCommentMatcher ( comment ) | javascript | ember-engines/ember-engines | packages/ember-engines/node-tests/helpers/matchers.js | https://github.com/ember-engines/ember-engines/blob/master/packages/ember-engines/node-tests/helpers/matchers.js | MIT |
options.ancestorHostAddons = function () {
if (this._hostAddons) {
return this._hostAddons;
}
let host = findLCAHost(this);
if (!host) {
return {};
}
let hostIsEngine = !!host.ancestorHostAddons;
let hostAddons = hostIsEngine
? Object.assign({}, host.ancestorHostAddons())
: {};
let queue = hostIsEngine
? host.addons.slice()
: host.project.addons.slice();
// Do a breadth-first walk of the addons in the host, ignoring those that
// have a different host (e.g., lazy engine)
while (queue.length) {
let addon = queue.pop();
if (addon.lazyLoading && addon.lazyLoading.enabled) {
continue;
}
if (hostAddons[addon.name]) {
continue;
}
hostAddons[addon.name] = addon;
let addons =
TARGET_INSTANCE_SYMBOL && addon[TARGET_INSTANCE_SYMBOL]
? addon[TARGET_INSTANCE_SYMBOL].addons
: addon.addons;
queue.push(...addons);
}
this._hostAddons = hostAddons;
return hostAddons;
}; | Gets a map of all the addons that are used by all hosts above
the current host. | options.ancestorHostAddons ( ) | javascript | ember-engines/ember-engines | packages/ember-engines/lib/engine-addon.js | https://github.com/ember-engines/ember-engines/blob/master/packages/ember-engines/lib/engine-addon.js | MIT |
options.updateFastBootManifest = function (manifest) {
if (this.lazyLoading.enabled) {
manifest.vendorFiles.push(
'engines-dist/' + options.name + '/assets/engine-vendor.js',
);
manifest.vendorFiles.push(
'engines-dist/' + options.name + '/assets/engine.js',
);
}
manifest.vendorFiles.push(
'engines-dist/' + options.name + '/config/environment.js',
);
return manifest;
}; | When using ember-cli-fastboot, this will ensure a lazy Engine's assets
are loaded into the FastBoot sandbox.
@override | options.updateFastBootManifest ( manifest ) | javascript | ember-engines/ember-engines | packages/ember-engines/lib/engine-addon.js | https://github.com/ember-engines/ember-engines/blob/master/packages/ember-engines/lib/engine-addon.js | MIT |
module.exports = function deeplyNonDuplicatedAddon(
hostAddons,
dedupedAddon,
treeName,
) {
if (dedupedAddon.addons.length === 0) {
return;
}
dedupedAddon._orginalAddons = dedupedAddon.addons;
dedupedAddon.addons = dedupedAddon.addons.filter((addon) => {
// nested lazy engine will have it's own deeplyNonDuplicatedAddon, just keep it here
if (addon.lazyLoading && addon.lazyLoading.enabled) {
return true;
}
if (ADDONS_TO_EXCLUDE_FROM_DEDUPE.includes(addon.name)) {
return true;
}
if (addon.addons.length > 0) {
addon._orginalAddons = addon.addons;
deeplyNonDuplicatedAddon(hostAddons, addon, treeName);
}
let hostAddon = hostAddons[addon.name];
if (hostAddon && hostAddon.cacheKeyForTree) {
let innerCacheKey = addon.cacheKeyForTree(treeName);
let hostAddonCacheKey = hostAddon.cacheKeyForTree(treeName);
if (innerCacheKey != null && innerCacheKey === hostAddonCacheKey) {
// the addon specifies cache key and it is the same as host instance of the addon, skip the tree
return false;
}
}
return true;
});
}; | Deduplicate one addon's children addons recursively from hostAddons.
@private
@param {Object} hostAddons
@param {EmberAddon} dedupedAddon
@param {String} treeName | deeplyNonDuplicatedAddon ( hostAddons , dedupedAddon , treeName , ) | javascript | ember-engines/ember-engines | packages/ember-engines/lib/utils/deeply-non-duplicated-addon.js | https://github.com/ember-engines/ember-engines/blob/master/packages/ember-engines/lib/utils/deeply-non-duplicated-addon.js | MIT |
module.exports = function shouldCompactReexports(addon, options = {}) {
if (options['ember-cli-babel'] && options['ember-cli-babel'].compileModules) {
const checker = new VersionChecker(addon);
return (
checker.for('ember-cli', 'npm').gte('2.13.0') &&
checker.for('ember-cli-babel', 'npm').gte('6.0.0') &&
checker.for('loader.js', 'npm').gte('4.4.0')
);
}
return false;
}; | Determines if ember-engines should use the compact-reexports Babel plugin.
@private
@param {EmberAddon} addon
@return {Boolean} | shouldCompactReexports ( addon , options = { } ) | javascript | ember-engines/ember-engines | packages/ember-engines/lib/utils/should-compact-reexports.js | https://github.com/ember-engines/ember-engines/blob/master/packages/ember-engines/lib/utils/should-compact-reexports.js | MIT |
function memoize(func) {
return function () {
let cacheKey = calculateCacheKeyForTree(func.name, this);
if (CACHE[cacheKey]) {
return CACHE[cacheKey];
} else {
return (CACHE[cacheKey] = func.apply(this, arguments));
}
};
} | Return the cached result of calculateCacheKeyForTree
@private
@param {Object} func
@return {Object} | memoize ( func ) | javascript | ember-engines/ember-engines | packages/ember-engines/lib/utils/memoize.js | https://github.com/ember-engines/ember-engines/blob/master/packages/ember-engines/lib/utils/memoize.js | MIT |
function getDistanceFromRoot(engine) {
let distance = 0;
let curr = engine;
while (curr !== engine.project) {
distance++;
curr = curr.parent;
}
return distance;
} | Gets the level of the engine node or the total distance
from the root
@name getDistanceFromRoot
@param {EngineAddon} engine The engine
@returns {number} The distance | getDistanceFromRoot ( engine ) | javascript | ember-engines/ember-engines | packages/ember-engines/lib/utils/find-lca-host.js | https://github.com/ember-engines/ember-engines/blob/master/packages/ember-engines/lib/utils/find-lca-host.js | MIT |
assertLinkToOrigin() {
assert(
'You attempted to use the <LinkTo> component within a routeless engine, this is not supported. ' +
'If you are using the ember-engines addon, use the <LinkToExternal> component instead. ' +
'See https://ember-engines.com/docs/links for more info.',
!this._isEngine || this._engineMountPoint !== undefined,
);
}, | Method to assert that LinkTo is not used inside of a routeless engine. This method is
overridden in ember-engines link-to-external component to just be a noop, since the
link-to-external component extends the link-to component.
@method assertLinkToOrigin
@private | assertLinkToOrigin ( ) | javascript | ember-engines/ember-engines | packages/ember-engines/addon/components/link-to-external.js | https://github.com/ember-engines/ember-engines/blob/master/packages/ember-engines/addon/components/link-to-external.js | MIT |
_getQPMeta(handlerInfo) {
let routeName = handlerInfo.name;
let isWithinEngine = this._engineInfoByRoute[routeName];
let hasBeenLoaded = this._seenHandlers[routeName];
if (isWithinEngine && !hasBeenLoaded) {
return undefined;
}
return this._super(...arguments);
}, | When going to an Engine route, we check for QP meta in the BucketCache
instead of checking the Route (which may not exist yet). We populate
the BucketCache after loading the Route the first time.
@override | _getQPMeta ( handlerInfo ) | javascript | ember-engines/ember-engines | packages/ember-engines/addon/-private/router-ext.js | https://github.com/ember-engines/ember-engines/blob/master/packages/ember-engines/addon/-private/router-ext.js | MIT |
_getHandlerFunction() {
newSetup = false;
return this._handlerResolver();
}, | We override this to fetch assets when crossing into a lazy Engine for the
first time. For other cases we do the normal thing.
@override | _getHandlerFunction ( ) | javascript | ember-engines/ember-engines | packages/ember-engines/addon/-private/router-ext.js | https://github.com/ember-engines/ember-engines/blob/master/packages/ember-engines/addon/-private/router-ext.js | MIT |
_getHandlerForEngine(seen, routeName, localRouteName, engineInstance) {
let handler = this._internalGetHandler(
seen,
routeName,
localRouteName,
engineInstance,
);
if (!hasDefaultSerialize(handler)) {
throw new Error(
'Defining a custom serialize method on an Engine route is not supported.',
);
}
return handler;
}, | Gets the handler for a route from an Engine instance, proxies to the
_internalGetHandler method.
@private
@method _getHandlerForEngine
@param {Object} seen
@param {String} routeName
@param {String} localRouteName
@param {Owner} routeOwner
@return {EngineInstance} engineInstance | _getHandlerForEngine ( seen , routeName , localRouteName , engineInstance ) | javascript | ember-engines/ember-engines | packages/ember-engines/addon/-private/router-ext.js | https://github.com/ember-engines/ember-engines/blob/master/packages/ember-engines/addon/-private/router-ext.js | MIT |
_internalGetHandler(seen, routeName, localRouteName, routeOwner) {
const fullRouteName = 'route:' + localRouteName;
let handler = routeOwner.lookup(fullRouteName);
if (seen[routeName] && handler) {
return handler;
}
seen[routeName] = true;
if (!handler) {
const DefaultRoute = routeOwner.factoryFor
? routeOwner.factoryFor('route:basic').class
: routeOwner._lookupFactory('route:basic');
routeOwner.register(fullRouteName, DefaultRoute.extend());
handler = routeOwner.lookup(fullRouteName);
if (get(this, 'namespace.LOG_ACTIVE_GENERATION')) {
// eslint-disable-next-line no-console
console.info(`generated -> ${fullRouteName}`, {
fullName: fullRouteName,
});
}
}
handler._setRouteName(localRouteName);
if (handler._populateQPMeta) {
handler._populateQPMeta();
}
return handler;
}, | This method is responsible for actually doing the lookup in getHandler.
It is separate so that it can be used from different code paths.
@private
@method _internalGetHandler
@param {Object} seen
@param {String} routeName
@param {String} localRouteName
@param {Owner} routeOwner
@return {Route} handler | _internalGetHandler ( seen , routeName , localRouteName , routeOwner ) | javascript | ember-engines/ember-engines | packages/ember-engines/addon/-private/router-ext.js | https://github.com/ember-engines/ember-engines/blob/master/packages/ember-engines/addon/-private/router-ext.js | MIT |
_engineIsLoaded(name) {
let owner = getOwner(this);
return owner.hasRegistration('engine:' + name);
}, | Checks the owner to see if it has a registration for an Engine. This is a
proxy to tell if an Engine's assets are loaded or not.
@private
@method _engineIsLoaded
@param {String} name
@return {Boolean} | _engineIsLoaded ( name ) | javascript | ember-engines/ember-engines | packages/ember-engines/addon/-private/router-ext.js | https://github.com/ember-engines/ember-engines/blob/master/packages/ember-engines/addon/-private/router-ext.js | MIT |
_registerEngine(name) {
let owner = getOwner(this);
if (!owner.hasRegistration('engine:' + name)) {
owner.register(
'engine:' + name,
window.require(name + '/engine').default,
);
}
}, | Registers an Engine that was recently loaded.
@private
@method _registerEngine
@param {String} name
@return {Void} | _registerEngine ( name ) | javascript | ember-engines/ember-engines | packages/ember-engines/addon/-private/router-ext.js | https://github.com/ember-engines/ember-engines/blob/master/packages/ember-engines/addon/-private/router-ext.js | MIT |
_getEngineInstance({ name, instanceId }) {
let engineInstances = this._engineInstances;
return engineInstances[name] && engineInstances[name][instanceId];
}, | Gets the instance of an Engine with the specified name and instanceId.
@private
@method _getEngineInstance
@param {Object} engineInfo
@param {String} engineInfo.name
@param {String} engineInfo.instanceId
@return {EngineInstance} | _getEngineInstance ( { name , instanceId } ) | javascript | ember-engines/ember-engines | packages/ember-engines/addon/-private/router-ext.js | https://github.com/ember-engines/ember-engines/blob/master/packages/ember-engines/addon/-private/router-ext.js | MIT |
_constructEngineInstance({ name, instanceId, mountPoint }) {
let owner = getOwner(this);
assert(
"You attempted to mount the engine '" +
name +
"' in your router map, but the engine cannot be found.",
owner.hasRegistration(`engine:${name}`),
);
let engineInstances = this._engineInstances;
if (!engineInstances[name]) {
engineInstances[name] = Object.create(null);
}
let engineInstance = owner.buildChildEngineInstance(name, {
routable: true,
mountPoint,
});
engineInstances[name][instanceId] = engineInstance;
return engineInstance.boot().then(() => {
return engineInstance;
});
}, | Constructs an instance of an Engine based on an engineInfo object.
TODO: Figure out if this works with nested Engines.
@private
@method _constructEngineInstance
@param {Object} engineInfo
@param {String} engineInfo.name
@param {String} engineInfo.instanceId
@param {String} engineInfo.mountPoint
@return {Promise<EngineInstance>} | _constructEngineInstance ( { name , instanceId , mountPoint } ) | javascript | ember-engines/ember-engines | packages/ember-engines/addon/-private/router-ext.js | https://github.com/ember-engines/ember-engines/blob/master/packages/ember-engines/addon/-private/router-ext.js | MIT |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.