id
int32
0
58k
repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
sequence
docstring
stringlengths
4
11.8k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
86
226
1,400
semantic-release/semantic-release
lib/git.js
repoUrl
async function repoUrl(execaOpts) { try { return await execa.stdout('git', ['config', '--get', 'remote.origin.url'], execaOpts); } catch (error) { debug(error); } }
javascript
async function repoUrl(execaOpts) { try { return await execa.stdout('git', ['config', '--get', 'remote.origin.url'], execaOpts); } catch (error) { debug(error); } }
[ "async", "function", "repoUrl", "(", "execaOpts", ")", "{", "try", "{", "return", "await", "execa", ".", "stdout", "(", "'git'", ",", "[", "'config'", ",", "'--get'", ",", "'remote.origin.url'", "]", ",", "execaOpts", ")", ";", "}", "catch", "(", "error", ")", "{", "debug", "(", "error", ")", ";", "}", "}" ]
Get the repository remote URL. @param {Object} [execaOpts] Options to pass to `execa`. @return {string} The value of the remote git URL.
[ "Get", "the", "repository", "remote", "URL", "." ]
edf382f88838ed543c0b76cb6c914cca1fc1ddd1
https://github.com/semantic-release/semantic-release/blob/edf382f88838ed543c0b76cb6c914cca1fc1ddd1/lib/git.js#L89-L95
1,401
semantic-release/semantic-release
lib/git.js
isGitRepo
async function isGitRepo(execaOpts) { try { return (await execa('git', ['rev-parse', '--git-dir'], execaOpts)).code === 0; } catch (error) { debug(error); } }
javascript
async function isGitRepo(execaOpts) { try { return (await execa('git', ['rev-parse', '--git-dir'], execaOpts)).code === 0; } catch (error) { debug(error); } }
[ "async", "function", "isGitRepo", "(", "execaOpts", ")", "{", "try", "{", "return", "(", "await", "execa", "(", "'git'", ",", "[", "'rev-parse'", ",", "'--git-dir'", "]", ",", "execaOpts", ")", ")", ".", "code", "===", "0", ";", "}", "catch", "(", "error", ")", "{", "debug", "(", "error", ")", ";", "}", "}" ]
Test if the current working directory is a Git repository. @param {Object} [execaOpts] Options to pass to `execa`. @return {Boolean} `true` if the current working directory is in a git repository, falsy otherwise.
[ "Test", "if", "the", "current", "working", "directory", "is", "a", "Git", "repository", "." ]
edf382f88838ed543c0b76cb6c914cca1fc1ddd1
https://github.com/semantic-release/semantic-release/blob/edf382f88838ed543c0b76cb6c914cca1fc1ddd1/lib/git.js#L104-L110
1,402
semantic-release/semantic-release
lib/git.js
verifyAuth
async function verifyAuth(repositoryUrl, branch, execaOpts) { try { await execa('git', ['push', '--dry-run', repositoryUrl, `HEAD:${branch}`], execaOpts); } catch (error) { debug(error); throw error; } }
javascript
async function verifyAuth(repositoryUrl, branch, execaOpts) { try { await execa('git', ['push', '--dry-run', repositoryUrl, `HEAD:${branch}`], execaOpts); } catch (error) { debug(error); throw error; } }
[ "async", "function", "verifyAuth", "(", "repositoryUrl", ",", "branch", ",", "execaOpts", ")", "{", "try", "{", "await", "execa", "(", "'git'", ",", "[", "'push'", ",", "'--dry-run'", ",", "repositoryUrl", ",", "`", "${", "branch", "}", "`", "]", ",", "execaOpts", ")", ";", "}", "catch", "(", "error", ")", "{", "debug", "(", "error", ")", ";", "throw", "error", ";", "}", "}" ]
Verify the write access authorization to remote repository with push dry-run. @param {String} repositoryUrl The remote repository URL. @param {String} branch The repositoru branch for which to verify write access. @param {Object} [execaOpts] Options to pass to `execa`. @throws {Error} if not authorized to push.
[ "Verify", "the", "write", "access", "authorization", "to", "remote", "repository", "with", "push", "dry", "-", "run", "." ]
edf382f88838ed543c0b76cb6c914cca1fc1ddd1
https://github.com/semantic-release/semantic-release/blob/edf382f88838ed543c0b76cb6c914cca1fc1ddd1/lib/git.js#L121-L128
1,403
semantic-release/semantic-release
lib/git.js
verifyTagName
async function verifyTagName(tagName, execaOpts) { try { return (await execa('git', ['check-ref-format', `refs/tags/${tagName}`], execaOpts)).code === 0; } catch (error) { debug(error); } }
javascript
async function verifyTagName(tagName, execaOpts) { try { return (await execa('git', ['check-ref-format', `refs/tags/${tagName}`], execaOpts)).code === 0; } catch (error) { debug(error); } }
[ "async", "function", "verifyTagName", "(", "tagName", ",", "execaOpts", ")", "{", "try", "{", "return", "(", "await", "execa", "(", "'git'", ",", "[", "'check-ref-format'", ",", "`", "${", "tagName", "}", "`", "]", ",", "execaOpts", ")", ")", ".", "code", "===", "0", ";", "}", "catch", "(", "error", ")", "{", "debug", "(", "error", ")", ";", "}", "}" ]
Verify a tag name is a valid Git reference. @param {String} tagName the tag name to verify. @param {Object} [execaOpts] Options to pass to `execa`. @return {Boolean} `true` if valid, falsy otherwise.
[ "Verify", "a", "tag", "name", "is", "a", "valid", "Git", "reference", "." ]
edf382f88838ed543c0b76cb6c914cca1fc1ddd1
https://github.com/semantic-release/semantic-release/blob/edf382f88838ed543c0b76cb6c914cca1fc1ddd1/lib/git.js#L162-L168
1,404
semantic-release/semantic-release
lib/git.js
isBranchUpToDate
async function isBranchUpToDate(branch, execaOpts) { const remoteHead = await execa.stdout('git', ['ls-remote', '--heads', 'origin', branch], execaOpts); try { return await isRefInHistory(remoteHead.match(/^(\w+)?/)[1], execaOpts); } catch (error) { debug(error); } }
javascript
async function isBranchUpToDate(branch, execaOpts) { const remoteHead = await execa.stdout('git', ['ls-remote', '--heads', 'origin', branch], execaOpts); try { return await isRefInHistory(remoteHead.match(/^(\w+)?/)[1], execaOpts); } catch (error) { debug(error); } }
[ "async", "function", "isBranchUpToDate", "(", "branch", ",", "execaOpts", ")", "{", "const", "remoteHead", "=", "await", "execa", ".", "stdout", "(", "'git'", ",", "[", "'ls-remote'", ",", "'--heads'", ",", "'origin'", ",", "branch", "]", ",", "execaOpts", ")", ";", "try", "{", "return", "await", "isRefInHistory", "(", "remoteHead", ".", "match", "(", "/", "^(\\w+)?", "/", ")", "[", "1", "]", ",", "execaOpts", ")", ";", "}", "catch", "(", "error", ")", "{", "debug", "(", "error", ")", ";", "}", "}" ]
Verify the local branch is up to date with the remote one. @param {String} branch The repository branch for which to verify status. @param {Object} [execaOpts] Options to pass to `execa`. @return {Boolean} `true` is the HEAD of the current local branch is the same as the HEAD of the remote branch, falsy otherwise.
[ "Verify", "the", "local", "branch", "is", "up", "to", "date", "with", "the", "remote", "one", "." ]
edf382f88838ed543c0b76cb6c914cca1fc1ddd1
https://github.com/semantic-release/semantic-release/blob/edf382f88838ed543c0b76cb6c914cca1fc1ddd1/lib/git.js#L178-L185
1,405
mochajs/mocha
lib/reporters/doc.js
Doc
function Doc(runner, options) { Base.call(this, runner, options); var indents = 2; function indent() { return Array(indents).join(' '); } runner.on(EVENT_SUITE_BEGIN, function(suite) { if (suite.root) { return; } ++indents; console.log('%s<section class="suite">', indent()); ++indents; console.log('%s<h1>%s</h1>', indent(), utils.escape(suite.title)); console.log('%s<dl>', indent()); }); runner.on(EVENT_SUITE_END, function(suite) { if (suite.root) { return; } console.log('%s</dl>', indent()); --indents; console.log('%s</section>', indent()); --indents; }); runner.on(EVENT_TEST_PASS, function(test) { console.log('%s <dt>%s</dt>', indent(), utils.escape(test.title)); var code = utils.escape(utils.clean(test.body)); console.log('%s <dd><pre><code>%s</code></pre></dd>', indent(), code); }); runner.on(EVENT_TEST_FAIL, function(test, err) { console.log( '%s <dt class="error">%s</dt>', indent(), utils.escape(test.title) ); var code = utils.escape(utils.clean(test.body)); console.log( '%s <dd class="error"><pre><code>%s</code></pre></dd>', indent(), code ); console.log('%s <dd class="error">%s</dd>', indent(), utils.escape(err)); }); }
javascript
function Doc(runner, options) { Base.call(this, runner, options); var indents = 2; function indent() { return Array(indents).join(' '); } runner.on(EVENT_SUITE_BEGIN, function(suite) { if (suite.root) { return; } ++indents; console.log('%s<section class="suite">', indent()); ++indents; console.log('%s<h1>%s</h1>', indent(), utils.escape(suite.title)); console.log('%s<dl>', indent()); }); runner.on(EVENT_SUITE_END, function(suite) { if (suite.root) { return; } console.log('%s</dl>', indent()); --indents; console.log('%s</section>', indent()); --indents; }); runner.on(EVENT_TEST_PASS, function(test) { console.log('%s <dt>%s</dt>', indent(), utils.escape(test.title)); var code = utils.escape(utils.clean(test.body)); console.log('%s <dd><pre><code>%s</code></pre></dd>', indent(), code); }); runner.on(EVENT_TEST_FAIL, function(test, err) { console.log( '%s <dt class="error">%s</dt>', indent(), utils.escape(test.title) ); var code = utils.escape(utils.clean(test.body)); console.log( '%s <dd class="error"><pre><code>%s</code></pre></dd>', indent(), code ); console.log('%s <dd class="error">%s</dd>', indent(), utils.escape(err)); }); }
[ "function", "Doc", "(", "runner", ",", "options", ")", "{", "Base", ".", "call", "(", "this", ",", "runner", ",", "options", ")", ";", "var", "indents", "=", "2", ";", "function", "indent", "(", ")", "{", "return", "Array", "(", "indents", ")", ".", "join", "(", "' '", ")", ";", "}", "runner", ".", "on", "(", "EVENT_SUITE_BEGIN", ",", "function", "(", "suite", ")", "{", "if", "(", "suite", ".", "root", ")", "{", "return", ";", "}", "++", "indents", ";", "console", ".", "log", "(", "'%s<section class=\"suite\">'", ",", "indent", "(", ")", ")", ";", "++", "indents", ";", "console", ".", "log", "(", "'%s<h1>%s</h1>'", ",", "indent", "(", ")", ",", "utils", ".", "escape", "(", "suite", ".", "title", ")", ")", ";", "console", ".", "log", "(", "'%s<dl>'", ",", "indent", "(", ")", ")", ";", "}", ")", ";", "runner", ".", "on", "(", "EVENT_SUITE_END", ",", "function", "(", "suite", ")", "{", "if", "(", "suite", ".", "root", ")", "{", "return", ";", "}", "console", ".", "log", "(", "'%s</dl>'", ",", "indent", "(", ")", ")", ";", "--", "indents", ";", "console", ".", "log", "(", "'%s</section>'", ",", "indent", "(", ")", ")", ";", "--", "indents", ";", "}", ")", ";", "runner", ".", "on", "(", "EVENT_TEST_PASS", ",", "function", "(", "test", ")", "{", "console", ".", "log", "(", "'%s <dt>%s</dt>'", ",", "indent", "(", ")", ",", "utils", ".", "escape", "(", "test", ".", "title", ")", ")", ";", "var", "code", "=", "utils", ".", "escape", "(", "utils", ".", "clean", "(", "test", ".", "body", ")", ")", ";", "console", ".", "log", "(", "'%s <dd><pre><code>%s</code></pre></dd>'", ",", "indent", "(", ")", ",", "code", ")", ";", "}", ")", ";", "runner", ".", "on", "(", "EVENT_TEST_FAIL", ",", "function", "(", "test", ",", "err", ")", "{", "console", ".", "log", "(", "'%s <dt class=\"error\">%s</dt>'", ",", "indent", "(", ")", ",", "utils", ".", "escape", "(", "test", ".", "title", ")", ")", ";", "var", "code", "=", "utils", ".", "escape", "(", "utils", ".", "clean", "(", "test", ".", "body", ")", ")", ";", "console", ".", "log", "(", "'%s <dd class=\"error\"><pre><code>%s</code></pre></dd>'", ",", "indent", "(", ")", ",", "code", ")", ";", "console", ".", "log", "(", "'%s <dd class=\"error\">%s</dd>'", ",", "indent", "(", ")", ",", "utils", ".", "escape", "(", "err", ")", ")", ";", "}", ")", ";", "}" ]
Constructs a new `Doc` reporter instance. @public @class @memberof Mocha.reporters @extends Mocha.reporters.Base @param {Runner} runner - Instance triggers reporter actions. @param {Object} [options] - runner options
[ "Constructs", "a", "new", "Doc", "reporter", "instance", "." ]
9b00fedb610241e33f7592c40164e42a38a793cf
https://github.com/mochajs/mocha/blob/9b00fedb610241e33f7592c40164e42a38a793cf/lib/reporters/doc.js#L33-L83
1,406
mochajs/mocha
lib/runnable.js
multiple
function multiple(err) { if (emitted) { return; } emitted = true; var msg = 'done() called multiple times'; if (err && err.message) { err.message += " (and Mocha's " + msg + ')'; self.emit('error', err); } else { self.emit('error', new Error(msg)); } }
javascript
function multiple(err) { if (emitted) { return; } emitted = true; var msg = 'done() called multiple times'; if (err && err.message) { err.message += " (and Mocha's " + msg + ')'; self.emit('error', err); } else { self.emit('error', new Error(msg)); } }
[ "function", "multiple", "(", "err", ")", "{", "if", "(", "emitted", ")", "{", "return", ";", "}", "emitted", "=", "true", ";", "var", "msg", "=", "'done() called multiple times'", ";", "if", "(", "err", "&&", "err", ".", "message", ")", "{", "err", ".", "message", "+=", "\" (and Mocha's \"", "+", "msg", "+", "')'", ";", "self", ".", "emit", "(", "'error'", ",", "err", ")", ";", "}", "else", "{", "self", ".", "emit", "(", "'error'", ",", "new", "Error", "(", "msg", ")", ")", ";", "}", "}" ]
called multiple times
[ "called", "multiple", "times" ]
9b00fedb610241e33f7592c40164e42a38a793cf
https://github.com/mochajs/mocha/blob/9b00fedb610241e33f7592c40164e42a38a793cf/lib/runnable.js#L303-L315
1,407
mochajs/mocha
lib/browser/growl.js
function() { // If user hasn't responded yet... "No notification for you!" (Seinfeld) Promise.race([promise, Promise.resolve(undefined)]) .then(canNotify) .then(function() { display(runner); }) .catch(notPermitted); }
javascript
function() { // If user hasn't responded yet... "No notification for you!" (Seinfeld) Promise.race([promise, Promise.resolve(undefined)]) .then(canNotify) .then(function() { display(runner); }) .catch(notPermitted); }
[ "function", "(", ")", "{", "// If user hasn't responded yet... \"No notification for you!\" (Seinfeld)", "Promise", ".", "race", "(", "[", "promise", ",", "Promise", ".", "resolve", "(", "undefined", ")", "]", ")", ".", "then", "(", "canNotify", ")", ".", "then", "(", "function", "(", ")", "{", "display", "(", "runner", ")", ";", "}", ")", ".", "catch", "(", "notPermitted", ")", ";", "}" ]
Attempt notification.
[ "Attempt", "notification", "." ]
9b00fedb610241e33f7592c40164e42a38a793cf
https://github.com/mochajs/mocha/blob/9b00fedb610241e33f7592c40164e42a38a793cf/lib/browser/growl.js#L47-L55
1,408
mochajs/mocha
lib/browser/growl.js
isPermitted
function isPermitted() { var permitted = { granted: function allow() { return Promise.resolve(true); }, denied: function deny() { return Promise.resolve(false); }, default: function ask() { return Notification.requestPermission().then(function(permission) { return permission === 'granted'; }); } }; return permitted[Notification.permission](); }
javascript
function isPermitted() { var permitted = { granted: function allow() { return Promise.resolve(true); }, denied: function deny() { return Promise.resolve(false); }, default: function ask() { return Notification.requestPermission().then(function(permission) { return permission === 'granted'; }); } }; return permitted[Notification.permission](); }
[ "function", "isPermitted", "(", ")", "{", "var", "permitted", "=", "{", "granted", ":", "function", "allow", "(", ")", "{", "return", "Promise", ".", "resolve", "(", "true", ")", ";", "}", ",", "denied", ":", "function", "deny", "(", ")", "{", "return", "Promise", ".", "resolve", "(", "false", ")", ";", "}", ",", "default", ":", "function", "ask", "(", ")", "{", "return", "Notification", ".", "requestPermission", "(", ")", ".", "then", "(", "function", "(", "permission", ")", "{", "return", "permission", "===", "'granted'", ";", "}", ")", ";", "}", "}", ";", "return", "permitted", "[", "Notification", ".", "permission", "]", "(", ")", ";", "}" ]
Checks if browser notification is permitted by user. @private @see {@link https://developer.mozilla.org/en-US/docs/Web/API/Notification/permission|Notification.permission} @see {@link Mocha#growl} @see {@link Mocha#isGrowlPermitted} @returns {Promise<boolean>} promise determining if browser notification permissible when fulfilled.
[ "Checks", "if", "browser", "notification", "is", "permitted", "by", "user", "." ]
9b00fedb610241e33f7592c40164e42a38a793cf
https://github.com/mochajs/mocha/blob/9b00fedb610241e33f7592c40164e42a38a793cf/lib/browser/growl.js#L70-L86
1,409
mochajs/mocha
lib/browser/growl.js
display
function display(runner) { var stats = runner.stats; var symbol = { cross: '\u274C', tick: '\u2705' }; var logo = require('../../package').notifyLogo; var _message; var message; var title; if (stats.failures) { _message = stats.failures + ' of ' + stats.tests + ' tests failed'; message = symbol.cross + ' ' + _message; title = 'Failed'; } else { _message = stats.passes + ' tests passed in ' + stats.duration + 'ms'; message = symbol.tick + ' ' + _message; title = 'Passed'; } // Send notification var options = { badge: logo, body: message, dir: 'ltr', icon: logo, lang: 'en-US', name: 'mocha', requireInteraction: false, timestamp: Date.now() }; var notification = new Notification(title, options); // Autoclose after brief delay (makes various browsers act same) var FORCE_DURATION = 4000; setTimeout(notification.close.bind(notification), FORCE_DURATION); }
javascript
function display(runner) { var stats = runner.stats; var symbol = { cross: '\u274C', tick: '\u2705' }; var logo = require('../../package').notifyLogo; var _message; var message; var title; if (stats.failures) { _message = stats.failures + ' of ' + stats.tests + ' tests failed'; message = symbol.cross + ' ' + _message; title = 'Failed'; } else { _message = stats.passes + ' tests passed in ' + stats.duration + 'ms'; message = symbol.tick + ' ' + _message; title = 'Passed'; } // Send notification var options = { badge: logo, body: message, dir: 'ltr', icon: logo, lang: 'en-US', name: 'mocha', requireInteraction: false, timestamp: Date.now() }; var notification = new Notification(title, options); // Autoclose after brief delay (makes various browsers act same) var FORCE_DURATION = 4000; setTimeout(notification.close.bind(notification), FORCE_DURATION); }
[ "function", "display", "(", "runner", ")", "{", "var", "stats", "=", "runner", ".", "stats", ";", "var", "symbol", "=", "{", "cross", ":", "'\\u274C'", ",", "tick", ":", "'\\u2705'", "}", ";", "var", "logo", "=", "require", "(", "'../../package'", ")", ".", "notifyLogo", ";", "var", "_message", ";", "var", "message", ";", "var", "title", ";", "if", "(", "stats", ".", "failures", ")", "{", "_message", "=", "stats", ".", "failures", "+", "' of '", "+", "stats", ".", "tests", "+", "' tests failed'", ";", "message", "=", "symbol", ".", "cross", "+", "' '", "+", "_message", ";", "title", "=", "'Failed'", ";", "}", "else", "{", "_message", "=", "stats", ".", "passes", "+", "' tests passed in '", "+", "stats", ".", "duration", "+", "'ms'", ";", "message", "=", "symbol", ".", "tick", "+", "' '", "+", "_message", ";", "title", "=", "'Passed'", ";", "}", "// Send notification", "var", "options", "=", "{", "badge", ":", "logo", ",", "body", ":", "message", ",", "dir", ":", "'ltr'", ",", "icon", ":", "logo", ",", "lang", ":", "'en-US'", ",", "name", ":", "'mocha'", ",", "requireInteraction", ":", "false", ",", "timestamp", ":", "Date", ".", "now", "(", ")", "}", ";", "var", "notification", "=", "new", "Notification", "(", "title", ",", "options", ")", ";", "// Autoclose after brief delay (makes various browsers act same)", "var", "FORCE_DURATION", "=", "4000", ";", "setTimeout", "(", "notification", ".", "close", ".", "bind", "(", "notification", ")", ",", "FORCE_DURATION", ")", ";", "}" ]
Displays the notification. @private @param {Runner} runner - Runner instance.
[ "Displays", "the", "notification", "." ]
9b00fedb610241e33f7592c40164e42a38a793cf
https://github.com/mochajs/mocha/blob/9b00fedb610241e33f7592c40164e42a38a793cf/lib/browser/growl.js#L121-L158
1,410
mochajs/mocha
lib/suite.js
Suite
function Suite(title, parentContext, isRoot) { if (!utils.isString(title)) { throw createInvalidArgumentTypeError( 'Suite argument "title" must be a string. Received type "' + typeof title + '"', 'title', 'string' ); } this.title = title; function Context() {} Context.prototype = parentContext; this.ctx = new Context(); this.suites = []; this.tests = []; this.pending = false; this._beforeEach = []; this._beforeAll = []; this._afterEach = []; this._afterAll = []; this.root = isRoot === true; this._timeout = 2000; this._enableTimeouts = true; this._slow = 75; this._bail = false; this._retries = -1; this._onlyTests = []; this._onlySuites = []; this.delayed = false; this.on('newListener', function(event) { if (deprecatedEvents[event]) { utils.deprecate( 'Event "' + event + '" is deprecated. Please let the Mocha team know about your use case: https://git.io/v6Lwm' ); } }); }
javascript
function Suite(title, parentContext, isRoot) { if (!utils.isString(title)) { throw createInvalidArgumentTypeError( 'Suite argument "title" must be a string. Received type "' + typeof title + '"', 'title', 'string' ); } this.title = title; function Context() {} Context.prototype = parentContext; this.ctx = new Context(); this.suites = []; this.tests = []; this.pending = false; this._beforeEach = []; this._beforeAll = []; this._afterEach = []; this._afterAll = []; this.root = isRoot === true; this._timeout = 2000; this._enableTimeouts = true; this._slow = 75; this._bail = false; this._retries = -1; this._onlyTests = []; this._onlySuites = []; this.delayed = false; this.on('newListener', function(event) { if (deprecatedEvents[event]) { utils.deprecate( 'Event "' + event + '" is deprecated. Please let the Mocha team know about your use case: https://git.io/v6Lwm' ); } }); }
[ "function", "Suite", "(", "title", ",", "parentContext", ",", "isRoot", ")", "{", "if", "(", "!", "utils", ".", "isString", "(", "title", ")", ")", "{", "throw", "createInvalidArgumentTypeError", "(", "'Suite argument \"title\" must be a string. Received type \"'", "+", "typeof", "title", "+", "'\"'", ",", "'title'", ",", "'string'", ")", ";", "}", "this", ".", "title", "=", "title", ";", "function", "Context", "(", ")", "{", "}", "Context", ".", "prototype", "=", "parentContext", ";", "this", ".", "ctx", "=", "new", "Context", "(", ")", ";", "this", ".", "suites", "=", "[", "]", ";", "this", ".", "tests", "=", "[", "]", ";", "this", ".", "pending", "=", "false", ";", "this", ".", "_beforeEach", "=", "[", "]", ";", "this", ".", "_beforeAll", "=", "[", "]", ";", "this", ".", "_afterEach", "=", "[", "]", ";", "this", ".", "_afterAll", "=", "[", "]", ";", "this", ".", "root", "=", "isRoot", "===", "true", ";", "this", ".", "_timeout", "=", "2000", ";", "this", ".", "_enableTimeouts", "=", "true", ";", "this", ".", "_slow", "=", "75", ";", "this", ".", "_bail", "=", "false", ";", "this", ".", "_retries", "=", "-", "1", ";", "this", ".", "_onlyTests", "=", "[", "]", ";", "this", ".", "_onlySuites", "=", "[", "]", ";", "this", ".", "delayed", "=", "false", ";", "this", ".", "on", "(", "'newListener'", ",", "function", "(", "event", ")", "{", "if", "(", "deprecatedEvents", "[", "event", "]", ")", "{", "utils", ".", "deprecate", "(", "'Event \"'", "+", "event", "+", "'\" is deprecated. Please let the Mocha team know about your use case: https://git.io/v6Lwm'", ")", ";", "}", "}", ")", ";", "}" ]
Constructs a new `Suite` instance with the given `title`, `ctx`, and `isRoot`. @public @class @extends EventEmitter @see {@link https://nodejs.org/api/events.html#events_class_eventemitter|EventEmitter} @param {string} title - Suite title. @param {Context} parentContext - Parent context instance. @param {boolean} [isRoot=false] - Whether this is the root suite.
[ "Constructs", "a", "new", "Suite", "instance", "with", "the", "given", "title", "ctx", "and", "isRoot", "." ]
9b00fedb610241e33f7592c40164e42a38a793cf
https://github.com/mochajs/mocha/blob/9b00fedb610241e33f7592c40164e42a38a793cf/lib/suite.js#L48-L88
1,411
mochajs/mocha
lib/reporters/json.js
JSONReporter
function JSONReporter(runner, options) { Base.call(this, runner, options); var self = this; var tests = []; var pending = []; var failures = []; var passes = []; runner.on(EVENT_TEST_END, function(test) { tests.push(test); }); runner.on(EVENT_TEST_PASS, function(test) { passes.push(test); }); runner.on(EVENT_TEST_FAIL, function(test) { failures.push(test); }); runner.on(EVENT_TEST_PENDING, function(test) { pending.push(test); }); runner.once(EVENT_RUN_END, function() { var obj = { stats: self.stats, tests: tests.map(clean), pending: pending.map(clean), failures: failures.map(clean), passes: passes.map(clean) }; runner.testResults = obj; process.stdout.write(JSON.stringify(obj, null, 2)); }); }
javascript
function JSONReporter(runner, options) { Base.call(this, runner, options); var self = this; var tests = []; var pending = []; var failures = []; var passes = []; runner.on(EVENT_TEST_END, function(test) { tests.push(test); }); runner.on(EVENT_TEST_PASS, function(test) { passes.push(test); }); runner.on(EVENT_TEST_FAIL, function(test) { failures.push(test); }); runner.on(EVENT_TEST_PENDING, function(test) { pending.push(test); }); runner.once(EVENT_RUN_END, function() { var obj = { stats: self.stats, tests: tests.map(clean), pending: pending.map(clean), failures: failures.map(clean), passes: passes.map(clean) }; runner.testResults = obj; process.stdout.write(JSON.stringify(obj, null, 2)); }); }
[ "function", "JSONReporter", "(", "runner", ",", "options", ")", "{", "Base", ".", "call", "(", "this", ",", "runner", ",", "options", ")", ";", "var", "self", "=", "this", ";", "var", "tests", "=", "[", "]", ";", "var", "pending", "=", "[", "]", ";", "var", "failures", "=", "[", "]", ";", "var", "passes", "=", "[", "]", ";", "runner", ".", "on", "(", "EVENT_TEST_END", ",", "function", "(", "test", ")", "{", "tests", ".", "push", "(", "test", ")", ";", "}", ")", ";", "runner", ".", "on", "(", "EVENT_TEST_PASS", ",", "function", "(", "test", ")", "{", "passes", ".", "push", "(", "test", ")", ";", "}", ")", ";", "runner", ".", "on", "(", "EVENT_TEST_FAIL", ",", "function", "(", "test", ")", "{", "failures", ".", "push", "(", "test", ")", ";", "}", ")", ";", "runner", ".", "on", "(", "EVENT_TEST_PENDING", ",", "function", "(", "test", ")", "{", "pending", ".", "push", "(", "test", ")", ";", "}", ")", ";", "runner", ".", "once", "(", "EVENT_RUN_END", ",", "function", "(", ")", "{", "var", "obj", "=", "{", "stats", ":", "self", ".", "stats", ",", "tests", ":", "tests", ".", "map", "(", "clean", ")", ",", "pending", ":", "pending", ".", "map", "(", "clean", ")", ",", "failures", ":", "failures", ".", "map", "(", "clean", ")", ",", "passes", ":", "passes", ".", "map", "(", "clean", ")", "}", ";", "runner", ".", "testResults", "=", "obj", ";", "process", ".", "stdout", ".", "write", "(", "JSON", ".", "stringify", "(", "obj", ",", "null", ",", "2", ")", ")", ";", "}", ")", ";", "}" ]
Constructs a new `JSON` reporter instance. @public @class JSON @memberof Mocha.reporters @extends Mocha.reporters.Base @param {Runner} runner - Instance triggers reporter actions. @param {Object} [options] - runner options
[ "Constructs", "a", "new", "JSON", "reporter", "instance", "." ]
9b00fedb610241e33f7592c40164e42a38a793cf
https://github.com/mochajs/mocha/blob/9b00fedb610241e33f7592c40164e42a38a793cf/lib/reporters/json.js#L33-L71
1,412
mochajs/mocha
lib/reporters/json.js
clean
function clean(test) { var err = test.err || {}; if (err instanceof Error) { err = errorJSON(err); } return { title: test.title, fullTitle: test.fullTitle(), duration: test.duration, currentRetry: test.currentRetry(), err: cleanCycles(err) }; }
javascript
function clean(test) { var err = test.err || {}; if (err instanceof Error) { err = errorJSON(err); } return { title: test.title, fullTitle: test.fullTitle(), duration: test.duration, currentRetry: test.currentRetry(), err: cleanCycles(err) }; }
[ "function", "clean", "(", "test", ")", "{", "var", "err", "=", "test", ".", "err", "||", "{", "}", ";", "if", "(", "err", "instanceof", "Error", ")", "{", "err", "=", "errorJSON", "(", "err", ")", ";", "}", "return", "{", "title", ":", "test", ".", "title", ",", "fullTitle", ":", "test", ".", "fullTitle", "(", ")", ",", "duration", ":", "test", ".", "duration", ",", "currentRetry", ":", "test", ".", "currentRetry", "(", ")", ",", "err", ":", "cleanCycles", "(", "err", ")", "}", ";", "}" ]
Return a plain-object representation of `test` free of cyclic properties etc. @private @param {Object} test @return {Object}
[ "Return", "a", "plain", "-", "object", "representation", "of", "test", "free", "of", "cyclic", "properties", "etc", "." ]
9b00fedb610241e33f7592c40164e42a38a793cf
https://github.com/mochajs/mocha/blob/9b00fedb610241e33f7592c40164e42a38a793cf/lib/reporters/json.js#L81-L94
1,413
mochajs/mocha
lib/reporters/xunit.js
XUnit
function XUnit(runner, options) { Base.call(this, runner, options); var stats = this.stats; var tests = []; var self = this; // the name of the test suite, as it will appear in the resulting XML file var suiteName; // the default name of the test suite if none is provided var DEFAULT_SUITE_NAME = 'Mocha Tests'; if (options && options.reporterOptions) { if (options.reporterOptions.output) { if (!fs.createWriteStream) { throw createUnsupportedError('file output not supported in browser'); } mkdirp.sync(path.dirname(options.reporterOptions.output)); self.fileStream = fs.createWriteStream(options.reporterOptions.output); } // get the suite name from the reporter options (if provided) suiteName = options.reporterOptions.suiteName; } // fall back to the default suite name suiteName = suiteName || DEFAULT_SUITE_NAME; runner.on(EVENT_TEST_PENDING, function(test) { tests.push(test); }); runner.on(EVENT_TEST_PASS, function(test) { tests.push(test); }); runner.on(EVENT_TEST_FAIL, function(test) { tests.push(test); }); runner.once(EVENT_RUN_END, function() { self.write( tag( 'testsuite', { name: suiteName, tests: stats.tests, failures: 0, errors: stats.failures, skipped: stats.tests - stats.failures - stats.passes, timestamp: new Date().toUTCString(), time: stats.duration / 1000 || 0 }, false ) ); tests.forEach(function(t) { self.test(t); }); self.write('</testsuite>'); }); }
javascript
function XUnit(runner, options) { Base.call(this, runner, options); var stats = this.stats; var tests = []; var self = this; // the name of the test suite, as it will appear in the resulting XML file var suiteName; // the default name of the test suite if none is provided var DEFAULT_SUITE_NAME = 'Mocha Tests'; if (options && options.reporterOptions) { if (options.reporterOptions.output) { if (!fs.createWriteStream) { throw createUnsupportedError('file output not supported in browser'); } mkdirp.sync(path.dirname(options.reporterOptions.output)); self.fileStream = fs.createWriteStream(options.reporterOptions.output); } // get the suite name from the reporter options (if provided) suiteName = options.reporterOptions.suiteName; } // fall back to the default suite name suiteName = suiteName || DEFAULT_SUITE_NAME; runner.on(EVENT_TEST_PENDING, function(test) { tests.push(test); }); runner.on(EVENT_TEST_PASS, function(test) { tests.push(test); }); runner.on(EVENT_TEST_FAIL, function(test) { tests.push(test); }); runner.once(EVENT_RUN_END, function() { self.write( tag( 'testsuite', { name: suiteName, tests: stats.tests, failures: 0, errors: stats.failures, skipped: stats.tests - stats.failures - stats.passes, timestamp: new Date().toUTCString(), time: stats.duration / 1000 || 0 }, false ) ); tests.forEach(function(t) { self.test(t); }); self.write('</testsuite>'); }); }
[ "function", "XUnit", "(", "runner", ",", "options", ")", "{", "Base", ".", "call", "(", "this", ",", "runner", ",", "options", ")", ";", "var", "stats", "=", "this", ".", "stats", ";", "var", "tests", "=", "[", "]", ";", "var", "self", "=", "this", ";", "// the name of the test suite, as it will appear in the resulting XML file", "var", "suiteName", ";", "// the default name of the test suite if none is provided", "var", "DEFAULT_SUITE_NAME", "=", "'Mocha Tests'", ";", "if", "(", "options", "&&", "options", ".", "reporterOptions", ")", "{", "if", "(", "options", ".", "reporterOptions", ".", "output", ")", "{", "if", "(", "!", "fs", ".", "createWriteStream", ")", "{", "throw", "createUnsupportedError", "(", "'file output not supported in browser'", ")", ";", "}", "mkdirp", ".", "sync", "(", "path", ".", "dirname", "(", "options", ".", "reporterOptions", ".", "output", ")", ")", ";", "self", ".", "fileStream", "=", "fs", ".", "createWriteStream", "(", "options", ".", "reporterOptions", ".", "output", ")", ";", "}", "// get the suite name from the reporter options (if provided)", "suiteName", "=", "options", ".", "reporterOptions", ".", "suiteName", ";", "}", "// fall back to the default suite name", "suiteName", "=", "suiteName", "||", "DEFAULT_SUITE_NAME", ";", "runner", ".", "on", "(", "EVENT_TEST_PENDING", ",", "function", "(", "test", ")", "{", "tests", ".", "push", "(", "test", ")", ";", "}", ")", ";", "runner", ".", "on", "(", "EVENT_TEST_PASS", ",", "function", "(", "test", ")", "{", "tests", ".", "push", "(", "test", ")", ";", "}", ")", ";", "runner", ".", "on", "(", "EVENT_TEST_FAIL", ",", "function", "(", "test", ")", "{", "tests", ".", "push", "(", "test", ")", ";", "}", ")", ";", "runner", ".", "once", "(", "EVENT_RUN_END", ",", "function", "(", ")", "{", "self", ".", "write", "(", "tag", "(", "'testsuite'", ",", "{", "name", ":", "suiteName", ",", "tests", ":", "stats", ".", "tests", ",", "failures", ":", "0", ",", "errors", ":", "stats", ".", "failures", ",", "skipped", ":", "stats", ".", "tests", "-", "stats", ".", "failures", "-", "stats", ".", "passes", ",", "timestamp", ":", "new", "Date", "(", ")", ".", "toUTCString", "(", ")", ",", "time", ":", "stats", ".", "duration", "/", "1000", "||", "0", "}", ",", "false", ")", ")", ";", "tests", ".", "forEach", "(", "function", "(", "t", ")", "{", "self", ".", "test", "(", "t", ")", ";", "}", ")", ";", "self", ".", "write", "(", "'</testsuite>'", ")", ";", "}", ")", ";", "}" ]
Constructs a new `XUnit` reporter instance. @public @class @memberof Mocha.reporters @extends Mocha.reporters.Base @param {Runner} runner - Instance triggers reporter actions. @param {Object} [options] - runner options
[ "Constructs", "a", "new", "XUnit", "reporter", "instance", "." ]
9b00fedb610241e33f7592c40164e42a38a793cf
https://github.com/mochajs/mocha/blob/9b00fedb610241e33f7592c40164e42a38a793cf/lib/reporters/xunit.js#L46-L111
1,414
mochajs/mocha
lib/reporters/base.js
Base
function Base(runner, options) { var failures = (this.failures = []); if (!runner) { throw new TypeError('Missing runner argument'); } this.options = options || {}; this.runner = runner; this.stats = runner.stats; // assigned so Reporters keep a closer reference runner.on(EVENT_TEST_PASS, function(test) { if (test.duration > test.slow()) { test.speed = 'slow'; } else if (test.duration > test.slow() / 2) { test.speed = 'medium'; } else { test.speed = 'fast'; } }); runner.on(EVENT_TEST_FAIL, function(test, err) { if (showDiff(err)) { stringifyDiffObjs(err); } test.err = err; failures.push(test); }); }
javascript
function Base(runner, options) { var failures = (this.failures = []); if (!runner) { throw new TypeError('Missing runner argument'); } this.options = options || {}; this.runner = runner; this.stats = runner.stats; // assigned so Reporters keep a closer reference runner.on(EVENT_TEST_PASS, function(test) { if (test.duration > test.slow()) { test.speed = 'slow'; } else if (test.duration > test.slow() / 2) { test.speed = 'medium'; } else { test.speed = 'fast'; } }); runner.on(EVENT_TEST_FAIL, function(test, err) { if (showDiff(err)) { stringifyDiffObjs(err); } test.err = err; failures.push(test); }); }
[ "function", "Base", "(", "runner", ",", "options", ")", "{", "var", "failures", "=", "(", "this", ".", "failures", "=", "[", "]", ")", ";", "if", "(", "!", "runner", ")", "{", "throw", "new", "TypeError", "(", "'Missing runner argument'", ")", ";", "}", "this", ".", "options", "=", "options", "||", "{", "}", ";", "this", ".", "runner", "=", "runner", ";", "this", ".", "stats", "=", "runner", ".", "stats", ";", "// assigned so Reporters keep a closer reference", "runner", ".", "on", "(", "EVENT_TEST_PASS", ",", "function", "(", "test", ")", "{", "if", "(", "test", ".", "duration", ">", "test", ".", "slow", "(", ")", ")", "{", "test", ".", "speed", "=", "'slow'", ";", "}", "else", "if", "(", "test", ".", "duration", ">", "test", ".", "slow", "(", ")", "/", "2", ")", "{", "test", ".", "speed", "=", "'medium'", ";", "}", "else", "{", "test", ".", "speed", "=", "'fast'", ";", "}", "}", ")", ";", "runner", ".", "on", "(", "EVENT_TEST_FAIL", ",", "function", "(", "test", ",", "err", ")", "{", "if", "(", "showDiff", "(", "err", ")", ")", "{", "stringifyDiffObjs", "(", "err", ")", ";", "}", "test", ".", "err", "=", "err", ";", "failures", ".", "push", "(", "test", ")", ";", "}", ")", ";", "}" ]
Constructs a new `Base` reporter instance. @description All other reporters generally inherit from this reporter. @public @class @memberof Mocha.reporters @param {Runner} runner - Instance triggers reporter actions. @param {Object} [options] - runner options
[ "Constructs", "a", "new", "Base", "reporter", "instance", "." ]
9b00fedb610241e33f7592c40164e42a38a793cf
https://github.com/mochajs/mocha/blob/9b00fedb610241e33f7592c40164e42a38a793cf/lib/reporters/base.js#L272-L299
1,415
mochajs/mocha
lib/reporters/base.js
errorDiff
function errorDiff(actual, expected) { return diff .diffWordsWithSpace(actual, expected) .map(function(str) { if (str.added) { return colorLines('diff added', str.value); } if (str.removed) { return colorLines('diff removed', str.value); } return str.value; }) .join(''); }
javascript
function errorDiff(actual, expected) { return diff .diffWordsWithSpace(actual, expected) .map(function(str) { if (str.added) { return colorLines('diff added', str.value); } if (str.removed) { return colorLines('diff removed', str.value); } return str.value; }) .join(''); }
[ "function", "errorDiff", "(", "actual", ",", "expected", ")", "{", "return", "diff", ".", "diffWordsWithSpace", "(", "actual", ",", "expected", ")", ".", "map", "(", "function", "(", "str", ")", "{", "if", "(", "str", ".", "added", ")", "{", "return", "colorLines", "(", "'diff added'", ",", "str", ".", "value", ")", ";", "}", "if", "(", "str", ".", "removed", ")", "{", "return", "colorLines", "(", "'diff removed'", ",", "str", ".", "value", ")", ";", "}", "return", "str", ".", "value", ";", "}", ")", ".", "join", "(", "''", ")", ";", "}" ]
Returns character diff for `err`. @private @param {String} actual @param {String} expected @return {string} the diff
[ "Returns", "character", "diff", "for", "err", "." ]
9b00fedb610241e33f7592c40164e42a38a793cf
https://github.com/mochajs/mocha/blob/9b00fedb610241e33f7592c40164e42a38a793cf/lib/reporters/base.js#L442-L455
1,416
mochajs/mocha
lib/reporters/base.js
colorLines
function colorLines(name, str) { return str .split('\n') .map(function(str) { return color(name, str); }) .join('\n'); }
javascript
function colorLines(name, str) { return str .split('\n') .map(function(str) { return color(name, str); }) .join('\n'); }
[ "function", "colorLines", "(", "name", ",", "str", ")", "{", "return", "str", ".", "split", "(", "'\\n'", ")", ".", "map", "(", "function", "(", "str", ")", "{", "return", "color", "(", "name", ",", "str", ")", ";", "}", ")", ".", "join", "(", "'\\n'", ")", ";", "}" ]
Colors lines for `str`, using the color `name`. @private @param {string} name @param {string} str @return {string}
[ "Colors", "lines", "for", "str", "using", "the", "color", "name", "." ]
9b00fedb610241e33f7592c40164e42a38a793cf
https://github.com/mochajs/mocha/blob/9b00fedb610241e33f7592c40164e42a38a793cf/lib/reporters/base.js#L465-L472
1,417
mochajs/mocha
lib/reporters/tap.js
TAP
function TAP(runner, options) { Base.call(this, runner, options); var self = this; var n = 1; var tapVersion = '12'; if (options && options.reporterOptions) { if (options.reporterOptions.tapVersion) { tapVersion = options.reporterOptions.tapVersion.toString(); } } this._producer = createProducer(tapVersion); runner.once(EVENT_RUN_BEGIN, function() { var ntests = runner.grepTotal(runner.suite); self._producer.writeVersion(); self._producer.writePlan(ntests); }); runner.on(EVENT_TEST_END, function() { ++n; }); runner.on(EVENT_TEST_PENDING, function(test) { self._producer.writePending(n, test); }); runner.on(EVENT_TEST_PASS, function(test) { self._producer.writePass(n, test); }); runner.on(EVENT_TEST_FAIL, function(test, err) { self._producer.writeFail(n, test, err); }); runner.once(EVENT_RUN_END, function() { self._producer.writeEpilogue(runner.stats); }); }
javascript
function TAP(runner, options) { Base.call(this, runner, options); var self = this; var n = 1; var tapVersion = '12'; if (options && options.reporterOptions) { if (options.reporterOptions.tapVersion) { tapVersion = options.reporterOptions.tapVersion.toString(); } } this._producer = createProducer(tapVersion); runner.once(EVENT_RUN_BEGIN, function() { var ntests = runner.grepTotal(runner.suite); self._producer.writeVersion(); self._producer.writePlan(ntests); }); runner.on(EVENT_TEST_END, function() { ++n; }); runner.on(EVENT_TEST_PENDING, function(test) { self._producer.writePending(n, test); }); runner.on(EVENT_TEST_PASS, function(test) { self._producer.writePass(n, test); }); runner.on(EVENT_TEST_FAIL, function(test, err) { self._producer.writeFail(n, test, err); }); runner.once(EVENT_RUN_END, function() { self._producer.writeEpilogue(runner.stats); }); }
[ "function", "TAP", "(", "runner", ",", "options", ")", "{", "Base", ".", "call", "(", "this", ",", "runner", ",", "options", ")", ";", "var", "self", "=", "this", ";", "var", "n", "=", "1", ";", "var", "tapVersion", "=", "'12'", ";", "if", "(", "options", "&&", "options", ".", "reporterOptions", ")", "{", "if", "(", "options", ".", "reporterOptions", ".", "tapVersion", ")", "{", "tapVersion", "=", "options", ".", "reporterOptions", ".", "tapVersion", ".", "toString", "(", ")", ";", "}", "}", "this", ".", "_producer", "=", "createProducer", "(", "tapVersion", ")", ";", "runner", ".", "once", "(", "EVENT_RUN_BEGIN", ",", "function", "(", ")", "{", "var", "ntests", "=", "runner", ".", "grepTotal", "(", "runner", ".", "suite", ")", ";", "self", ".", "_producer", ".", "writeVersion", "(", ")", ";", "self", ".", "_producer", ".", "writePlan", "(", "ntests", ")", ";", "}", ")", ";", "runner", ".", "on", "(", "EVENT_TEST_END", ",", "function", "(", ")", "{", "++", "n", ";", "}", ")", ";", "runner", ".", "on", "(", "EVENT_TEST_PENDING", ",", "function", "(", "test", ")", "{", "self", ".", "_producer", ".", "writePending", "(", "n", ",", "test", ")", ";", "}", ")", ";", "runner", ".", "on", "(", "EVENT_TEST_PASS", ",", "function", "(", "test", ")", "{", "self", ".", "_producer", ".", "writePass", "(", "n", ",", "test", ")", ";", "}", ")", ";", "runner", ".", "on", "(", "EVENT_TEST_FAIL", ",", "function", "(", "test", ",", "err", ")", "{", "self", ".", "_producer", ".", "writeFail", "(", "n", ",", "test", ",", "err", ")", ";", "}", ")", ";", "runner", ".", "once", "(", "EVENT_RUN_END", ",", "function", "(", ")", "{", "self", ".", "_producer", ".", "writeEpilogue", "(", "runner", ".", "stats", ")", ";", "}", ")", ";", "}" ]
Constructs a new `TAP` reporter instance. @public @class @memberof Mocha.reporters @extends Mocha.reporters.Base @param {Runner} runner - Instance triggers reporter actions. @param {Object} [options] - runner options
[ "Constructs", "a", "new", "TAP", "reporter", "instance", "." ]
9b00fedb610241e33f7592c40164e42a38a793cf
https://github.com/mochajs/mocha/blob/9b00fedb610241e33f7592c40164e42a38a793cf/lib/reporters/tap.js#L37-L77
1,418
mochajs/mocha
lib/reporters/tap.js
println
function println(format, varArgs) { var vargs = Array.from(arguments); vargs[0] += '\n'; process.stdout.write(sprintf.apply(null, vargs)); }
javascript
function println(format, varArgs) { var vargs = Array.from(arguments); vargs[0] += '\n'; process.stdout.write(sprintf.apply(null, vargs)); }
[ "function", "println", "(", "format", ",", "varArgs", ")", "{", "var", "vargs", "=", "Array", ".", "from", "(", "arguments", ")", ";", "vargs", "[", "0", "]", "+=", "'\\n'", ";", "process", ".", "stdout", ".", "write", "(", "sprintf", ".", "apply", "(", "null", ",", "vargs", ")", ")", ";", "}" ]
Writes newline-terminated formatted string to reporter output stream. @private @param {string} format - `printf`-like format string @param {...*} [varArgs] - Format string arguments
[ "Writes", "newline", "-", "terminated", "formatted", "string", "to", "reporter", "output", "stream", "." ]
9b00fedb610241e33f7592c40164e42a38a793cf
https://github.com/mochajs/mocha/blob/9b00fedb610241e33f7592c40164e42a38a793cf/lib/reporters/tap.js#L102-L106
1,419
mochajs/mocha
lib/reporters/tap.js
createProducer
function createProducer(tapVersion) { var producers = { '12': new TAP12Producer(), '13': new TAP13Producer() }; var producer = producers[tapVersion]; if (!producer) { throw new Error( 'invalid or unsupported TAP version: ' + JSON.stringify(tapVersion) ); } return producer; }
javascript
function createProducer(tapVersion) { var producers = { '12': new TAP12Producer(), '13': new TAP13Producer() }; var producer = producers[tapVersion]; if (!producer) { throw new Error( 'invalid or unsupported TAP version: ' + JSON.stringify(tapVersion) ); } return producer; }
[ "function", "createProducer", "(", "tapVersion", ")", "{", "var", "producers", "=", "{", "'12'", ":", "new", "TAP12Producer", "(", ")", ",", "'13'", ":", "new", "TAP13Producer", "(", ")", "}", ";", "var", "producer", "=", "producers", "[", "tapVersion", "]", ";", "if", "(", "!", "producer", ")", "{", "throw", "new", "Error", "(", "'invalid or unsupported TAP version: '", "+", "JSON", ".", "stringify", "(", "tapVersion", ")", ")", ";", "}", "return", "producer", ";", "}" ]
Returns a `tapVersion`-appropriate TAP producer instance, if possible. @private @param {string} tapVersion - Version of TAP specification to produce. @returns {TAPProducer} specification-appropriate instance @throws {Error} if specification version has no associated producer.
[ "Returns", "a", "tapVersion", "-", "appropriate", "TAP", "producer", "instance", "if", "possible", "." ]
9b00fedb610241e33f7592c40164e42a38a793cf
https://github.com/mochajs/mocha/blob/9b00fedb610241e33f7592c40164e42a38a793cf/lib/reporters/tap.js#L116-L130
1,420
mochajs/mocha
lib/reporters/nyan.js
NyanCat
function NyanCat(runner, options) { Base.call(this, runner, options); var self = this; var width = (Base.window.width * 0.75) | 0; var nyanCatWidth = (this.nyanCatWidth = 11); this.colorIndex = 0; this.numberOfLines = 4; this.rainbowColors = self.generateColors(); this.scoreboardWidth = 5; this.tick = 0; this.trajectories = [[], [], [], []]; this.trajectoryWidthMax = width - nyanCatWidth; runner.on(EVENT_RUN_BEGIN, function() { Base.cursor.hide(); self.draw(); }); runner.on(EVENT_TEST_PENDING, function() { self.draw(); }); runner.on(EVENT_TEST_PASS, function() { self.draw(); }); runner.on(EVENT_TEST_FAIL, function() { self.draw(); }); runner.once(EVENT_RUN_END, function() { Base.cursor.show(); for (var i = 0; i < self.numberOfLines; i++) { write('\n'); } self.epilogue(); }); }
javascript
function NyanCat(runner, options) { Base.call(this, runner, options); var self = this; var width = (Base.window.width * 0.75) | 0; var nyanCatWidth = (this.nyanCatWidth = 11); this.colorIndex = 0; this.numberOfLines = 4; this.rainbowColors = self.generateColors(); this.scoreboardWidth = 5; this.tick = 0; this.trajectories = [[], [], [], []]; this.trajectoryWidthMax = width - nyanCatWidth; runner.on(EVENT_RUN_BEGIN, function() { Base.cursor.hide(); self.draw(); }); runner.on(EVENT_TEST_PENDING, function() { self.draw(); }); runner.on(EVENT_TEST_PASS, function() { self.draw(); }); runner.on(EVENT_TEST_FAIL, function() { self.draw(); }); runner.once(EVENT_RUN_END, function() { Base.cursor.show(); for (var i = 0; i < self.numberOfLines; i++) { write('\n'); } self.epilogue(); }); }
[ "function", "NyanCat", "(", "runner", ",", "options", ")", "{", "Base", ".", "call", "(", "this", ",", "runner", ",", "options", ")", ";", "var", "self", "=", "this", ";", "var", "width", "=", "(", "Base", ".", "window", ".", "width", "*", "0.75", ")", "|", "0", ";", "var", "nyanCatWidth", "=", "(", "this", ".", "nyanCatWidth", "=", "11", ")", ";", "this", ".", "colorIndex", "=", "0", ";", "this", ".", "numberOfLines", "=", "4", ";", "this", ".", "rainbowColors", "=", "self", ".", "generateColors", "(", ")", ";", "this", ".", "scoreboardWidth", "=", "5", ";", "this", ".", "tick", "=", "0", ";", "this", ".", "trajectories", "=", "[", "[", "]", ",", "[", "]", ",", "[", "]", ",", "[", "]", "]", ";", "this", ".", "trajectoryWidthMax", "=", "width", "-", "nyanCatWidth", ";", "runner", ".", "on", "(", "EVENT_RUN_BEGIN", ",", "function", "(", ")", "{", "Base", ".", "cursor", ".", "hide", "(", ")", ";", "self", ".", "draw", "(", ")", ";", "}", ")", ";", "runner", ".", "on", "(", "EVENT_TEST_PENDING", ",", "function", "(", ")", "{", "self", ".", "draw", "(", ")", ";", "}", ")", ";", "runner", ".", "on", "(", "EVENT_TEST_PASS", ",", "function", "(", ")", "{", "self", ".", "draw", "(", ")", ";", "}", ")", ";", "runner", ".", "on", "(", "EVENT_TEST_FAIL", ",", "function", "(", ")", "{", "self", ".", "draw", "(", ")", ";", "}", ")", ";", "runner", ".", "once", "(", "EVENT_RUN_END", ",", "function", "(", ")", "{", "Base", ".", "cursor", ".", "show", "(", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "self", ".", "numberOfLines", ";", "i", "++", ")", "{", "write", "(", "'\\n'", ")", ";", "}", "self", ".", "epilogue", "(", ")", ";", "}", ")", ";", "}" ]
Constructs a new `Nyan` reporter instance. @public @class Nyan @memberof Mocha.reporters @extends Mocha.reporters.Base @param {Runner} runner - Instance triggers reporter actions. @param {Object} [options] - runner options
[ "Constructs", "a", "new", "Nyan", "reporter", "instance", "." ]
9b00fedb610241e33f7592c40164e42a38a793cf
https://github.com/mochajs/mocha/blob/9b00fedb610241e33f7592c40164e42a38a793cf/lib/reporters/nyan.js#L34-L73
1,421
mochajs/mocha
lib/errors.js
createInvalidReporterError
function createInvalidReporterError(message, reporter) { var err = new TypeError(message); err.code = 'ERR_MOCHA_INVALID_REPORTER'; err.reporter = reporter; return err; }
javascript
function createInvalidReporterError(message, reporter) { var err = new TypeError(message); err.code = 'ERR_MOCHA_INVALID_REPORTER'; err.reporter = reporter; return err; }
[ "function", "createInvalidReporterError", "(", "message", ",", "reporter", ")", "{", "var", "err", "=", "new", "TypeError", "(", "message", ")", ";", "err", ".", "code", "=", "'ERR_MOCHA_INVALID_REPORTER'", ";", "err", ".", "reporter", "=", "reporter", ";", "return", "err", ";", "}" ]
Creates an error object to be thrown when the reporter specified in the options was not found. @public @param {string} message - Error message to be displayed. @param {string} reporter - User-specified reporter value. @returns {Error} instance detailing the error condition
[ "Creates", "an", "error", "object", "to", "be", "thrown", "when", "the", "reporter", "specified", "in", "the", "options", "was", "not", "found", "." ]
9b00fedb610241e33f7592c40164e42a38a793cf
https://github.com/mochajs/mocha/blob/9b00fedb610241e33f7592c40164e42a38a793cf/lib/errors.js#L32-L37
1,422
mochajs/mocha
lib/errors.js
createInvalidInterfaceError
function createInvalidInterfaceError(message, ui) { var err = new Error(message); err.code = 'ERR_MOCHA_INVALID_INTERFACE'; err.interface = ui; return err; }
javascript
function createInvalidInterfaceError(message, ui) { var err = new Error(message); err.code = 'ERR_MOCHA_INVALID_INTERFACE'; err.interface = ui; return err; }
[ "function", "createInvalidInterfaceError", "(", "message", ",", "ui", ")", "{", "var", "err", "=", "new", "Error", "(", "message", ")", ";", "err", ".", "code", "=", "'ERR_MOCHA_INVALID_INTERFACE'", ";", "err", ".", "interface", "=", "ui", ";", "return", "err", ";", "}" ]
Creates an error object to be thrown when the interface specified in the options was not found. @public @param {string} message - Error message to be displayed. @param {string} ui - User-specified interface value. @returns {Error} instance detailing the error condition
[ "Creates", "an", "error", "object", "to", "be", "thrown", "when", "the", "interface", "specified", "in", "the", "options", "was", "not", "found", "." ]
9b00fedb610241e33f7592c40164e42a38a793cf
https://github.com/mochajs/mocha/blob/9b00fedb610241e33f7592c40164e42a38a793cf/lib/errors.js#L47-L52
1,423
mochajs/mocha
lib/errors.js
createInvalidArgumentTypeError
function createInvalidArgumentTypeError(message, argument, expected) { var err = new TypeError(message); err.code = 'ERR_MOCHA_INVALID_ARG_TYPE'; err.argument = argument; err.expected = expected; err.actual = typeof argument; return err; }
javascript
function createInvalidArgumentTypeError(message, argument, expected) { var err = new TypeError(message); err.code = 'ERR_MOCHA_INVALID_ARG_TYPE'; err.argument = argument; err.expected = expected; err.actual = typeof argument; return err; }
[ "function", "createInvalidArgumentTypeError", "(", "message", ",", "argument", ",", "expected", ")", "{", "var", "err", "=", "new", "TypeError", "(", "message", ")", ";", "err", ".", "code", "=", "'ERR_MOCHA_INVALID_ARG_TYPE'", ";", "err", ".", "argument", "=", "argument", ";", "err", ".", "expected", "=", "expected", ";", "err", ".", "actual", "=", "typeof", "argument", ";", "return", "err", ";", "}" ]
Creates an error object to be thrown when an argument did not use the supported type @public @param {string} message - Error message to be displayed. @param {string} argument - Argument name. @param {string} expected - Expected argument datatype. @returns {Error} instance detailing the error condition
[ "Creates", "an", "error", "object", "to", "be", "thrown", "when", "an", "argument", "did", "not", "use", "the", "supported", "type" ]
9b00fedb610241e33f7592c40164e42a38a793cf
https://github.com/mochajs/mocha/blob/9b00fedb610241e33f7592c40164e42a38a793cf/lib/errors.js#L89-L96
1,424
mochajs/mocha
lib/errors.js
createInvalidArgumentValueError
function createInvalidArgumentValueError(message, argument, value, reason) { var err = new TypeError(message); err.code = 'ERR_MOCHA_INVALID_ARG_VALUE'; err.argument = argument; err.value = value; err.reason = typeof reason !== 'undefined' ? reason : 'is invalid'; return err; }
javascript
function createInvalidArgumentValueError(message, argument, value, reason) { var err = new TypeError(message); err.code = 'ERR_MOCHA_INVALID_ARG_VALUE'; err.argument = argument; err.value = value; err.reason = typeof reason !== 'undefined' ? reason : 'is invalid'; return err; }
[ "function", "createInvalidArgumentValueError", "(", "message", ",", "argument", ",", "value", ",", "reason", ")", "{", "var", "err", "=", "new", "TypeError", "(", "message", ")", ";", "err", ".", "code", "=", "'ERR_MOCHA_INVALID_ARG_VALUE'", ";", "err", ".", "argument", "=", "argument", ";", "err", ".", "value", "=", "value", ";", "err", ".", "reason", "=", "typeof", "reason", "!==", "'undefined'", "?", "reason", ":", "'is invalid'", ";", "return", "err", ";", "}" ]
Creates an error object to be thrown when an argument did not use the supported value @public @param {string} message - Error message to be displayed. @param {string} argument - Argument name. @param {string} value - Argument value. @param {string} [reason] - Why value is invalid. @returns {Error} instance detailing the error condition
[ "Creates", "an", "error", "object", "to", "be", "thrown", "when", "an", "argument", "did", "not", "use", "the", "supported", "value" ]
9b00fedb610241e33f7592c40164e42a38a793cf
https://github.com/mochajs/mocha/blob/9b00fedb610241e33f7592c40164e42a38a793cf/lib/errors.js#L108-L115
1,425
mochajs/mocha
lib/errors.js
createInvalidExceptionError
function createInvalidExceptionError(message, value) { var err = new Error(message); err.code = 'ERR_MOCHA_INVALID_EXCEPTION'; err.valueType = typeof value; err.value = value; return err; }
javascript
function createInvalidExceptionError(message, value) { var err = new Error(message); err.code = 'ERR_MOCHA_INVALID_EXCEPTION'; err.valueType = typeof value; err.value = value; return err; }
[ "function", "createInvalidExceptionError", "(", "message", ",", "value", ")", "{", "var", "err", "=", "new", "Error", "(", "message", ")", ";", "err", ".", "code", "=", "'ERR_MOCHA_INVALID_EXCEPTION'", ";", "err", ".", "valueType", "=", "typeof", "value", ";", "err", ".", "value", "=", "value", ";", "return", "err", ";", "}" ]
Creates an error object to be thrown when an exception was caught, but the `Error` is falsy or undefined. @public @param {string} message - Error message to be displayed. @returns {Error} instance detailing the error condition
[ "Creates", "an", "error", "object", "to", "be", "thrown", "when", "an", "exception", "was", "caught", "but", "the", "Error", "is", "falsy", "or", "undefined", "." ]
9b00fedb610241e33f7592c40164e42a38a793cf
https://github.com/mochajs/mocha/blob/9b00fedb610241e33f7592c40164e42a38a793cf/lib/errors.js#L124-L130
1,426
mochajs/mocha
lib/utils.js
highlight
function highlight(js) { return js .replace(/</g, '&lt;') .replace(/>/g, '&gt;') .replace(/\/\/(.*)/gm, '<span class="comment">//$1</span>') .replace(/('.*?')/gm, '<span class="string">$1</span>') .replace(/(\d+\.\d+)/gm, '<span class="number">$1</span>') .replace(/(\d+)/gm, '<span class="number">$1</span>') .replace( /\bnew[ \t]+(\w+)/gm, '<span class="keyword">new</span> <span class="init">$1</span>' ) .replace( /\b(function|new|throw|return|var|if|else)\b/gm, '<span class="keyword">$1</span>' ); }
javascript
function highlight(js) { return js .replace(/</g, '&lt;') .replace(/>/g, '&gt;') .replace(/\/\/(.*)/gm, '<span class="comment">//$1</span>') .replace(/('.*?')/gm, '<span class="string">$1</span>') .replace(/(\d+\.\d+)/gm, '<span class="number">$1</span>') .replace(/(\d+)/gm, '<span class="number">$1</span>') .replace( /\bnew[ \t]+(\w+)/gm, '<span class="keyword">new</span> <span class="init">$1</span>' ) .replace( /\b(function|new|throw|return|var|if|else)\b/gm, '<span class="keyword">$1</span>' ); }
[ "function", "highlight", "(", "js", ")", "{", "return", "js", ".", "replace", "(", "/", "<", "/", "g", ",", "'&lt;'", ")", ".", "replace", "(", "/", ">", "/", "g", ",", "'&gt;'", ")", ".", "replace", "(", "/", "\\/\\/(.*)", "/", "gm", ",", "'<span class=\"comment\">//$1</span>'", ")", ".", "replace", "(", "/", "('.*?')", "/", "gm", ",", "'<span class=\"string\">$1</span>'", ")", ".", "replace", "(", "/", "(\\d+\\.\\d+)", "/", "gm", ",", "'<span class=\"number\">$1</span>'", ")", ".", "replace", "(", "/", "(\\d+)", "/", "gm", ",", "'<span class=\"number\">$1</span>'", ")", ".", "replace", "(", "/", "\\bnew[ \\t]+(\\w+)", "/", "gm", ",", "'<span class=\"keyword\">new</span> <span class=\"init\">$1</span>'", ")", ".", "replace", "(", "/", "\\b(function|new|throw|return|var|if|else)\\b", "/", "gm", ",", "'<span class=\"keyword\">$1</span>'", ")", ";", "}" ]
Highlight the given string of `js`. @private @param {string} js @return {string}
[ "Highlight", "the", "given", "string", "of", "js", "." ]
9b00fedb610241e33f7592c40164e42a38a793cf
https://github.com/mochajs/mocha/blob/9b00fedb610241e33f7592c40164e42a38a793cf/lib/utils.js#L202-L218
1,427
mochajs/mocha
lib/utils.js
jsonStringify
function jsonStringify(object, spaces, depth) { if (typeof spaces === 'undefined') { // primitive types return _stringify(object); } depth = depth || 1; var space = spaces * depth; var str = Array.isArray(object) ? '[' : '{'; var end = Array.isArray(object) ? ']' : '}'; var length = typeof object.length === 'number' ? object.length : Object.keys(object).length; // `.repeat()` polyfill function repeat(s, n) { return new Array(n).join(s); } function _stringify(val) { switch (type(val)) { case 'null': case 'undefined': val = '[' + val + ']'; break; case 'array': case 'object': val = jsonStringify(val, spaces, depth + 1); break; case 'boolean': case 'regexp': case 'symbol': case 'number': val = val === 0 && 1 / val === -Infinity // `-0` ? '-0' : val.toString(); break; case 'date': var sDate = isNaN(val.getTime()) ? val.toString() : val.toISOString(); val = '[Date: ' + sDate + ']'; break; case 'buffer': var json = val.toJSON(); // Based on the toJSON result json = json.data && json.type ? json.data : json; val = '[Buffer: ' + jsonStringify(json, 2, depth + 1) + ']'; break; default: val = val === '[Function]' || val === '[Circular]' ? val : JSON.stringify(val); // string } return val; } for (var i in object) { if (!Object.prototype.hasOwnProperty.call(object, i)) { continue; // not my business } --length; str += '\n ' + repeat(' ', space) + (Array.isArray(object) ? '' : '"' + i + '": ') + // key _stringify(object[i]) + // value (length ? ',' : ''); // comma } return ( str + // [], {} (str.length !== 1 ? '\n' + repeat(' ', --space) + end : end) ); }
javascript
function jsonStringify(object, spaces, depth) { if (typeof spaces === 'undefined') { // primitive types return _stringify(object); } depth = depth || 1; var space = spaces * depth; var str = Array.isArray(object) ? '[' : '{'; var end = Array.isArray(object) ? ']' : '}'; var length = typeof object.length === 'number' ? object.length : Object.keys(object).length; // `.repeat()` polyfill function repeat(s, n) { return new Array(n).join(s); } function _stringify(val) { switch (type(val)) { case 'null': case 'undefined': val = '[' + val + ']'; break; case 'array': case 'object': val = jsonStringify(val, spaces, depth + 1); break; case 'boolean': case 'regexp': case 'symbol': case 'number': val = val === 0 && 1 / val === -Infinity // `-0` ? '-0' : val.toString(); break; case 'date': var sDate = isNaN(val.getTime()) ? val.toString() : val.toISOString(); val = '[Date: ' + sDate + ']'; break; case 'buffer': var json = val.toJSON(); // Based on the toJSON result json = json.data && json.type ? json.data : json; val = '[Buffer: ' + jsonStringify(json, 2, depth + 1) + ']'; break; default: val = val === '[Function]' || val === '[Circular]' ? val : JSON.stringify(val); // string } return val; } for (var i in object) { if (!Object.prototype.hasOwnProperty.call(object, i)) { continue; // not my business } --length; str += '\n ' + repeat(' ', space) + (Array.isArray(object) ? '' : '"' + i + '": ') + // key _stringify(object[i]) + // value (length ? ',' : ''); // comma } return ( str + // [], {} (str.length !== 1 ? '\n' + repeat(' ', --space) + end : end) ); }
[ "function", "jsonStringify", "(", "object", ",", "spaces", ",", "depth", ")", "{", "if", "(", "typeof", "spaces", "===", "'undefined'", ")", "{", "// primitive types", "return", "_stringify", "(", "object", ")", ";", "}", "depth", "=", "depth", "||", "1", ";", "var", "space", "=", "spaces", "*", "depth", ";", "var", "str", "=", "Array", ".", "isArray", "(", "object", ")", "?", "'['", ":", "'{'", ";", "var", "end", "=", "Array", ".", "isArray", "(", "object", ")", "?", "']'", ":", "'}'", ";", "var", "length", "=", "typeof", "object", ".", "length", "===", "'number'", "?", "object", ".", "length", ":", "Object", ".", "keys", "(", "object", ")", ".", "length", ";", "// `.repeat()` polyfill", "function", "repeat", "(", "s", ",", "n", ")", "{", "return", "new", "Array", "(", "n", ")", ".", "join", "(", "s", ")", ";", "}", "function", "_stringify", "(", "val", ")", "{", "switch", "(", "type", "(", "val", ")", ")", "{", "case", "'null'", ":", "case", "'undefined'", ":", "val", "=", "'['", "+", "val", "+", "']'", ";", "break", ";", "case", "'array'", ":", "case", "'object'", ":", "val", "=", "jsonStringify", "(", "val", ",", "spaces", ",", "depth", "+", "1", ")", ";", "break", ";", "case", "'boolean'", ":", "case", "'regexp'", ":", "case", "'symbol'", ":", "case", "'number'", ":", "val", "=", "val", "===", "0", "&&", "1", "/", "val", "===", "-", "Infinity", "// `-0`", "?", "'-0'", ":", "val", ".", "toString", "(", ")", ";", "break", ";", "case", "'date'", ":", "var", "sDate", "=", "isNaN", "(", "val", ".", "getTime", "(", ")", ")", "?", "val", ".", "toString", "(", ")", ":", "val", ".", "toISOString", "(", ")", ";", "val", "=", "'[Date: '", "+", "sDate", "+", "']'", ";", "break", ";", "case", "'buffer'", ":", "var", "json", "=", "val", ".", "toJSON", "(", ")", ";", "// Based on the toJSON result", "json", "=", "json", ".", "data", "&&", "json", ".", "type", "?", "json", ".", "data", ":", "json", ";", "val", "=", "'[Buffer: '", "+", "jsonStringify", "(", "json", ",", "2", ",", "depth", "+", "1", ")", "+", "']'", ";", "break", ";", "default", ":", "val", "=", "val", "===", "'[Function]'", "||", "val", "===", "'[Circular]'", "?", "val", ":", "JSON", ".", "stringify", "(", "val", ")", ";", "// string", "}", "return", "val", ";", "}", "for", "(", "var", "i", "in", "object", ")", "{", "if", "(", "!", "Object", ".", "prototype", ".", "hasOwnProperty", ".", "call", "(", "object", ",", "i", ")", ")", "{", "continue", ";", "// not my business", "}", "--", "length", ";", "str", "+=", "'\\n '", "+", "repeat", "(", "' '", ",", "space", ")", "+", "(", "Array", ".", "isArray", "(", "object", ")", "?", "''", ":", "'\"'", "+", "i", "+", "'\": '", ")", "+", "// key", "_stringify", "(", "object", "[", "i", "]", ")", "+", "// value", "(", "length", "?", "','", ":", "''", ")", ";", "// comma", "}", "return", "(", "str", "+", "// [], {}", "(", "str", ".", "length", "!==", "1", "?", "'\\n'", "+", "repeat", "(", "' '", ",", "--", "space", ")", "+", "end", ":", "end", ")", ")", ";", "}" ]
like JSON.stringify but more sense. @private @param {Object} object @param {number=} spaces @param {number=} depth @returns {*}
[ "like", "JSON", ".", "stringify", "but", "more", "sense", "." ]
9b00fedb610241e33f7592c40164e42a38a793cf
https://github.com/mochajs/mocha/blob/9b00fedb610241e33f7592c40164e42a38a793cf/lib/utils.js#L357-L432
1,428
mochajs/mocha
lib/utils.js
hasMatchingExtname
function hasMatchingExtname(pathname, exts) { var suffix = path.extname(pathname).slice(1); return exts.some(function(element) { return suffix === element; }); }
javascript
function hasMatchingExtname(pathname, exts) { var suffix = path.extname(pathname).slice(1); return exts.some(function(element) { return suffix === element; }); }
[ "function", "hasMatchingExtname", "(", "pathname", ",", "exts", ")", "{", "var", "suffix", "=", "path", ".", "extname", "(", "pathname", ")", ".", "slice", "(", "1", ")", ";", "return", "exts", ".", "some", "(", "function", "(", "element", ")", "{", "return", "suffix", "===", "element", ";", "}", ")", ";", "}" ]
Determines if pathname has a matching file extension. @private @param {string} pathname - Pathname to check for match. @param {string[]} exts - List of file extensions (sans period). @return {boolean} whether file extension matches. @example hasMatchingExtname('foo.html', ['js', 'css']); // => false
[ "Determines", "if", "pathname", "has", "a", "matching", "file", "extension", "." ]
9b00fedb610241e33f7592c40164e42a38a793cf
https://github.com/mochajs/mocha/blob/9b00fedb610241e33f7592c40164e42a38a793cf/lib/utils.js#L530-L535
1,429
mochajs/mocha
lib/utils.js
emitWarning
function emitWarning(msg, type) { if (process.emitWarning) { process.emitWarning(msg, type); } else { process.nextTick(function() { console.warn(type + ': ' + msg); }); } }
javascript
function emitWarning(msg, type) { if (process.emitWarning) { process.emitWarning(msg, type); } else { process.nextTick(function() { console.warn(type + ': ' + msg); }); } }
[ "function", "emitWarning", "(", "msg", ",", "type", ")", "{", "if", "(", "process", ".", "emitWarning", ")", "{", "process", ".", "emitWarning", "(", "msg", ",", "type", ")", ";", "}", "else", "{", "process", ".", "nextTick", "(", "function", "(", ")", "{", "console", ".", "warn", "(", "type", "+", "': '", "+", "msg", ")", ";", "}", ")", ";", "}", "}" ]
process.emitWarning or a polyfill @see https://nodejs.org/api/process.html#process_process_emitwarning_warning_options @ignore
[ "process", ".", "emitWarning", "or", "a", "polyfill" ]
9b00fedb610241e33f7592c40164e42a38a793cf
https://github.com/mochajs/mocha/blob/9b00fedb610241e33f7592c40164e42a38a793cf/lib/utils.js#L655-L663
1,430
mochajs/mocha
lib/reporters/min.js
Min
function Min(runner, options) { Base.call(this, runner, options); runner.on(EVENT_RUN_BEGIN, function() { // clear screen process.stdout.write('\u001b[2J'); // set cursor position process.stdout.write('\u001b[1;3H'); }); runner.once(EVENT_RUN_END, this.epilogue.bind(this)); }
javascript
function Min(runner, options) { Base.call(this, runner, options); runner.on(EVENT_RUN_BEGIN, function() { // clear screen process.stdout.write('\u001b[2J'); // set cursor position process.stdout.write('\u001b[1;3H'); }); runner.once(EVENT_RUN_END, this.epilogue.bind(this)); }
[ "function", "Min", "(", "runner", ",", "options", ")", "{", "Base", ".", "call", "(", "this", ",", "runner", ",", "options", ")", ";", "runner", ".", "on", "(", "EVENT_RUN_BEGIN", ",", "function", "(", ")", "{", "// clear screen", "process", ".", "stdout", ".", "write", "(", "'\\u001b[2J'", ")", ";", "// set cursor position", "process", ".", "stdout", ".", "write", "(", "'\\u001b[1;3H'", ")", ";", "}", ")", ";", "runner", ".", "once", "(", "EVENT_RUN_END", ",", "this", ".", "epilogue", ".", "bind", "(", "this", ")", ")", ";", "}" ]
Constructs a new `Min` reporter instance. @description This minimal test reporter is best used with '--watch'. @public @class @memberof Mocha.reporters @extends Mocha.reporters.Base @param {Runner} runner - Instance triggers reporter actions. @param {Object} [options] - runner options
[ "Constructs", "a", "new", "Min", "reporter", "instance", "." ]
9b00fedb610241e33f7592c40164e42a38a793cf
https://github.com/mochajs/mocha/blob/9b00fedb610241e33f7592c40164e42a38a793cf/lib/reporters/min.js#L34-L45
1,431
mochajs/mocha
lib/reporters/spec.js
Spec
function Spec(runner, options) { Base.call(this, runner, options); var self = this; var indents = 0; var n = 0; function indent() { return Array(indents).join(' '); } runner.on(EVENT_RUN_BEGIN, function() { console.log(); }); runner.on(EVENT_SUITE_BEGIN, function(suite) { ++indents; console.log(color('suite', '%s%s'), indent(), suite.title); }); runner.on(EVENT_SUITE_END, function() { --indents; if (indents === 1) { console.log(); } }); runner.on(EVENT_TEST_PENDING, function(test) { var fmt = indent() + color('pending', ' - %s'); console.log(fmt, test.title); }); runner.on(EVENT_TEST_PASS, function(test) { var fmt; if (test.speed === 'fast') { fmt = indent() + color('checkmark', ' ' + Base.symbols.ok) + color('pass', ' %s'); console.log(fmt, test.title); } else { fmt = indent() + color('checkmark', ' ' + Base.symbols.ok) + color('pass', ' %s') + color(test.speed, ' (%dms)'); console.log(fmt, test.title, test.duration); } }); runner.on(EVENT_TEST_FAIL, function(test) { console.log(indent() + color('fail', ' %d) %s'), ++n, test.title); }); runner.once(EVENT_RUN_END, self.epilogue.bind(self)); }
javascript
function Spec(runner, options) { Base.call(this, runner, options); var self = this; var indents = 0; var n = 0; function indent() { return Array(indents).join(' '); } runner.on(EVENT_RUN_BEGIN, function() { console.log(); }); runner.on(EVENT_SUITE_BEGIN, function(suite) { ++indents; console.log(color('suite', '%s%s'), indent(), suite.title); }); runner.on(EVENT_SUITE_END, function() { --indents; if (indents === 1) { console.log(); } }); runner.on(EVENT_TEST_PENDING, function(test) { var fmt = indent() + color('pending', ' - %s'); console.log(fmt, test.title); }); runner.on(EVENT_TEST_PASS, function(test) { var fmt; if (test.speed === 'fast') { fmt = indent() + color('checkmark', ' ' + Base.symbols.ok) + color('pass', ' %s'); console.log(fmt, test.title); } else { fmt = indent() + color('checkmark', ' ' + Base.symbols.ok) + color('pass', ' %s') + color(test.speed, ' (%dms)'); console.log(fmt, test.title, test.duration); } }); runner.on(EVENT_TEST_FAIL, function(test) { console.log(indent() + color('fail', ' %d) %s'), ++n, test.title); }); runner.once(EVENT_RUN_END, self.epilogue.bind(self)); }
[ "function", "Spec", "(", "runner", ",", "options", ")", "{", "Base", ".", "call", "(", "this", ",", "runner", ",", "options", ")", ";", "var", "self", "=", "this", ";", "var", "indents", "=", "0", ";", "var", "n", "=", "0", ";", "function", "indent", "(", ")", "{", "return", "Array", "(", "indents", ")", ".", "join", "(", "' '", ")", ";", "}", "runner", ".", "on", "(", "EVENT_RUN_BEGIN", ",", "function", "(", ")", "{", "console", ".", "log", "(", ")", ";", "}", ")", ";", "runner", ".", "on", "(", "EVENT_SUITE_BEGIN", ",", "function", "(", "suite", ")", "{", "++", "indents", ";", "console", ".", "log", "(", "color", "(", "'suite'", ",", "'%s%s'", ")", ",", "indent", "(", ")", ",", "suite", ".", "title", ")", ";", "}", ")", ";", "runner", ".", "on", "(", "EVENT_SUITE_END", ",", "function", "(", ")", "{", "--", "indents", ";", "if", "(", "indents", "===", "1", ")", "{", "console", ".", "log", "(", ")", ";", "}", "}", ")", ";", "runner", ".", "on", "(", "EVENT_TEST_PENDING", ",", "function", "(", "test", ")", "{", "var", "fmt", "=", "indent", "(", ")", "+", "color", "(", "'pending'", ",", "' - %s'", ")", ";", "console", ".", "log", "(", "fmt", ",", "test", ".", "title", ")", ";", "}", ")", ";", "runner", ".", "on", "(", "EVENT_TEST_PASS", ",", "function", "(", "test", ")", "{", "var", "fmt", ";", "if", "(", "test", ".", "speed", "===", "'fast'", ")", "{", "fmt", "=", "indent", "(", ")", "+", "color", "(", "'checkmark'", ",", "' '", "+", "Base", ".", "symbols", ".", "ok", ")", "+", "color", "(", "'pass'", ",", "' %s'", ")", ";", "console", ".", "log", "(", "fmt", ",", "test", ".", "title", ")", ";", "}", "else", "{", "fmt", "=", "indent", "(", ")", "+", "color", "(", "'checkmark'", ",", "' '", "+", "Base", ".", "symbols", ".", "ok", ")", "+", "color", "(", "'pass'", ",", "' %s'", ")", "+", "color", "(", "test", ".", "speed", ",", "' (%dms)'", ")", ";", "console", ".", "log", "(", "fmt", ",", "test", ".", "title", ",", "test", ".", "duration", ")", ";", "}", "}", ")", ";", "runner", ".", "on", "(", "EVENT_TEST_FAIL", ",", "function", "(", "test", ")", "{", "console", ".", "log", "(", "indent", "(", ")", "+", "color", "(", "'fail'", ",", "' %d) %s'", ")", ",", "++", "n", ",", "test", ".", "title", ")", ";", "}", ")", ";", "runner", ".", "once", "(", "EVENT_RUN_END", ",", "self", ".", "epilogue", ".", "bind", "(", "self", ")", ")", ";", "}" ]
Constructs a new `Spec` reporter instance. @public @class @memberof Mocha.reporters @extends Mocha.reporters.Base @param {Runner} runner - Instance triggers reporter actions. @param {Object} [options] - runner options
[ "Constructs", "a", "new", "Spec", "reporter", "instance", "." ]
9b00fedb610241e33f7592c40164e42a38a793cf
https://github.com/mochajs/mocha/blob/9b00fedb610241e33f7592c40164e42a38a793cf/lib/reporters/spec.js#L37-L92
1,432
mochajs/mocha
lib/reporters/markdown.js
Markdown
function Markdown(runner, options) { Base.call(this, runner, options); var level = 0; var buf = ''; function title(str) { return Array(level).join('#') + ' ' + str; } function mapTOC(suite, obj) { var ret = obj; var key = SUITE_PREFIX + suite.title; obj = obj[key] = obj[key] || {suite: suite}; suite.suites.forEach(function(suite) { mapTOC(suite, obj); }); return ret; } function stringifyTOC(obj, level) { ++level; var buf = ''; var link; for (var key in obj) { if (key === 'suite') { continue; } if (key !== SUITE_PREFIX) { link = ' - [' + key.substring(1) + ']'; link += '(#' + utils.slug(obj[key].suite.fullTitle()) + ')\n'; buf += Array(level).join(' ') + link; } buf += stringifyTOC(obj[key], level); } return buf; } function generateTOC(suite) { var obj = mapTOC(suite, {}); return stringifyTOC(obj, 0); } generateTOC(runner.suite); runner.on(EVENT_SUITE_BEGIN, function(suite) { ++level; var slug = utils.slug(suite.fullTitle()); buf += '<a name="' + slug + '"></a>' + '\n'; buf += title(suite.title) + '\n'; }); runner.on(EVENT_SUITE_END, function() { --level; }); runner.on(EVENT_TEST_PASS, function(test) { var code = utils.clean(test.body); buf += test.title + '.\n'; buf += '\n```js\n'; buf += code + '\n'; buf += '```\n\n'; }); runner.once(EVENT_RUN_END, function() { process.stdout.write('# TOC\n'); process.stdout.write(generateTOC(runner.suite)); process.stdout.write(buf); }); }
javascript
function Markdown(runner, options) { Base.call(this, runner, options); var level = 0; var buf = ''; function title(str) { return Array(level).join('#') + ' ' + str; } function mapTOC(suite, obj) { var ret = obj; var key = SUITE_PREFIX + suite.title; obj = obj[key] = obj[key] || {suite: suite}; suite.suites.forEach(function(suite) { mapTOC(suite, obj); }); return ret; } function stringifyTOC(obj, level) { ++level; var buf = ''; var link; for (var key in obj) { if (key === 'suite') { continue; } if (key !== SUITE_PREFIX) { link = ' - [' + key.substring(1) + ']'; link += '(#' + utils.slug(obj[key].suite.fullTitle()) + ')\n'; buf += Array(level).join(' ') + link; } buf += stringifyTOC(obj[key], level); } return buf; } function generateTOC(suite) { var obj = mapTOC(suite, {}); return stringifyTOC(obj, 0); } generateTOC(runner.suite); runner.on(EVENT_SUITE_BEGIN, function(suite) { ++level; var slug = utils.slug(suite.fullTitle()); buf += '<a name="' + slug + '"></a>' + '\n'; buf += title(suite.title) + '\n'; }); runner.on(EVENT_SUITE_END, function() { --level; }); runner.on(EVENT_TEST_PASS, function(test) { var code = utils.clean(test.body); buf += test.title + '.\n'; buf += '\n```js\n'; buf += code + '\n'; buf += '```\n\n'; }); runner.once(EVENT_RUN_END, function() { process.stdout.write('# TOC\n'); process.stdout.write(generateTOC(runner.suite)); process.stdout.write(buf); }); }
[ "function", "Markdown", "(", "runner", ",", "options", ")", "{", "Base", ".", "call", "(", "this", ",", "runner", ",", "options", ")", ";", "var", "level", "=", "0", ";", "var", "buf", "=", "''", ";", "function", "title", "(", "str", ")", "{", "return", "Array", "(", "level", ")", ".", "join", "(", "'#'", ")", "+", "' '", "+", "str", ";", "}", "function", "mapTOC", "(", "suite", ",", "obj", ")", "{", "var", "ret", "=", "obj", ";", "var", "key", "=", "SUITE_PREFIX", "+", "suite", ".", "title", ";", "obj", "=", "obj", "[", "key", "]", "=", "obj", "[", "key", "]", "||", "{", "suite", ":", "suite", "}", ";", "suite", ".", "suites", ".", "forEach", "(", "function", "(", "suite", ")", "{", "mapTOC", "(", "suite", ",", "obj", ")", ";", "}", ")", ";", "return", "ret", ";", "}", "function", "stringifyTOC", "(", "obj", ",", "level", ")", "{", "++", "level", ";", "var", "buf", "=", "''", ";", "var", "link", ";", "for", "(", "var", "key", "in", "obj", ")", "{", "if", "(", "key", "===", "'suite'", ")", "{", "continue", ";", "}", "if", "(", "key", "!==", "SUITE_PREFIX", ")", "{", "link", "=", "' - ['", "+", "key", ".", "substring", "(", "1", ")", "+", "']'", ";", "link", "+=", "'(#'", "+", "utils", ".", "slug", "(", "obj", "[", "key", "]", ".", "suite", ".", "fullTitle", "(", ")", ")", "+", "')\\n'", ";", "buf", "+=", "Array", "(", "level", ")", ".", "join", "(", "' '", ")", "+", "link", ";", "}", "buf", "+=", "stringifyTOC", "(", "obj", "[", "key", "]", ",", "level", ")", ";", "}", "return", "buf", ";", "}", "function", "generateTOC", "(", "suite", ")", "{", "var", "obj", "=", "mapTOC", "(", "suite", ",", "{", "}", ")", ";", "return", "stringifyTOC", "(", "obj", ",", "0", ")", ";", "}", "generateTOC", "(", "runner", ".", "suite", ")", ";", "runner", ".", "on", "(", "EVENT_SUITE_BEGIN", ",", "function", "(", "suite", ")", "{", "++", "level", ";", "var", "slug", "=", "utils", ".", "slug", "(", "suite", ".", "fullTitle", "(", ")", ")", ";", "buf", "+=", "'<a name=\"'", "+", "slug", "+", "'\"></a>'", "+", "'\\n'", ";", "buf", "+=", "title", "(", "suite", ".", "title", ")", "+", "'\\n'", ";", "}", ")", ";", "runner", ".", "on", "(", "EVENT_SUITE_END", ",", "function", "(", ")", "{", "--", "level", ";", "}", ")", ";", "runner", ".", "on", "(", "EVENT_TEST_PASS", ",", "function", "(", "test", ")", "{", "var", "code", "=", "utils", ".", "clean", "(", "test", ".", "body", ")", ";", "buf", "+=", "test", ".", "title", "+", "'.\\n'", ";", "buf", "+=", "'\\n```js\\n'", ";", "buf", "+=", "code", "+", "'\\n'", ";", "buf", "+=", "'```\\n\\n'", ";", "}", ")", ";", "runner", ".", "once", "(", "EVENT_RUN_END", ",", "function", "(", ")", "{", "process", ".", "stdout", ".", "write", "(", "'# TOC\\n'", ")", ";", "process", ".", "stdout", ".", "write", "(", "generateTOC", "(", "runner", ".", "suite", ")", ")", ";", "process", ".", "stdout", ".", "write", "(", "buf", ")", ";", "}", ")", ";", "}" ]
Constructs a new `Markdown` reporter instance. @public @class @memberof Mocha.reporters @extends Mocha.reporters.Base @param {Runner} runner - Instance triggers reporter actions. @param {Object} [options] - runner options
[ "Constructs", "a", "new", "Markdown", "reporter", "instance", "." ]
9b00fedb610241e33f7592c40164e42a38a793cf
https://github.com/mochajs/mocha/blob/9b00fedb610241e33f7592c40164e42a38a793cf/lib/reporters/markdown.js#L39-L110
1,433
mochajs/mocha
lib/mocha.js
Mocha
function Mocha(options) { options = utils.assign({}, mocharc, options || {}); this.files = []; this.options = options; // root suite this.suite = new exports.Suite('', new exports.Context(), true); if ('useColors' in options) { utils.deprecate( 'useColors is DEPRECATED and will be removed from a future version of Mocha. Instead, use the "color" option' ); options.color = 'color' in options ? options.color : options.useColors; } this.grep(options.grep) .fgrep(options.fgrep) .ui(options.ui) .bail(options.bail) .reporter(options.reporter, options.reporterOptions) .useColors(options.color) .slow(options.slow) .useInlineDiffs(options.inlineDiffs) .globals(options.globals); if ('enableTimeouts' in options) { utils.deprecate( 'enableTimeouts is DEPRECATED and will be removed from a future version of Mocha. Instead, use "timeout: false" to disable timeouts.' ); if (options.enableTimeouts === false) { this.timeout(0); } } // this guard exists because Suite#timeout does not consider `undefined` to be valid input if (typeof options.timeout !== 'undefined') { this.timeout(options.timeout === false ? 0 : options.timeout); } if ('retries' in options) { this.retries(options.retries); } if ('diff' in options) { this.hideDiff(!options.diff); } [ 'allowUncaught', 'asyncOnly', 'checkLeaks', 'delay', 'forbidOnly', 'forbidPending', 'fullTrace', 'growl', 'invert' ].forEach(function(opt) { if (options[opt]) { this[opt](); } }, this); }
javascript
function Mocha(options) { options = utils.assign({}, mocharc, options || {}); this.files = []; this.options = options; // root suite this.suite = new exports.Suite('', new exports.Context(), true); if ('useColors' in options) { utils.deprecate( 'useColors is DEPRECATED and will be removed from a future version of Mocha. Instead, use the "color" option' ); options.color = 'color' in options ? options.color : options.useColors; } this.grep(options.grep) .fgrep(options.fgrep) .ui(options.ui) .bail(options.bail) .reporter(options.reporter, options.reporterOptions) .useColors(options.color) .slow(options.slow) .useInlineDiffs(options.inlineDiffs) .globals(options.globals); if ('enableTimeouts' in options) { utils.deprecate( 'enableTimeouts is DEPRECATED and will be removed from a future version of Mocha. Instead, use "timeout: false" to disable timeouts.' ); if (options.enableTimeouts === false) { this.timeout(0); } } // this guard exists because Suite#timeout does not consider `undefined` to be valid input if (typeof options.timeout !== 'undefined') { this.timeout(options.timeout === false ? 0 : options.timeout); } if ('retries' in options) { this.retries(options.retries); } if ('diff' in options) { this.hideDiff(!options.diff); } [ 'allowUncaught', 'asyncOnly', 'checkLeaks', 'delay', 'forbidOnly', 'forbidPending', 'fullTrace', 'growl', 'invert' ].forEach(function(opt) { if (options[opt]) { this[opt](); } }, this); }
[ "function", "Mocha", "(", "options", ")", "{", "options", "=", "utils", ".", "assign", "(", "{", "}", ",", "mocharc", ",", "options", "||", "{", "}", ")", ";", "this", ".", "files", "=", "[", "]", ";", "this", ".", "options", "=", "options", ";", "// root suite", "this", ".", "suite", "=", "new", "exports", ".", "Suite", "(", "''", ",", "new", "exports", ".", "Context", "(", ")", ",", "true", ")", ";", "if", "(", "'useColors'", "in", "options", ")", "{", "utils", ".", "deprecate", "(", "'useColors is DEPRECATED and will be removed from a future version of Mocha. Instead, use the \"color\" option'", ")", ";", "options", ".", "color", "=", "'color'", "in", "options", "?", "options", ".", "color", ":", "options", ".", "useColors", ";", "}", "this", ".", "grep", "(", "options", ".", "grep", ")", ".", "fgrep", "(", "options", ".", "fgrep", ")", ".", "ui", "(", "options", ".", "ui", ")", ".", "bail", "(", "options", ".", "bail", ")", ".", "reporter", "(", "options", ".", "reporter", ",", "options", ".", "reporterOptions", ")", ".", "useColors", "(", "options", ".", "color", ")", ".", "slow", "(", "options", ".", "slow", ")", ".", "useInlineDiffs", "(", "options", ".", "inlineDiffs", ")", ".", "globals", "(", "options", ".", "globals", ")", ";", "if", "(", "'enableTimeouts'", "in", "options", ")", "{", "utils", ".", "deprecate", "(", "'enableTimeouts is DEPRECATED and will be removed from a future version of Mocha. Instead, use \"timeout: false\" to disable timeouts.'", ")", ";", "if", "(", "options", ".", "enableTimeouts", "===", "false", ")", "{", "this", ".", "timeout", "(", "0", ")", ";", "}", "}", "// this guard exists because Suite#timeout does not consider `undefined` to be valid input", "if", "(", "typeof", "options", ".", "timeout", "!==", "'undefined'", ")", "{", "this", ".", "timeout", "(", "options", ".", "timeout", "===", "false", "?", "0", ":", "options", ".", "timeout", ")", ";", "}", "if", "(", "'retries'", "in", "options", ")", "{", "this", ".", "retries", "(", "options", ".", "retries", ")", ";", "}", "if", "(", "'diff'", "in", "options", ")", "{", "this", ".", "hideDiff", "(", "!", "options", ".", "diff", ")", ";", "}", "[", "'allowUncaught'", ",", "'asyncOnly'", ",", "'checkLeaks'", ",", "'delay'", ",", "'forbidOnly'", ",", "'forbidPending'", ",", "'fullTrace'", ",", "'growl'", ",", "'invert'", "]", ".", "forEach", "(", "function", "(", "opt", ")", "{", "if", "(", "options", "[", "opt", "]", ")", "{", "this", "[", "opt", "]", "(", ")", ";", "}", "}", ",", "this", ")", ";", "}" ]
Constructs a new Mocha instance with `options`. @public @class Mocha @param {Object} [options] - Settings object. @param {boolean} [options.allowUncaught] - Propagate uncaught errors? @param {boolean} [options.asyncOnly] - Force `done` callback or promise? @param {boolean} [options.bail] - Bail after first test failure? @param {boolean} [options.checkLeaks] - If true, check leaks. @param {boolean} [options.delay] - Delay root suite execution? @param {boolean} [options.enableTimeouts] - Enable timeouts? @param {string} [options.fgrep] - Test filter given string. @param {boolean} [options.forbidOnly] - Tests marked `only` fail the suite? @param {boolean} [options.forbidPending] - Pending tests fail the suite? @param {boolean} [options.fullStackTrace] - Full stacktrace upon failure? @param {string[]} [options.global] - Variables expected in global scope. @param {RegExp|string} [options.grep] - Test filter given regular expression. @param {boolean} [options.growl] - Enable desktop notifications? @param {boolean} [options.hideDiff] - Suppress diffs from failures? @param {boolean} [options.ignoreLeaks] - Ignore global leaks? @param {boolean} [options.invert] - Invert test filter matches? @param {boolean} [options.noHighlighting] - Disable syntax highlighting? @param {string} [options.reporter] - Reporter name. @param {Object} [options.reporterOption] - Reporter settings object. @param {number} [options.retries] - Number of times to retry failed tests. @param {number} [options.slow] - Slow threshold value. @param {number|string} [options.timeout] - Timeout threshold value. @param {string} [options.ui] - Interface name. @param {boolean} [options.color] - Color TTY output from reporter? @param {boolean} [options.useInlineDiffs] - Use inline diffs?
[ "Constructs", "a", "new", "Mocha", "instance", "with", "options", "." ]
9b00fedb610241e33f7592c40164e42a38a793cf
https://github.com/mochajs/mocha/blob/9b00fedb610241e33f7592c40164e42a38a793cf/lib/mocha.js#L95-L156
1,434
mochajs/mocha
lib/reporters/json-stream.js
JSONStream
function JSONStream(runner, options) { Base.call(this, runner, options); var self = this; var total = runner.total; runner.once(EVENT_RUN_BEGIN, function() { writeEvent(['start', {total: total}]); }); runner.on(EVENT_TEST_PASS, function(test) { writeEvent(['pass', clean(test)]); }); runner.on(EVENT_TEST_FAIL, function(test, err) { test = clean(test); test.err = err.message; test.stack = err.stack || null; writeEvent(['fail', test]); }); runner.once(EVENT_RUN_END, function() { writeEvent(['end', self.stats]); }); }
javascript
function JSONStream(runner, options) { Base.call(this, runner, options); var self = this; var total = runner.total; runner.once(EVENT_RUN_BEGIN, function() { writeEvent(['start', {total: total}]); }); runner.on(EVENT_TEST_PASS, function(test) { writeEvent(['pass', clean(test)]); }); runner.on(EVENT_TEST_FAIL, function(test, err) { test = clean(test); test.err = err.message; test.stack = err.stack || null; writeEvent(['fail', test]); }); runner.once(EVENT_RUN_END, function() { writeEvent(['end', self.stats]); }); }
[ "function", "JSONStream", "(", "runner", ",", "options", ")", "{", "Base", ".", "call", "(", "this", ",", "runner", ",", "options", ")", ";", "var", "self", "=", "this", ";", "var", "total", "=", "runner", ".", "total", ";", "runner", ".", "once", "(", "EVENT_RUN_BEGIN", ",", "function", "(", ")", "{", "writeEvent", "(", "[", "'start'", ",", "{", "total", ":", "total", "}", "]", ")", ";", "}", ")", ";", "runner", ".", "on", "(", "EVENT_TEST_PASS", ",", "function", "(", "test", ")", "{", "writeEvent", "(", "[", "'pass'", ",", "clean", "(", "test", ")", "]", ")", ";", "}", ")", ";", "runner", ".", "on", "(", "EVENT_TEST_FAIL", ",", "function", "(", "test", ",", "err", ")", "{", "test", "=", "clean", "(", "test", ")", ";", "test", ".", "err", "=", "err", ".", "message", ";", "test", ".", "stack", "=", "err", ".", "stack", "||", "null", ";", "writeEvent", "(", "[", "'fail'", ",", "test", "]", ")", ";", "}", ")", ";", "runner", ".", "once", "(", "EVENT_RUN_END", ",", "function", "(", ")", "{", "writeEvent", "(", "[", "'end'", ",", "self", ".", "stats", "]", ")", ";", "}", ")", ";", "}" ]
Constructs a new `JSONStream` reporter instance. @public @class @memberof Mocha.reporters @extends Mocha.reporters.Base @param {Runner} runner - Instance triggers reporter actions. @param {Object} [options] - runner options
[ "Constructs", "a", "new", "JSONStream", "reporter", "instance", "." ]
9b00fedb610241e33f7592c40164e42a38a793cf
https://github.com/mochajs/mocha/blob/9b00fedb610241e33f7592c40164e42a38a793cf/lib/reporters/json-stream.js#L32-L56
1,435
mochajs/mocha
lib/reporters/json-stream.js
clean
function clean(test) { return { title: test.title, fullTitle: test.fullTitle(), duration: test.duration, currentRetry: test.currentRetry() }; }
javascript
function clean(test) { return { title: test.title, fullTitle: test.fullTitle(), duration: test.duration, currentRetry: test.currentRetry() }; }
[ "function", "clean", "(", "test", ")", "{", "return", "{", "title", ":", "test", ".", "title", ",", "fullTitle", ":", "test", ".", "fullTitle", "(", ")", ",", "duration", ":", "test", ".", "duration", ",", "currentRetry", ":", "test", ".", "currentRetry", "(", ")", "}", ";", "}" ]
Returns an object literal representation of `test` free of cyclic properties, etc. @private @param {Test} test - Instance used as data source. @return {Object} object containing pared-down test instance data
[ "Returns", "an", "object", "literal", "representation", "of", "test", "free", "of", "cyclic", "properties", "etc", "." ]
9b00fedb610241e33f7592c40164e42a38a793cf
https://github.com/mochajs/mocha/blob/9b00fedb610241e33f7592c40164e42a38a793cf/lib/reporters/json-stream.js#L81-L88
1,436
mochajs/mocha
lib/reporters/list.js
List
function List(runner, options) { Base.call(this, runner, options); var self = this; var n = 0; runner.on(EVENT_RUN_BEGIN, function() { console.log(); }); runner.on(EVENT_TEST_BEGIN, function(test) { process.stdout.write(color('pass', ' ' + test.fullTitle() + ': ')); }); runner.on(EVENT_TEST_PENDING, function(test) { var fmt = color('checkmark', ' -') + color('pending', ' %s'); console.log(fmt, test.fullTitle()); }); runner.on(EVENT_TEST_PASS, function(test) { var fmt = color('checkmark', ' ' + Base.symbols.ok) + color('pass', ' %s: ') + color(test.speed, '%dms'); cursor.CR(); console.log(fmt, test.fullTitle(), test.duration); }); runner.on(EVENT_TEST_FAIL, function(test) { cursor.CR(); console.log(color('fail', ' %d) %s'), ++n, test.fullTitle()); }); runner.once(EVENT_RUN_END, self.epilogue.bind(self)); }
javascript
function List(runner, options) { Base.call(this, runner, options); var self = this; var n = 0; runner.on(EVENT_RUN_BEGIN, function() { console.log(); }); runner.on(EVENT_TEST_BEGIN, function(test) { process.stdout.write(color('pass', ' ' + test.fullTitle() + ': ')); }); runner.on(EVENT_TEST_PENDING, function(test) { var fmt = color('checkmark', ' -') + color('pending', ' %s'); console.log(fmt, test.fullTitle()); }); runner.on(EVENT_TEST_PASS, function(test) { var fmt = color('checkmark', ' ' + Base.symbols.ok) + color('pass', ' %s: ') + color(test.speed, '%dms'); cursor.CR(); console.log(fmt, test.fullTitle(), test.duration); }); runner.on(EVENT_TEST_FAIL, function(test) { cursor.CR(); console.log(color('fail', ' %d) %s'), ++n, test.fullTitle()); }); runner.once(EVENT_RUN_END, self.epilogue.bind(self)); }
[ "function", "List", "(", "runner", ",", "options", ")", "{", "Base", ".", "call", "(", "this", ",", "runner", ",", "options", ")", ";", "var", "self", "=", "this", ";", "var", "n", "=", "0", ";", "runner", ".", "on", "(", "EVENT_RUN_BEGIN", ",", "function", "(", ")", "{", "console", ".", "log", "(", ")", ";", "}", ")", ";", "runner", ".", "on", "(", "EVENT_TEST_BEGIN", ",", "function", "(", "test", ")", "{", "process", ".", "stdout", ".", "write", "(", "color", "(", "'pass'", ",", "' '", "+", "test", ".", "fullTitle", "(", ")", "+", "': '", ")", ")", ";", "}", ")", ";", "runner", ".", "on", "(", "EVENT_TEST_PENDING", ",", "function", "(", "test", ")", "{", "var", "fmt", "=", "color", "(", "'checkmark'", ",", "' -'", ")", "+", "color", "(", "'pending'", ",", "' %s'", ")", ";", "console", ".", "log", "(", "fmt", ",", "test", ".", "fullTitle", "(", ")", ")", ";", "}", ")", ";", "runner", ".", "on", "(", "EVENT_TEST_PASS", ",", "function", "(", "test", ")", "{", "var", "fmt", "=", "color", "(", "'checkmark'", ",", "' '", "+", "Base", ".", "symbols", ".", "ok", ")", "+", "color", "(", "'pass'", ",", "' %s: '", ")", "+", "color", "(", "test", ".", "speed", ",", "'%dms'", ")", ";", "cursor", ".", "CR", "(", ")", ";", "console", ".", "log", "(", "fmt", ",", "test", ".", "fullTitle", "(", ")", ",", "test", ".", "duration", ")", ";", "}", ")", ";", "runner", ".", "on", "(", "EVENT_TEST_FAIL", ",", "function", "(", "test", ")", "{", "cursor", ".", "CR", "(", ")", ";", "console", ".", "log", "(", "color", "(", "'fail'", ",", "' %d) %s'", ")", ",", "++", "n", ",", "test", ".", "fullTitle", "(", ")", ")", ";", "}", ")", ";", "runner", ".", "once", "(", "EVENT_RUN_END", ",", "self", ".", "epilogue", ".", "bind", "(", "self", ")", ")", ";", "}" ]
Constructs a new `List` reporter instance. @public @class @memberof Mocha.reporters @extends Mocha.reporters.Base @param {Runner} runner - Instance triggers reporter actions. @param {Object} [options] - runner options
[ "Constructs", "a", "new", "List", "reporter", "instance", "." ]
9b00fedb610241e33f7592c40164e42a38a793cf
https://github.com/mochajs/mocha/blob/9b00fedb610241e33f7592c40164e42a38a793cf/lib/reporters/list.js#L37-L71
1,437
mochajs/mocha
lib/reporters/html.js
text
function text(el, contents) { if (el.textContent) { el.textContent = contents; } else { el.innerText = contents; } }
javascript
function text(el, contents) { if (el.textContent) { el.textContent = contents; } else { el.innerText = contents; } }
[ "function", "text", "(", "el", ",", "contents", ")", "{", "if", "(", "el", ".", "textContent", ")", "{", "el", ".", "textContent", "=", "contents", ";", "}", "else", "{", "el", ".", "innerText", "=", "contents", ";", "}", "}" ]
Set an element's text contents. @param {HTMLElement} el @param {string} contents
[ "Set", "an", "element", "s", "text", "contents", "." ]
9b00fedb610241e33f7592c40164e42a38a793cf
https://github.com/mochajs/mocha/blob/9b00fedb610241e33f7592c40164e42a38a793cf/lib/reporters/html.js#L371-L377
1,438
mochajs/mocha
lib/reporters/dot.js
Dot
function Dot(runner, options) { Base.call(this, runner, options); var self = this; var width = (Base.window.width * 0.75) | 0; var n = -1; runner.on(EVENT_RUN_BEGIN, function() { process.stdout.write('\n'); }); runner.on(EVENT_TEST_PENDING, function() { if (++n % width === 0) { process.stdout.write('\n '); } process.stdout.write(Base.color('pending', Base.symbols.comma)); }); runner.on(EVENT_TEST_PASS, function(test) { if (++n % width === 0) { process.stdout.write('\n '); } if (test.speed === 'slow') { process.stdout.write(Base.color('bright yellow', Base.symbols.dot)); } else { process.stdout.write(Base.color(test.speed, Base.symbols.dot)); } }); runner.on(EVENT_TEST_FAIL, function() { if (++n % width === 0) { process.stdout.write('\n '); } process.stdout.write(Base.color('fail', Base.symbols.bang)); }); runner.once(EVENT_RUN_END, function() { console.log(); self.epilogue(); }); }
javascript
function Dot(runner, options) { Base.call(this, runner, options); var self = this; var width = (Base.window.width * 0.75) | 0; var n = -1; runner.on(EVENT_RUN_BEGIN, function() { process.stdout.write('\n'); }); runner.on(EVENT_TEST_PENDING, function() { if (++n % width === 0) { process.stdout.write('\n '); } process.stdout.write(Base.color('pending', Base.symbols.comma)); }); runner.on(EVENT_TEST_PASS, function(test) { if (++n % width === 0) { process.stdout.write('\n '); } if (test.speed === 'slow') { process.stdout.write(Base.color('bright yellow', Base.symbols.dot)); } else { process.stdout.write(Base.color(test.speed, Base.symbols.dot)); } }); runner.on(EVENT_TEST_FAIL, function() { if (++n % width === 0) { process.stdout.write('\n '); } process.stdout.write(Base.color('fail', Base.symbols.bang)); }); runner.once(EVENT_RUN_END, function() { console.log(); self.epilogue(); }); }
[ "function", "Dot", "(", "runner", ",", "options", ")", "{", "Base", ".", "call", "(", "this", ",", "runner", ",", "options", ")", ";", "var", "self", "=", "this", ";", "var", "width", "=", "(", "Base", ".", "window", ".", "width", "*", "0.75", ")", "|", "0", ";", "var", "n", "=", "-", "1", ";", "runner", ".", "on", "(", "EVENT_RUN_BEGIN", ",", "function", "(", ")", "{", "process", ".", "stdout", ".", "write", "(", "'\\n'", ")", ";", "}", ")", ";", "runner", ".", "on", "(", "EVENT_TEST_PENDING", ",", "function", "(", ")", "{", "if", "(", "++", "n", "%", "width", "===", "0", ")", "{", "process", ".", "stdout", ".", "write", "(", "'\\n '", ")", ";", "}", "process", ".", "stdout", ".", "write", "(", "Base", ".", "color", "(", "'pending'", ",", "Base", ".", "symbols", ".", "comma", ")", ")", ";", "}", ")", ";", "runner", ".", "on", "(", "EVENT_TEST_PASS", ",", "function", "(", "test", ")", "{", "if", "(", "++", "n", "%", "width", "===", "0", ")", "{", "process", ".", "stdout", ".", "write", "(", "'\\n '", ")", ";", "}", "if", "(", "test", ".", "speed", "===", "'slow'", ")", "{", "process", ".", "stdout", ".", "write", "(", "Base", ".", "color", "(", "'bright yellow'", ",", "Base", ".", "symbols", ".", "dot", ")", ")", ";", "}", "else", "{", "process", ".", "stdout", ".", "write", "(", "Base", ".", "color", "(", "test", ".", "speed", ",", "Base", ".", "symbols", ".", "dot", ")", ")", ";", "}", "}", ")", ";", "runner", ".", "on", "(", "EVENT_TEST_FAIL", ",", "function", "(", ")", "{", "if", "(", "++", "n", "%", "width", "===", "0", ")", "{", "process", ".", "stdout", ".", "write", "(", "'\\n '", ")", ";", "}", "process", ".", "stdout", ".", "write", "(", "Base", ".", "color", "(", "'fail'", ",", "Base", ".", "symbols", ".", "bang", ")", ")", ";", "}", ")", ";", "runner", ".", "once", "(", "EVENT_RUN_END", ",", "function", "(", ")", "{", "console", ".", "log", "(", ")", ";", "self", ".", "epilogue", "(", ")", ";", "}", ")", ";", "}" ]
Constructs a new `Dot` reporter instance. @public @class @memberof Mocha.reporters @extends Mocha.reporters.Base @param {Runner} runner - Instance triggers reporter actions. @param {Object} [options] - runner options
[ "Constructs", "a", "new", "Dot", "reporter", "instance", "." ]
9b00fedb610241e33f7592c40164e42a38a793cf
https://github.com/mochajs/mocha/blob/9b00fedb610241e33f7592c40164e42a38a793cf/lib/reporters/dot.js#L34-L74
1,439
mochajs/mocha
lib/runner.js
extraGlobals
function extraGlobals() { if (typeof process === 'object' && typeof process.version === 'string') { var parts = process.version.split('.'); var nodeVersion = parts.reduce(function(a, v) { return (a << 8) | v; }); // 'errno' was renamed to process._errno in v0.9.11. if (nodeVersion < 0x00090b) { return ['errno']; } } return []; }
javascript
function extraGlobals() { if (typeof process === 'object' && typeof process.version === 'string') { var parts = process.version.split('.'); var nodeVersion = parts.reduce(function(a, v) { return (a << 8) | v; }); // 'errno' was renamed to process._errno in v0.9.11. if (nodeVersion < 0x00090b) { return ['errno']; } } return []; }
[ "function", "extraGlobals", "(", ")", "{", "if", "(", "typeof", "process", "===", "'object'", "&&", "typeof", "process", ".", "version", "===", "'string'", ")", "{", "var", "parts", "=", "process", ".", "version", ".", "split", "(", "'.'", ")", ";", "var", "nodeVersion", "=", "parts", ".", "reduce", "(", "function", "(", "a", ",", "v", ")", "{", "return", "(", "a", "<<", "8", ")", "|", "v", ";", "}", ")", ";", "// 'errno' was renamed to process._errno in v0.9.11.", "if", "(", "nodeVersion", "<", "0x00090b", ")", "{", "return", "[", "'errno'", "]", ";", "}", "}", "return", "[", "]", ";", "}" ]
Array of globals dependent on the environment. @return {Array} @deprecated @todo remove; long since unsupported @private
[ "Array", "of", "globals", "dependent", "on", "the", "environment", "." ]
9b00fedb610241e33f7592c40164e42a38a793cf
https://github.com/mochajs/mocha/blob/9b00fedb610241e33f7592c40164e42a38a793cf/lib/runner.js#L1027-L1041
1,440
goldfire/howler.js
examples/3d/js/camera.js
function(resolution) { this.width = canvas.width = window.innerWidth; this.height = canvas.height = window.innerHeight; this.resolution = resolution; this.spacing = this.width / resolution; this.focalLen = this.height / this.width; this.range = isMobile ? 9 : 18; this.lightRange = 9; this.scale = canvas.width / 1200; }
javascript
function(resolution) { this.width = canvas.width = window.innerWidth; this.height = canvas.height = window.innerHeight; this.resolution = resolution; this.spacing = this.width / resolution; this.focalLen = this.height / this.width; this.range = isMobile ? 9 : 18; this.lightRange = 9; this.scale = canvas.width / 1200; }
[ "function", "(", "resolution", ")", "{", "this", ".", "width", "=", "canvas", ".", "width", "=", "window", ".", "innerWidth", ";", "this", ".", "height", "=", "canvas", ".", "height", "=", "window", ".", "innerHeight", ";", "this", ".", "resolution", "=", "resolution", ";", "this", ".", "spacing", "=", "this", ".", "width", "/", "resolution", ";", "this", ".", "focalLen", "=", "this", ".", "height", "/", "this", ".", "width", ";", "this", ".", "range", "=", "isMobile", "?", "9", ":", "18", ";", "this", ".", "lightRange", "=", "9", ";", "this", ".", "scale", "=", "canvas", ".", "width", "/", "1200", ";", "}" ]
Camera that draws everything you see on the screen from the player's perspective. @param {Number} resolution Resolution to render at (higher has better quality, but lower performance).
[ "Camera", "that", "draws", "everything", "you", "see", "on", "the", "screen", "from", "the", "player", "s", "perspective", "." ]
030db918dd8ce640afd57e172418472497e8f113
https://github.com/goldfire/howler.js/blob/030db918dd8ce640afd57e172418472497e8f113/examples/3d/js/camera.js#L17-L26
1,441
goldfire/howler.js
examples/3d/js/camera.js
function() { var dir = game.player.dir; var sky = game.map.skybox; var ambient = game.map.light; var width = sky.width * (this.height / sky.height) * 2; var left = (dir / circle) * -width; ctx.save(); ctx.drawImage(sky.image, left, 0, width, this.height); if (left < width - this.width) { ctx.drawImage(sky.image, left + width, 0, width, this.height); } if (ambient > 0) { ctx.fillStyle = '#fff'; ctx.globalAlpha = ambient * 0.1; ctx.fillRect(0, this.height * 0.5, this.width, this.height * 0.5); } ctx.restore(); }
javascript
function() { var dir = game.player.dir; var sky = game.map.skybox; var ambient = game.map.light; var width = sky.width * (this.height / sky.height) * 2; var left = (dir / circle) * -width; ctx.save(); ctx.drawImage(sky.image, left, 0, width, this.height); if (left < width - this.width) { ctx.drawImage(sky.image, left + width, 0, width, this.height); } if (ambient > 0) { ctx.fillStyle = '#fff'; ctx.globalAlpha = ambient * 0.1; ctx.fillRect(0, this.height * 0.5, this.width, this.height * 0.5); } ctx.restore(); }
[ "function", "(", ")", "{", "var", "dir", "=", "game", ".", "player", ".", "dir", ";", "var", "sky", "=", "game", ".", "map", ".", "skybox", ";", "var", "ambient", "=", "game", ".", "map", ".", "light", ";", "var", "width", "=", "sky", ".", "width", "*", "(", "this", ".", "height", "/", "sky", ".", "height", ")", "*", "2", ";", "var", "left", "=", "(", "dir", "/", "circle", ")", "*", "-", "width", ";", "ctx", ".", "save", "(", ")", ";", "ctx", ".", "drawImage", "(", "sky", ".", "image", ",", "left", ",", "0", ",", "width", ",", "this", ".", "height", ")", ";", "if", "(", "left", "<", "width", "-", "this", ".", "width", ")", "{", "ctx", ".", "drawImage", "(", "sky", ".", "image", ",", "left", "+", "width", ",", "0", ",", "width", ",", "this", ".", "height", ")", ";", "}", "if", "(", "ambient", ">", "0", ")", "{", "ctx", ".", "fillStyle", "=", "'#fff'", ";", "ctx", ".", "globalAlpha", "=", "ambient", "*", "0.1", ";", "ctx", ".", "fillRect", "(", "0", ",", "this", ".", "height", "*", "0.5", ",", "this", ".", "width", ",", "this", ".", "height", "*", "0.5", ")", ";", "}", "ctx", ".", "restore", "(", ")", ";", "}" ]
Draw the skybox based on the player's direction.
[ "Draw", "the", "skybox", "based", "on", "the", "player", "s", "direction", "." ]
030db918dd8ce640afd57e172418472497e8f113
https://github.com/goldfire/howler.js/blob/030db918dd8ce640afd57e172418472497e8f113/examples/3d/js/camera.js#L31-L49
1,442
goldfire/howler.js
examples/3d/js/camera.js
function() { var x, angle, ray; ctx.save(); for (var col=0; col<this.resolution; col++) { x = col / this.resolution - 0.5; angle = Math.atan2(x, this.focalLen); ray = game.map.cast(game.player, game.player.dir + angle, this.range); this.drawCol(col, ray, angle); } ctx.restore(); }
javascript
function() { var x, angle, ray; ctx.save(); for (var col=0; col<this.resolution; col++) { x = col / this.resolution - 0.5; angle = Math.atan2(x, this.focalLen); ray = game.map.cast(game.player, game.player.dir + angle, this.range); this.drawCol(col, ray, angle); } ctx.restore(); }
[ "function", "(", ")", "{", "var", "x", ",", "angle", ",", "ray", ";", "ctx", ".", "save", "(", ")", ";", "for", "(", "var", "col", "=", "0", ";", "col", "<", "this", ".", "resolution", ";", "col", "++", ")", "{", "x", "=", "col", "/", "this", ".", "resolution", "-", "0.5", ";", "angle", "=", "Math", ".", "atan2", "(", "x", ",", "this", ".", "focalLen", ")", ";", "ray", "=", "game", ".", "map", ".", "cast", "(", "game", ".", "player", ",", "game", ".", "player", ".", "dir", "+", "angle", ",", "this", ".", "range", ")", ";", "this", ".", "drawCol", "(", "col", ",", "ray", ",", "angle", ")", ";", "}", "ctx", ".", "restore", "(", ")", ";", "}" ]
Based on the resolution, split the scene up and draw it column by column.
[ "Based", "on", "the", "resolution", "split", "the", "scene", "up", "and", "draw", "it", "column", "by", "column", "." ]
030db918dd8ce640afd57e172418472497e8f113
https://github.com/goldfire/howler.js/blob/030db918dd8ce640afd57e172418472497e8f113/examples/3d/js/camera.js#L54-L68
1,443
goldfire/howler.js
examples/3d/js/camera.js
function(col, ray, angle) { var step, drops, rain, texX, wall; var tex1 = game.map.wall; var tex2 = game.map.speaker; var left = Math.floor(col * this.spacing); var width = Math.ceil(this.spacing); var hit = -1; // Find the next wall hit. while (++hit < ray.length && ray[hit].height <= 0); // Draw the wall sections and rain drops. for (var i=ray.length - 1; i>=0; i--) { step = ray[i]; drops = Math.pow(Math.random(), 100) * i; rain = (drops > 0) && this.project(0.2, angle, step.dist); var tex = (step.type === 1) ? tex1 : tex2; if (i === hit) { texX = Math.floor(tex.width * step.offset); wall = this.project(step.height, angle, step.dist); ctx.globalAlpha = 1; ctx.drawImage(tex.image, texX, 0, 1, tex.height, left, wall.top, width, wall.height); ctx.fillStyle = '#000'; ctx.globalAlpha = Math.max((step.dist + step.shading) / this.lightRange - game.map.light, 0); ctx.fillRect(left, wall.top, width, wall.height); } ctx.fillStyle = '#fff'; ctx.globalAlpha = 0.15; while (--drops > 0) { ctx.fillRect(left, Math.random() * rain.top, 1, rain.height); } } }
javascript
function(col, ray, angle) { var step, drops, rain, texX, wall; var tex1 = game.map.wall; var tex2 = game.map.speaker; var left = Math.floor(col * this.spacing); var width = Math.ceil(this.spacing); var hit = -1; // Find the next wall hit. while (++hit < ray.length && ray[hit].height <= 0); // Draw the wall sections and rain drops. for (var i=ray.length - 1; i>=0; i--) { step = ray[i]; drops = Math.pow(Math.random(), 100) * i; rain = (drops > 0) && this.project(0.2, angle, step.dist); var tex = (step.type === 1) ? tex1 : tex2; if (i === hit) { texX = Math.floor(tex.width * step.offset); wall = this.project(step.height, angle, step.dist); ctx.globalAlpha = 1; ctx.drawImage(tex.image, texX, 0, 1, tex.height, left, wall.top, width, wall.height); ctx.fillStyle = '#000'; ctx.globalAlpha = Math.max((step.dist + step.shading) / this.lightRange - game.map.light, 0); ctx.fillRect(left, wall.top, width, wall.height); } ctx.fillStyle = '#fff'; ctx.globalAlpha = 0.15; while (--drops > 0) { ctx.fillRect(left, Math.random() * rain.top, 1, rain.height); } } }
[ "function", "(", "col", ",", "ray", ",", "angle", ")", "{", "var", "step", ",", "drops", ",", "rain", ",", "texX", ",", "wall", ";", "var", "tex1", "=", "game", ".", "map", ".", "wall", ";", "var", "tex2", "=", "game", ".", "map", ".", "speaker", ";", "var", "left", "=", "Math", ".", "floor", "(", "col", "*", "this", ".", "spacing", ")", ";", "var", "width", "=", "Math", ".", "ceil", "(", "this", ".", "spacing", ")", ";", "var", "hit", "=", "-", "1", ";", "// Find the next wall hit.", "while", "(", "++", "hit", "<", "ray", ".", "length", "&&", "ray", "[", "hit", "]", ".", "height", "<=", "0", ")", ";", "// Draw the wall sections and rain drops.", "for", "(", "var", "i", "=", "ray", ".", "length", "-", "1", ";", "i", ">=", "0", ";", "i", "--", ")", "{", "step", "=", "ray", "[", "i", "]", ";", "drops", "=", "Math", ".", "pow", "(", "Math", ".", "random", "(", ")", ",", "100", ")", "*", "i", ";", "rain", "=", "(", "drops", ">", "0", ")", "&&", "this", ".", "project", "(", "0.2", ",", "angle", ",", "step", ".", "dist", ")", ";", "var", "tex", "=", "(", "step", ".", "type", "===", "1", ")", "?", "tex1", ":", "tex2", ";", "if", "(", "i", "===", "hit", ")", "{", "texX", "=", "Math", ".", "floor", "(", "tex", ".", "width", "*", "step", ".", "offset", ")", ";", "wall", "=", "this", ".", "project", "(", "step", ".", "height", ",", "angle", ",", "step", ".", "dist", ")", ";", "ctx", ".", "globalAlpha", "=", "1", ";", "ctx", ".", "drawImage", "(", "tex", ".", "image", ",", "texX", ",", "0", ",", "1", ",", "tex", ".", "height", ",", "left", ",", "wall", ".", "top", ",", "width", ",", "wall", ".", "height", ")", ";", "ctx", ".", "fillStyle", "=", "'#000'", ";", "ctx", ".", "globalAlpha", "=", "Math", ".", "max", "(", "(", "step", ".", "dist", "+", "step", ".", "shading", ")", "/", "this", ".", "lightRange", "-", "game", ".", "map", ".", "light", ",", "0", ")", ";", "ctx", ".", "fillRect", "(", "left", ",", "wall", ".", "top", ",", "width", ",", "wall", ".", "height", ")", ";", "}", "ctx", ".", "fillStyle", "=", "'#fff'", ";", "ctx", ".", "globalAlpha", "=", "0.15", ";", "while", "(", "--", "drops", ">", "0", ")", "{", "ctx", ".", "fillRect", "(", "left", ",", "Math", ".", "random", "(", ")", "*", "rain", ".", "top", ",", "1", ",", "rain", ".", "height", ")", ";", "}", "}", "}" ]
Draw a single column of the scene. @param {Number} col Which column in the sequence. @param {Array} ray Ray to follow. @param {Number} angle Angle of the ray.
[ "Draw", "a", "single", "column", "of", "the", "scene", "." ]
030db918dd8ce640afd57e172418472497e8f113
https://github.com/goldfire/howler.js/blob/030db918dd8ce640afd57e172418472497e8f113/examples/3d/js/camera.js#L76-L113
1,444
goldfire/howler.js
examples/3d/js/camera.js
function() { var hand = game.player.hand; var steps = game.player.steps; var scaleFactor = this.scale * 6; // Calculate the position of each hand relative to the steps taken. var xScale = Math.cos(steps * 2); var yScale = Math.sin(steps * 4); var bobX = xScale * scaleFactor; var bobY = yScale * scaleFactor; var x = (canvas.width - (hand.width * this.scale) + scaleFactor) + bobX; var y = (canvas.height - (hand.height * this.scale) + scaleFactor) + bobY; var w = hand.width * this.scale; var h = hand.height * this.scale; ctx.drawImage(hand.image, x, y, w, h); }
javascript
function() { var hand = game.player.hand; var steps = game.player.steps; var scaleFactor = this.scale * 6; // Calculate the position of each hand relative to the steps taken. var xScale = Math.cos(steps * 2); var yScale = Math.sin(steps * 4); var bobX = xScale * scaleFactor; var bobY = yScale * scaleFactor; var x = (canvas.width - (hand.width * this.scale) + scaleFactor) + bobX; var y = (canvas.height - (hand.height * this.scale) + scaleFactor) + bobY; var w = hand.width * this.scale; var h = hand.height * this.scale; ctx.drawImage(hand.image, x, y, w, h); }
[ "function", "(", ")", "{", "var", "hand", "=", "game", ".", "player", ".", "hand", ";", "var", "steps", "=", "game", ".", "player", ".", "steps", ";", "var", "scaleFactor", "=", "this", ".", "scale", "*", "6", ";", "// Calculate the position of each hand relative to the steps taken.", "var", "xScale", "=", "Math", ".", "cos", "(", "steps", "*", "2", ")", ";", "var", "yScale", "=", "Math", ".", "sin", "(", "steps", "*", "4", ")", ";", "var", "bobX", "=", "xScale", "*", "scaleFactor", ";", "var", "bobY", "=", "yScale", "*", "scaleFactor", ";", "var", "x", "=", "(", "canvas", ".", "width", "-", "(", "hand", ".", "width", "*", "this", ".", "scale", ")", "+", "scaleFactor", ")", "+", "bobX", ";", "var", "y", "=", "(", "canvas", ".", "height", "-", "(", "hand", ".", "height", "*", "this", ".", "scale", ")", "+", "scaleFactor", ")", "+", "bobY", ";", "var", "w", "=", "hand", ".", "width", "*", "this", ".", "scale", ";", "var", "h", "=", "hand", ".", "height", "*", "this", ".", "scale", ";", "ctx", ".", "drawImage", "(", "hand", ".", "image", ",", "x", ",", "y", ",", "w", ",", "h", ")", ";", "}" ]
Draw the hand holding the gun and implement a "bobbing" to simulate walking.
[ "Draw", "the", "hand", "holding", "the", "gun", "and", "implement", "a", "bobbing", "to", "simulate", "walking", "." ]
030db918dd8ce640afd57e172418472497e8f113
https://github.com/goldfire/howler.js/blob/030db918dd8ce640afd57e172418472497e8f113/examples/3d/js/camera.js#L118-L134
1,445
goldfire/howler.js
examples/3d/js/camera.js
function(height, angle, dist) { var z = dist * Math.cos(angle); var wallH = this.height * height / z; var bottom = this.height / 2 * (1 + 1 / z); return { top: bottom - wallH, height: wallH }; }
javascript
function(height, angle, dist) { var z = dist * Math.cos(angle); var wallH = this.height * height / z; var bottom = this.height / 2 * (1 + 1 / z); return { top: bottom - wallH, height: wallH }; }
[ "function", "(", "height", ",", "angle", ",", "dist", ")", "{", "var", "z", "=", "dist", "*", "Math", ".", "cos", "(", "angle", ")", ";", "var", "wallH", "=", "this", ".", "height", "*", "height", "/", "z", ";", "var", "bottom", "=", "this", ".", "height", "/", "2", "*", "(", "1", "+", "1", "/", "z", ")", ";", "return", "{", "top", ":", "bottom", "-", "wallH", ",", "height", ":", "wallH", "}", ";", "}" ]
Based on the angle and distance, determine how we are going to project the image. @param {Number} height Wall piece height. @param {Number} angle Angle of the ray. @param {Number} dist Distnace from the player. @return {Object} top and height
[ "Based", "on", "the", "angle", "and", "distance", "determine", "how", "we", "are", "going", "to", "project", "the", "image", "." ]
030db918dd8ce640afd57e172418472497e8f113
https://github.com/goldfire/howler.js/blob/030db918dd8ce640afd57e172418472497e8f113/examples/3d/js/camera.js#L143-L152
1,446
goldfire/howler.js
examples/sprite/sprite.js
function(options) { var self = this; self.sounds = []; // Setup the options to define this sprite display. self._width = options.width; self._left = options.left; self._spriteMap = options.spriteMap; self._sprite = options.sprite; self.setupListeners(); // Create our audio sprite definition. self.sound = new Howl({ src: options.src, sprite: options.sprite }); // Setup a resize event and fire it to setup our sprite overlays. window.addEventListener('resize', function() { self.resize(); }, false); self.resize(); // Begin the progress step tick. requestAnimationFrame(self.step.bind(self)); }
javascript
function(options) { var self = this; self.sounds = []; // Setup the options to define this sprite display. self._width = options.width; self._left = options.left; self._spriteMap = options.spriteMap; self._sprite = options.sprite; self.setupListeners(); // Create our audio sprite definition. self.sound = new Howl({ src: options.src, sprite: options.sprite }); // Setup a resize event and fire it to setup our sprite overlays. window.addEventListener('resize', function() { self.resize(); }, false); self.resize(); // Begin the progress step tick. requestAnimationFrame(self.step.bind(self)); }
[ "function", "(", "options", ")", "{", "var", "self", "=", "this", ";", "self", ".", "sounds", "=", "[", "]", ";", "// Setup the options to define this sprite display.", "self", ".", "_width", "=", "options", ".", "width", ";", "self", ".", "_left", "=", "options", ".", "left", ";", "self", ".", "_spriteMap", "=", "options", ".", "spriteMap", ";", "self", ".", "_sprite", "=", "options", ".", "sprite", ";", "self", ".", "setupListeners", "(", ")", ";", "// Create our audio sprite definition.", "self", ".", "sound", "=", "new", "Howl", "(", "{", "src", ":", "options", ".", "src", ",", "sprite", ":", "options", ".", "sprite", "}", ")", ";", "// Setup a resize event and fire it to setup our sprite overlays.", "window", ".", "addEventListener", "(", "'resize'", ",", "function", "(", ")", "{", "self", ".", "resize", "(", ")", ";", "}", ",", "false", ")", ";", "self", ".", "resize", "(", ")", ";", "// Begin the progress step tick.", "requestAnimationFrame", "(", "self", ".", "step", ".", "bind", "(", "self", ")", ")", ";", "}" ]
Sprite class containing the state of our sprites to play and their progress. @param {Object} options Settings to pass into and setup the sound and visuals.
[ "Sprite", "class", "containing", "the", "state", "of", "our", "sprites", "to", "play", "and", "their", "progress", "." ]
030db918dd8ce640afd57e172418472497e8f113
https://github.com/goldfire/howler.js/blob/030db918dd8ce640afd57e172418472497e8f113/examples/sprite/sprite.js#L21-L47
1,447
goldfire/howler.js
examples/sprite/sprite.js
function() { var self = this; var keys = Object.keys(self._spriteMap); keys.forEach(function(key) { window[key].addEventListener('click', function() { self.play(key); }, false); }); }
javascript
function() { var self = this; var keys = Object.keys(self._spriteMap); keys.forEach(function(key) { window[key].addEventListener('click', function() { self.play(key); }, false); }); }
[ "function", "(", ")", "{", "var", "self", "=", "this", ";", "var", "keys", "=", "Object", ".", "keys", "(", "self", ".", "_spriteMap", ")", ";", "keys", ".", "forEach", "(", "function", "(", "key", ")", "{", "window", "[", "key", "]", ".", "addEventListener", "(", "'click'", ",", "function", "(", ")", "{", "self", ".", "play", "(", "key", ")", ";", "}", ",", "false", ")", ";", "}", ")", ";", "}" ]
Setup the listeners for each sprite click area.
[ "Setup", "the", "listeners", "for", "each", "sprite", "click", "area", "." ]
030db918dd8ce640afd57e172418472497e8f113
https://github.com/goldfire/howler.js/blob/030db918dd8ce640afd57e172418472497e8f113/examples/sprite/sprite.js#L52-L61
1,448
goldfire/howler.js
examples/sprite/sprite.js
function(key) { var self = this; var sprite = self._spriteMap[key]; // Play the sprite sound and capture the ID. var id = self.sound.play(sprite); // Create a progress element and begin visually tracking it. var elm = document.createElement('div'); elm.className = 'progress'; elm.id = id; elm.dataset.sprite = sprite; window[key].appendChild(elm); self.sounds.push(elm); // When this sound is finished, remove the progress element. self.sound.once('end', function() { var index = self.sounds.indexOf(elm); if (index >= 0) { self.sounds.splice(index, 1); window[key].removeChild(elm); } }, id); }
javascript
function(key) { var self = this; var sprite = self._spriteMap[key]; // Play the sprite sound and capture the ID. var id = self.sound.play(sprite); // Create a progress element and begin visually tracking it. var elm = document.createElement('div'); elm.className = 'progress'; elm.id = id; elm.dataset.sprite = sprite; window[key].appendChild(elm); self.sounds.push(elm); // When this sound is finished, remove the progress element. self.sound.once('end', function() { var index = self.sounds.indexOf(elm); if (index >= 0) { self.sounds.splice(index, 1); window[key].removeChild(elm); } }, id); }
[ "function", "(", "key", ")", "{", "var", "self", "=", "this", ";", "var", "sprite", "=", "self", ".", "_spriteMap", "[", "key", "]", ";", "// Play the sprite sound and capture the ID.", "var", "id", "=", "self", ".", "sound", ".", "play", "(", "sprite", ")", ";", "// Create a progress element and begin visually tracking it.", "var", "elm", "=", "document", ".", "createElement", "(", "'div'", ")", ";", "elm", ".", "className", "=", "'progress'", ";", "elm", ".", "id", "=", "id", ";", "elm", ".", "dataset", ".", "sprite", "=", "sprite", ";", "window", "[", "key", "]", ".", "appendChild", "(", "elm", ")", ";", "self", ".", "sounds", ".", "push", "(", "elm", ")", ";", "// When this sound is finished, remove the progress element.", "self", ".", "sound", ".", "once", "(", "'end'", ",", "function", "(", ")", "{", "var", "index", "=", "self", ".", "sounds", ".", "indexOf", "(", "elm", ")", ";", "if", "(", "index", ">=", "0", ")", "{", "self", ".", "sounds", ".", "splice", "(", "index", ",", "1", ")", ";", "window", "[", "key", "]", ".", "removeChild", "(", "elm", ")", ";", "}", "}", ",", "id", ")", ";", "}" ]
Play a sprite when clicked and track the progress. @param {String} key Key in the sprite map object.
[ "Play", "a", "sprite", "when", "clicked", "and", "track", "the", "progress", "." ]
030db918dd8ce640afd57e172418472497e8f113
https://github.com/goldfire/howler.js/blob/030db918dd8ce640afd57e172418472497e8f113/examples/sprite/sprite.js#L67-L90
1,449
goldfire/howler.js
examples/sprite/sprite.js
function() { var self = this; // Calculate the scale of our window from "full" size. var scale = window.innerWidth / 3600; // Resize and reposition the sprite overlays. var keys = Object.keys(self._spriteMap); for (var i=0; i<keys.length; i++) { var sprite = window[keys[i]]; sprite.style.width = Math.round(self._width[i] * scale) + 'px'; if (self._left[i]) { sprite.style.left = Math.round(self._left[i] * scale) + 'px'; } } }
javascript
function() { var self = this; // Calculate the scale of our window from "full" size. var scale = window.innerWidth / 3600; // Resize and reposition the sprite overlays. var keys = Object.keys(self._spriteMap); for (var i=0; i<keys.length; i++) { var sprite = window[keys[i]]; sprite.style.width = Math.round(self._width[i] * scale) + 'px'; if (self._left[i]) { sprite.style.left = Math.round(self._left[i] * scale) + 'px'; } } }
[ "function", "(", ")", "{", "var", "self", "=", "this", ";", "// Calculate the scale of our window from \"full\" size.", "var", "scale", "=", "window", ".", "innerWidth", "/", "3600", ";", "// Resize and reposition the sprite overlays.", "var", "keys", "=", "Object", ".", "keys", "(", "self", ".", "_spriteMap", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "keys", ".", "length", ";", "i", "++", ")", "{", "var", "sprite", "=", "window", "[", "keys", "[", "i", "]", "]", ";", "sprite", ".", "style", ".", "width", "=", "Math", ".", "round", "(", "self", ".", "_width", "[", "i", "]", "*", "scale", ")", "+", "'px'", ";", "if", "(", "self", ".", "_left", "[", "i", "]", ")", "{", "sprite", ".", "style", ".", "left", "=", "Math", ".", "round", "(", "self", ".", "_left", "[", "i", "]", "*", "scale", ")", "+", "'px'", ";", "}", "}", "}" ]
Called on window resize to correctly psotion and size the click overlays.
[ "Called", "on", "window", "resize", "to", "correctly", "psotion", "and", "size", "the", "click", "overlays", "." ]
030db918dd8ce640afd57e172418472497e8f113
https://github.com/goldfire/howler.js/blob/030db918dd8ce640afd57e172418472497e8f113/examples/sprite/sprite.js#L95-L110
1,450
goldfire/howler.js
examples/sprite/sprite.js
function() { var self = this; // Loop through all active sounds and update their progress bar. for (var i=0; i<self.sounds.length; i++) { var id = parseInt(self.sounds[i].id, 10); var offset = self._sprite[self.sounds[i].dataset.sprite][0]; var seek = (self.sound.seek(id) || 0) - (offset / 1000); self.sounds[i].style.width = (((seek / self.sound.duration(id)) * 100) || 0) + '%'; } requestAnimationFrame(self.step.bind(self)); }
javascript
function() { var self = this; // Loop through all active sounds and update their progress bar. for (var i=0; i<self.sounds.length; i++) { var id = parseInt(self.sounds[i].id, 10); var offset = self._sprite[self.sounds[i].dataset.sprite][0]; var seek = (self.sound.seek(id) || 0) - (offset / 1000); self.sounds[i].style.width = (((seek / self.sound.duration(id)) * 100) || 0) + '%'; } requestAnimationFrame(self.step.bind(self)); }
[ "function", "(", ")", "{", "var", "self", "=", "this", ";", "// Loop through all active sounds and update their progress bar.", "for", "(", "var", "i", "=", "0", ";", "i", "<", "self", ".", "sounds", ".", "length", ";", "i", "++", ")", "{", "var", "id", "=", "parseInt", "(", "self", ".", "sounds", "[", "i", "]", ".", "id", ",", "10", ")", ";", "var", "offset", "=", "self", ".", "_sprite", "[", "self", ".", "sounds", "[", "i", "]", ".", "dataset", ".", "sprite", "]", "[", "0", "]", ";", "var", "seek", "=", "(", "self", ".", "sound", ".", "seek", "(", "id", ")", "||", "0", ")", "-", "(", "offset", "/", "1000", ")", ";", "self", ".", "sounds", "[", "i", "]", ".", "style", ".", "width", "=", "(", "(", "(", "seek", "/", "self", ".", "sound", ".", "duration", "(", "id", ")", ")", "*", "100", ")", "||", "0", ")", "+", "'%'", ";", "}", "requestAnimationFrame", "(", "self", ".", "step", ".", "bind", "(", "self", ")", ")", ";", "}" ]
The step called within requestAnimationFrame to update the playback positions.
[ "The", "step", "called", "within", "requestAnimationFrame", "to", "update", "the", "playback", "positions", "." ]
030db918dd8ce640afd57e172418472497e8f113
https://github.com/goldfire/howler.js/blob/030db918dd8ce640afd57e172418472497e8f113/examples/sprite/sprite.js#L115-L127
1,451
goldfire/howler.js
examples/3d/js/controls.js
function() { // Define our control key codes and states. this.codes = { // Arrows 37: 'left', 39: 'right', 38: 'front', 40: 'back', // WASD 65: 'left', 68: 'right', 87: 'front', 83: 'back', }; this.states = {left: false, right: false, front: false, back: false}; // Setup the DOM listeners. document.addEventListener('keydown', this.key.bind(this, true), false); document.addEventListener('keyup', this.key.bind(this, false), false); document.addEventListener('touchstart', this.touch.bind(this), false); document.addEventListener('touchmove', this.touch.bind(this), false); document.addEventListener('touchend', this.touchEnd.bind(this), false); }
javascript
function() { // Define our control key codes and states. this.codes = { // Arrows 37: 'left', 39: 'right', 38: 'front', 40: 'back', // WASD 65: 'left', 68: 'right', 87: 'front', 83: 'back', }; this.states = {left: false, right: false, front: false, back: false}; // Setup the DOM listeners. document.addEventListener('keydown', this.key.bind(this, true), false); document.addEventListener('keyup', this.key.bind(this, false), false); document.addEventListener('touchstart', this.touch.bind(this), false); document.addEventListener('touchmove', this.touch.bind(this), false); document.addEventListener('touchend', this.touchEnd.bind(this), false); }
[ "function", "(", ")", "{", "// Define our control key codes and states.", "this", ".", "codes", "=", "{", "// Arrows", "37", ":", "'left'", ",", "39", ":", "'right'", ",", "38", ":", "'front'", ",", "40", ":", "'back'", ",", "// WASD", "65", ":", "'left'", ",", "68", ":", "'right'", ",", "87", ":", "'front'", ",", "83", ":", "'back'", ",", "}", ";", "this", ".", "states", "=", "{", "left", ":", "false", ",", "right", ":", "false", ",", "front", ":", "false", ",", "back", ":", "false", "}", ";", "// Setup the DOM listeners.", "document", ".", "addEventListener", "(", "'keydown'", ",", "this", ".", "key", ".", "bind", "(", "this", ",", "true", ")", ",", "false", ")", ";", "document", ".", "addEventListener", "(", "'keyup'", ",", "this", ".", "key", ".", "bind", "(", "this", ",", "false", ")", ",", "false", ")", ";", "document", ".", "addEventListener", "(", "'touchstart'", ",", "this", ".", "touch", ".", "bind", "(", "this", ")", ",", "false", ")", ";", "document", ".", "addEventListener", "(", "'touchmove'", ",", "this", ".", "touch", ".", "bind", "(", "this", ")", ",", "false", ")", ";", "document", ".", "addEventListener", "(", "'touchend'", ",", "this", ".", "touchEnd", ".", "bind", "(", "this", ")", ",", "false", ")", ";", "}" ]
Defines and handles the various controls.
[ "Defines", "and", "handles", "the", "various", "controls", "." ]
030db918dd8ce640afd57e172418472497e8f113
https://github.com/goldfire/howler.js/blob/030db918dd8ce640afd57e172418472497e8f113/examples/3d/js/controls.js#L16-L32
1,452
goldfire/howler.js
examples/3d/js/controls.js
function(pressed, event) { var state = this.codes[event.keyCode]; if (!state) { return; } this.states[state] = pressed; event.preventDefault && event.preventDefault(); event.stopPropagation && event.stopPropagation(); }
javascript
function(pressed, event) { var state = this.codes[event.keyCode]; if (!state) { return; } this.states[state] = pressed; event.preventDefault && event.preventDefault(); event.stopPropagation && event.stopPropagation(); }
[ "function", "(", "pressed", ",", "event", ")", "{", "var", "state", "=", "this", ".", "codes", "[", "event", ".", "keyCode", "]", ";", "if", "(", "!", "state", ")", "{", "return", ";", "}", "this", ".", "states", "[", "state", "]", "=", "pressed", ";", "event", ".", "preventDefault", "&&", "event", ".", "preventDefault", "(", ")", ";", "event", ".", "stopPropagation", "&&", "event", ".", "stopPropagation", "(", ")", ";", "}" ]
Handle all keydown and keyup events and update our internal controls state. @param {Boolean} pressed Whether or not the key is being pressed. @param {Object} event DOM event data including the key being pressed.
[ "Handle", "all", "keydown", "and", "keyup", "events", "and", "update", "our", "internal", "controls", "state", "." ]
030db918dd8ce640afd57e172418472497e8f113
https://github.com/goldfire/howler.js/blob/030db918dd8ce640afd57e172418472497e8f113/examples/3d/js/controls.js#L39-L49
1,453
goldfire/howler.js
examples/3d/js/controls.js
function(event) { var touches = event.touches[0]; // Reset the states. this.touchEnd(event); // Determine which key to simulate. if (touches.pageY < window.innerHeight * 0.3) { this.key(true, {keyCode: 38}); } else if (touches.pageY > window.innerHeight * 0.7) { this.key(true, {keyCode: 40}); } else if (touches.pageX < window.innerWidth * 0.5) { this.key(true, {keyCode: 37}); } else if (touches.pageX > window.innerWidth * 0.5) { this.key(true, {keyCode: 39}); } }
javascript
function(event) { var touches = event.touches[0]; // Reset the states. this.touchEnd(event); // Determine which key to simulate. if (touches.pageY < window.innerHeight * 0.3) { this.key(true, {keyCode: 38}); } else if (touches.pageY > window.innerHeight * 0.7) { this.key(true, {keyCode: 40}); } else if (touches.pageX < window.innerWidth * 0.5) { this.key(true, {keyCode: 37}); } else if (touches.pageX > window.innerWidth * 0.5) { this.key(true, {keyCode: 39}); } }
[ "function", "(", "event", ")", "{", "var", "touches", "=", "event", ".", "touches", "[", "0", "]", ";", "// Reset the states.", "this", ".", "touchEnd", "(", "event", ")", ";", "// Determine which key to simulate.", "if", "(", "touches", ".", "pageY", "<", "window", ".", "innerHeight", "*", "0.3", ")", "{", "this", ".", "key", "(", "true", ",", "{", "keyCode", ":", "38", "}", ")", ";", "}", "else", "if", "(", "touches", ".", "pageY", ">", "window", ".", "innerHeight", "*", "0.7", ")", "{", "this", ".", "key", "(", "true", ",", "{", "keyCode", ":", "40", "}", ")", ";", "}", "else", "if", "(", "touches", ".", "pageX", "<", "window", ".", "innerWidth", "*", "0.5", ")", "{", "this", ".", "key", "(", "true", ",", "{", "keyCode", ":", "37", "}", ")", ";", "}", "else", "if", "(", "touches", ".", "pageX", ">", "window", ".", "innerWidth", "*", "0.5", ")", "{", "this", ".", "key", "(", "true", ",", "{", "keyCode", ":", "39", "}", ")", ";", "}", "}" ]
Listen for touch events and determine which key to simulate. @param {Object} event DOM event data including the position touched.
[ "Listen", "for", "touch", "events", "and", "determine", "which", "key", "to", "simulate", "." ]
030db918dd8ce640afd57e172418472497e8f113
https://github.com/goldfire/howler.js/blob/030db918dd8ce640afd57e172418472497e8f113/examples/3d/js/controls.js#L55-L71
1,454
goldfire/howler.js
examples/3d/js/controls.js
function(event) { this.states.left = false; this.states.right = false; this.states.front = false; this.states.back = false; event.preventDefault(); event.stopPropagation(); }
javascript
function(event) { this.states.left = false; this.states.right = false; this.states.front = false; this.states.back = false; event.preventDefault(); event.stopPropagation(); }
[ "function", "(", "event", ")", "{", "this", ".", "states", ".", "left", "=", "false", ";", "this", ".", "states", ".", "right", "=", "false", ";", "this", ".", "states", ".", "front", "=", "false", ";", "this", ".", "states", ".", "back", "=", "false", ";", "event", ".", "preventDefault", "(", ")", ";", "event", ".", "stopPropagation", "(", ")", ";", "}" ]
Fired to reset all key statuses based on no fingers being on the screen. @param {Object} event DOM event data including the position touched.
[ "Fired", "to", "reset", "all", "key", "statuses", "based", "on", "no", "fingers", "being", "on", "the", "screen", "." ]
030db918dd8ce640afd57e172418472497e8f113
https://github.com/goldfire/howler.js/blob/030db918dd8ce640afd57e172418472497e8f113/examples/3d/js/controls.js#L77-L85
1,455
goldfire/howler.js
examples/3d/js/map.js
function() { // Loop through the tiles and setup the audio listeners. for (var i=0; i<this.grid.length; i++) { if (this.grid[i] === 2) { var y = Math.floor(i / this.size); var x = i % this.size; game.audio.speaker(x, y); } } }
javascript
function() { // Loop through the tiles and setup the audio listeners. for (var i=0; i<this.grid.length; i++) { if (this.grid[i] === 2) { var y = Math.floor(i / this.size); var x = i % this.size; game.audio.speaker(x, y); } } }
[ "function", "(", ")", "{", "// Loop through the tiles and setup the audio listeners.", "for", "(", "var", "i", "=", "0", ";", "i", "<", "this", ".", "grid", ".", "length", ";", "i", "++", ")", "{", "if", "(", "this", ".", "grid", "[", "i", "]", "===", "2", ")", "{", "var", "y", "=", "Math", ".", "floor", "(", "i", "/", "this", ".", "size", ")", ";", "var", "x", "=", "i", "%", "this", ".", "size", ";", "game", ".", "audio", ".", "speaker", "(", "x", ",", "y", ")", ";", "}", "}", "}" ]
Sets up the map including the speaker audio points.
[ "Sets", "up", "the", "map", "including", "the", "speaker", "audio", "points", "." ]
030db918dd8ce640afd57e172418472497e8f113
https://github.com/goldfire/howler.js/blob/030db918dd8ce640afd57e172418472497e8f113/examples/3d/js/map.js#L32-L41
1,456
goldfire/howler.js
examples/3d/js/map.js
function(x, y) { x = Math.floor(x); y = Math.floor(y); if (x < 0 || x > this.size - 1 || y < 0 || y > this.size - 1) { return -1; } return this.grid[y * this.size + x]; }
javascript
function(x, y) { x = Math.floor(x); y = Math.floor(y); if (x < 0 || x > this.size - 1 || y < 0 || y > this.size - 1) { return -1; } return this.grid[y * this.size + x]; }
[ "function", "(", "x", ",", "y", ")", "{", "x", "=", "Math", ".", "floor", "(", "x", ")", ";", "y", "=", "Math", ".", "floor", "(", "y", ")", ";", "if", "(", "x", "<", "0", "||", "x", ">", "this", ".", "size", "-", "1", "||", "y", "<", "0", "||", "y", ">", "this", ".", "size", "-", "1", ")", "{", "return", "-", "1", ";", "}", "return", "this", ".", "grid", "[", "y", "*", "this", ".", "size", "+", "x", "]", ";", "}" ]
Check if a gird location is out of bounds, a wall or empty. @param {Number} x x-coordinate @param {Number} y y-coordinate @return {Number} -1, 0, 1
[ "Check", "if", "a", "gird", "location", "is", "out", "of", "bounds", "a", "wall", "or", "empty", "." ]
030db918dd8ce640afd57e172418472497e8f113
https://github.com/goldfire/howler.js/blob/030db918dd8ce640afd57e172418472497e8f113/examples/3d/js/map.js#L49-L58
1,457
goldfire/howler.js
examples/3d/js/map.js
function(sin, cos, range, origin) { var stepX = this.step(sin, cos, origin.x, origin.y, false); var stepY = this.step(cos, sin, origin.y, origin.x, true); var inspectX = [sin, cos, stepX, 1, 0, origin.dist, stepX.y]; var inspectY = [sin, cos, stepY, 0, 1, origin.dist, stepY.x]; var next = this.inspect.apply(this, (stepX.len2 < stepY.len2) ? inspectX : inspectY); if (next.dist > range) { return [origin]; } return [origin].concat(this.ray(sin, cos, range, next)); }
javascript
function(sin, cos, range, origin) { var stepX = this.step(sin, cos, origin.x, origin.y, false); var stepY = this.step(cos, sin, origin.y, origin.x, true); var inspectX = [sin, cos, stepX, 1, 0, origin.dist, stepX.y]; var inspectY = [sin, cos, stepY, 0, 1, origin.dist, stepY.x]; var next = this.inspect.apply(this, (stepX.len2 < stepY.len2) ? inspectX : inspectY); if (next.dist > range) { return [origin]; } return [origin].concat(this.ray(sin, cos, range, next)); }
[ "function", "(", "sin", ",", "cos", ",", "range", ",", "origin", ")", "{", "var", "stepX", "=", "this", ".", "step", "(", "sin", ",", "cos", ",", "origin", ".", "x", ",", "origin", ".", "y", ",", "false", ")", ";", "var", "stepY", "=", "this", ".", "step", "(", "cos", ",", "sin", ",", "origin", ".", "y", ",", "origin", ".", "x", ",", "true", ")", ";", "var", "inspectX", "=", "[", "sin", ",", "cos", ",", "stepX", ",", "1", ",", "0", ",", "origin", ".", "dist", ",", "stepX", ".", "y", "]", ";", "var", "inspectY", "=", "[", "sin", ",", "cos", ",", "stepY", ",", "0", ",", "1", ",", "origin", ".", "dist", ",", "stepY", ".", "x", "]", ";", "var", "next", "=", "this", ".", "inspect", ".", "apply", "(", "this", ",", "(", "stepX", ".", "len2", "<", "stepY", ".", "len2", ")", "?", "inspectX", ":", "inspectY", ")", ";", "if", "(", "next", ".", "dist", ">", "range", ")", "{", "return", "[", "origin", "]", ";", "}", "return", "[", "origin", "]", ".", "concat", "(", "this", ".", "ray", "(", "sin", ",", "cos", ",", "range", ",", "next", ")", ")", ";", "}" ]
Emit a ray to beginb uilding the scene. @param {Number} sin Sine of the cast angle. @param {Number} cos Cosine of the cast angle. @param {Number} range Max length of the ray. @param {Object} origin x, y, height and sitance
[ "Emit", "a", "ray", "to", "beginb", "uilding", "the", "scene", "." ]
030db918dd8ce640afd57e172418472497e8f113
https://github.com/goldfire/howler.js/blob/030db918dd8ce640afd57e172418472497e8f113/examples/3d/js/map.js#L67-L80
1,458
goldfire/howler.js
examples/3d/js/map.js
function(rise, run, x, y, inverted) { if (run === 0) { return {len2: Infinity}; } var dx = run > 0 ? Math.floor(x + 1) - x : Math.ceil(x - 1) - x; var dy = dx * (rise / run); return { x: inverted ? y + dy : x + dx, y: inverted ? x + dx : y + dy, len2: dx * dx + dy * dy }; }
javascript
function(rise, run, x, y, inverted) { if (run === 0) { return {len2: Infinity}; } var dx = run > 0 ? Math.floor(x + 1) - x : Math.ceil(x - 1) - x; var dy = dx * (rise / run); return { x: inverted ? y + dy : x + dx, y: inverted ? x + dx : y + dy, len2: dx * dx + dy * dy }; }
[ "function", "(", "rise", ",", "run", ",", "x", ",", "y", ",", "inverted", ")", "{", "if", "(", "run", "===", "0", ")", "{", "return", "{", "len2", ":", "Infinity", "}", ";", "}", "var", "dx", "=", "run", ">", "0", "?", "Math", ".", "floor", "(", "x", "+", "1", ")", "-", "x", ":", "Math", ".", "ceil", "(", "x", "-", "1", ")", "-", "x", ";", "var", "dy", "=", "dx", "*", "(", "rise", "/", "run", ")", ";", "return", "{", "x", ":", "inverted", "?", "y", "+", "dy", ":", "x", "+", "dx", ",", "y", ":", "inverted", "?", "x", "+", "dx", ":", "y", "+", "dy", ",", "len2", ":", "dx", "*", "dx", "+", "dy", "*", "dy", "}", ";", "}" ]
Processes each step along the ray. @param {Number} rise Slope of line: sine of the cast angle. @param {Number} run Slope of line: cosine of the cast angle. @param {Number} x Origin x-position. @param {Number} y Origin y-position. @param {Boolean} inverted
[ "Processes", "each", "step", "along", "the", "ray", "." ]
030db918dd8ce640afd57e172418472497e8f113
https://github.com/goldfire/howler.js/blob/030db918dd8ce640afd57e172418472497e8f113/examples/3d/js/map.js#L90-L103
1,459
goldfire/howler.js
examples/3d/js/map.js
function(sin, cos, step, shiftX, shiftY, dist, offset) { var dx = (cos < 0) ? shiftX : 0; var dy = (sin < 0) ? shiftY : 0; step.type = this.check(step.x - dx, step.y - dy); step.height = (step.type) > 0 ? 1 : 0; step.dist = dist + Math.sqrt(step.len2); if (shiftX) { step.shading = (cos < 0) ? 2 : 0; } else { step.shading = (sin < 0) ? 2 : 1; } step.offset = offset - Math.floor(offset); return step; }
javascript
function(sin, cos, step, shiftX, shiftY, dist, offset) { var dx = (cos < 0) ? shiftX : 0; var dy = (sin < 0) ? shiftY : 0; step.type = this.check(step.x - dx, step.y - dy); step.height = (step.type) > 0 ? 1 : 0; step.dist = dist + Math.sqrt(step.len2); if (shiftX) { step.shading = (cos < 0) ? 2 : 0; } else { step.shading = (sin < 0) ? 2 : 1; } step.offset = offset - Math.floor(offset); return step; }
[ "function", "(", "sin", ",", "cos", ",", "step", ",", "shiftX", ",", "shiftY", ",", "dist", ",", "offset", ")", "{", "var", "dx", "=", "(", "cos", "<", "0", ")", "?", "shiftX", ":", "0", ";", "var", "dy", "=", "(", "sin", "<", "0", ")", "?", "shiftY", ":", "0", ";", "step", ".", "type", "=", "this", ".", "check", "(", "step", ".", "x", "-", "dx", ",", "step", ".", "y", "-", "dy", ")", ";", "step", ".", "height", "=", "(", "step", ".", "type", ")", ">", "0", "?", "1", ":", "0", ";", "step", ".", "dist", "=", "dist", "+", "Math", ".", "sqrt", "(", "step", ".", "len2", ")", ";", "if", "(", "shiftX", ")", "{", "step", ".", "shading", "=", "(", "cos", "<", "0", ")", "?", "2", ":", "0", ";", "}", "else", "{", "step", ".", "shading", "=", "(", "sin", "<", "0", ")", "?", "2", ":", "1", ";", "}", "step", ".", "offset", "=", "offset", "-", "Math", ".", "floor", "(", "offset", ")", ";", "return", "step", ";", "}" ]
Inspect the next position to determine distance, height, shading, etc. @param {Number} sin Sine of the cast angle. @param {Number} cos Cosine of the cast angle. @param {Object} step x, y and length of the step. @param {Number} shiftX X shifted by 1 or 0. @param {Number} shiftY Y shifted by 1 or 0. @param {Number} dist Distnace from origin. @param {Number} offset Step offset.
[ "Inspect", "the", "next", "position", "to", "determine", "distance", "height", "shading", "etc", "." ]
030db918dd8ce640afd57e172418472497e8f113
https://github.com/goldfire/howler.js/blob/030db918dd8ce640afd57e172418472497e8f113/examples/3d/js/map.js#L115-L132
1,460
goldfire/howler.js
examples/3d/js/map.js
function(point, angle, range) { var sin = Math.sin(angle); var cos = Math.cos(angle); return this.ray(sin, cos, range, { x: point.x, y: point.y, height: 0, dist: 0 }); }
javascript
function(point, angle, range) { var sin = Math.sin(angle); var cos = Math.cos(angle); return this.ray(sin, cos, range, { x: point.x, y: point.y, height: 0, dist: 0 }); }
[ "function", "(", "point", ",", "angle", ",", "range", ")", "{", "var", "sin", "=", "Math", ".", "sin", "(", "angle", ")", ";", "var", "cos", "=", "Math", ".", "cos", "(", "angle", ")", ";", "return", "this", ".", "ray", "(", "sin", ",", "cos", ",", "range", ",", "{", "x", ":", "point", ".", "x", ",", "y", ":", "point", ".", "y", ",", "height", ":", "0", ",", "dist", ":", "0", "}", ")", ";", "}" ]
Casts a ray from the camera and returns the results. @param {Object} point Player/camera's x/y position. @param {Number} angle Angle (in radians) of camera. @param {Number} range Max length of the ray.
[ "Casts", "a", "ray", "from", "the", "camera", "and", "returns", "the", "results", "." ]
030db918dd8ce640afd57e172418472497e8f113
https://github.com/goldfire/howler.js/blob/030db918dd8ce640afd57e172418472497e8f113/examples/3d/js/map.js#L140-L150
1,461
goldfire/howler.js
examples/3d/js/map.js
function(secs) { if (this.light > 0) { this.light = Math.max(this.light - 10 * secs, 0); } else if (Math.random() * 6 < secs) { this.light = 2; // Play the lightning sound. game.audio.lightning(); } }
javascript
function(secs) { if (this.light > 0) { this.light = Math.max(this.light - 10 * secs, 0); } else if (Math.random() * 6 < secs) { this.light = 2; // Play the lightning sound. game.audio.lightning(); } }
[ "function", "(", "secs", ")", "{", "if", "(", "this", ".", "light", ">", "0", ")", "{", "this", ".", "light", "=", "Math", ".", "max", "(", "this", ".", "light", "-", "10", "*", "secs", ",", "0", ")", ";", "}", "else", "if", "(", "Math", ".", "random", "(", ")", "*", "6", "<", "secs", ")", "{", "this", ".", "light", "=", "2", ";", "// Play the lightning sound.", "game", ".", "audio", ".", "lightning", "(", ")", ";", "}", "}" ]
Update loop on the map, in this case used to add in lightning by adjusting global lighting. @param {Number} secs Seconds since last tick.
[ "Update", "loop", "on", "the", "map", "in", "this", "case", "used", "to", "add", "in", "lightning", "by", "adjusting", "global", "lighting", "." ]
030db918dd8ce640afd57e172418472497e8f113
https://github.com/goldfire/howler.js/blob/030db918dd8ce640afd57e172418472497e8f113/examples/3d/js/map.js#L156-L165
1,462
goldfire/howler.js
dist/howler.js
function() { var self = this || Howler; // Create a global ID counter. self._counter = 1000; // Pool of unlocked HTML5 Audio objects. self._html5AudioPool = []; self.html5PoolSize = 10; // Internal properties. self._codecs = {}; self._howls = []; self._muted = false; self._volume = 1; self._canPlayEvent = 'canplaythrough'; self._navigator = (typeof window !== 'undefined' && window.navigator) ? window.navigator : null; // Public properties. self.masterGain = null; self.noAudio = false; self.usingWebAudio = true; self.autoSuspend = true; self.ctx = null; // Set to false to disable the auto audio unlocker. self.autoUnlock = true; // Setup the various state values for global tracking. self._setup(); return self; }
javascript
function() { var self = this || Howler; // Create a global ID counter. self._counter = 1000; // Pool of unlocked HTML5 Audio objects. self._html5AudioPool = []; self.html5PoolSize = 10; // Internal properties. self._codecs = {}; self._howls = []; self._muted = false; self._volume = 1; self._canPlayEvent = 'canplaythrough'; self._navigator = (typeof window !== 'undefined' && window.navigator) ? window.navigator : null; // Public properties. self.masterGain = null; self.noAudio = false; self.usingWebAudio = true; self.autoSuspend = true; self.ctx = null; // Set to false to disable the auto audio unlocker. self.autoUnlock = true; // Setup the various state values for global tracking. self._setup(); return self; }
[ "function", "(", ")", "{", "var", "self", "=", "this", "||", "Howler", ";", "// Create a global ID counter.", "self", ".", "_counter", "=", "1000", ";", "// Pool of unlocked HTML5 Audio objects.", "self", ".", "_html5AudioPool", "=", "[", "]", ";", "self", ".", "html5PoolSize", "=", "10", ";", "// Internal properties.", "self", ".", "_codecs", "=", "{", "}", ";", "self", ".", "_howls", "=", "[", "]", ";", "self", ".", "_muted", "=", "false", ";", "self", ".", "_volume", "=", "1", ";", "self", ".", "_canPlayEvent", "=", "'canplaythrough'", ";", "self", ".", "_navigator", "=", "(", "typeof", "window", "!==", "'undefined'", "&&", "window", ".", "navigator", ")", "?", "window", ".", "navigator", ":", "null", ";", "// Public properties.", "self", ".", "masterGain", "=", "null", ";", "self", ".", "noAudio", "=", "false", ";", "self", ".", "usingWebAudio", "=", "true", ";", "self", ".", "autoSuspend", "=", "true", ";", "self", ".", "ctx", "=", "null", ";", "// Set to false to disable the auto audio unlocker.", "self", ".", "autoUnlock", "=", "true", ";", "// Setup the various state values for global tracking.", "self", ".", "_setup", "(", ")", ";", "return", "self", ";", "}" ]
Initialize the global Howler object. @return {Howler}
[ "Initialize", "the", "global", "Howler", "object", "." ]
030db918dd8ce640afd57e172418472497e8f113
https://github.com/goldfire/howler.js/blob/030db918dd8ce640afd57e172418472497e8f113/dist/howler.js#L30-L62
1,463
goldfire/howler.js
dist/howler.js
function() { var self = this || Howler; for (var i=self._howls.length-1; i>=0; i--) { self._howls[i].unload(); } // Create a new AudioContext to make sure it is fully reset. if (self.usingWebAudio && self.ctx && typeof self.ctx.close !== 'undefined') { self.ctx.close(); self.ctx = null; setupAudioContext(); } return self; }
javascript
function() { var self = this || Howler; for (var i=self._howls.length-1; i>=0; i--) { self._howls[i].unload(); } // Create a new AudioContext to make sure it is fully reset. if (self.usingWebAudio && self.ctx && typeof self.ctx.close !== 'undefined') { self.ctx.close(); self.ctx = null; setupAudioContext(); } return self; }
[ "function", "(", ")", "{", "var", "self", "=", "this", "||", "Howler", ";", "for", "(", "var", "i", "=", "self", ".", "_howls", ".", "length", "-", "1", ";", "i", ">=", "0", ";", "i", "--", ")", "{", "self", ".", "_howls", "[", "i", "]", ".", "unload", "(", ")", ";", "}", "// Create a new AudioContext to make sure it is fully reset.", "if", "(", "self", ".", "usingWebAudio", "&&", "self", ".", "ctx", "&&", "typeof", "self", ".", "ctx", ".", "close", "!==", "'undefined'", ")", "{", "self", ".", "ctx", ".", "close", "(", ")", ";", "self", ".", "ctx", "=", "null", ";", "setupAudioContext", "(", ")", ";", "}", "return", "self", ";", "}" ]
Unload and destroy all currently loaded Howl objects. @return {Howler}
[ "Unload", "and", "destroy", "all", "currently", "loaded", "Howl", "objects", "." ]
030db918dd8ce640afd57e172418472497e8f113
https://github.com/goldfire/howler.js/blob/030db918dd8ce640afd57e172418472497e8f113/dist/howler.js#L157-L172
1,464
goldfire/howler.js
dist/howler.js
function() { var self = this || Howler; // Keeps track of the suspend/resume state of the AudioContext. self.state = self.ctx ? self.ctx.state || 'suspended' : 'suspended'; // Automatically begin the 30-second suspend process self._autoSuspend(); // Check if audio is available. if (!self.usingWebAudio) { // No audio is available on this system if noAudio is set to true. if (typeof Audio !== 'undefined') { try { var test = new Audio(); // Check if the canplaythrough event is available. if (typeof test.oncanplaythrough === 'undefined') { self._canPlayEvent = 'canplay'; } } catch(e) { self.noAudio = true; } } else { self.noAudio = true; } } // Test to make sure audio isn't disabled in Internet Explorer. try { var test = new Audio(); if (test.muted) { self.noAudio = true; } } catch (e) {} // Check for supported codecs. if (!self.noAudio) { self._setupCodecs(); } return self; }
javascript
function() { var self = this || Howler; // Keeps track of the suspend/resume state of the AudioContext. self.state = self.ctx ? self.ctx.state || 'suspended' : 'suspended'; // Automatically begin the 30-second suspend process self._autoSuspend(); // Check if audio is available. if (!self.usingWebAudio) { // No audio is available on this system if noAudio is set to true. if (typeof Audio !== 'undefined') { try { var test = new Audio(); // Check if the canplaythrough event is available. if (typeof test.oncanplaythrough === 'undefined') { self._canPlayEvent = 'canplay'; } } catch(e) { self.noAudio = true; } } else { self.noAudio = true; } } // Test to make sure audio isn't disabled in Internet Explorer. try { var test = new Audio(); if (test.muted) { self.noAudio = true; } } catch (e) {} // Check for supported codecs. if (!self.noAudio) { self._setupCodecs(); } return self; }
[ "function", "(", ")", "{", "var", "self", "=", "this", "||", "Howler", ";", "// Keeps track of the suspend/resume state of the AudioContext.", "self", ".", "state", "=", "self", ".", "ctx", "?", "self", ".", "ctx", ".", "state", "||", "'suspended'", ":", "'suspended'", ";", "// Automatically begin the 30-second suspend process", "self", ".", "_autoSuspend", "(", ")", ";", "// Check if audio is available.", "if", "(", "!", "self", ".", "usingWebAudio", ")", "{", "// No audio is available on this system if noAudio is set to true.", "if", "(", "typeof", "Audio", "!==", "'undefined'", ")", "{", "try", "{", "var", "test", "=", "new", "Audio", "(", ")", ";", "// Check if the canplaythrough event is available.", "if", "(", "typeof", "test", ".", "oncanplaythrough", "===", "'undefined'", ")", "{", "self", ".", "_canPlayEvent", "=", "'canplay'", ";", "}", "}", "catch", "(", "e", ")", "{", "self", ".", "noAudio", "=", "true", ";", "}", "}", "else", "{", "self", ".", "noAudio", "=", "true", ";", "}", "}", "// Test to make sure audio isn't disabled in Internet Explorer.", "try", "{", "var", "test", "=", "new", "Audio", "(", ")", ";", "if", "(", "test", ".", "muted", ")", "{", "self", ".", "noAudio", "=", "true", ";", "}", "}", "catch", "(", "e", ")", "{", "}", "// Check for supported codecs.", "if", "(", "!", "self", ".", "noAudio", ")", "{", "self", ".", "_setupCodecs", "(", ")", ";", "}", "return", "self", ";", "}" ]
Setup various state values for global tracking. @return {Howler}
[ "Setup", "various", "state", "values", "for", "global", "tracking", "." ]
030db918dd8ce640afd57e172418472497e8f113
https://github.com/goldfire/howler.js/blob/030db918dd8ce640afd57e172418472497e8f113/dist/howler.js#L187-L229
1,465
goldfire/howler.js
dist/howler.js
function() { var self = this || Howler; var audioTest = null; // Must wrap in a try/catch because IE11 in server mode throws an error. try { audioTest = (typeof Audio !== 'undefined') ? new Audio() : null; } catch (err) { return self; } if (!audioTest || typeof audioTest.canPlayType !== 'function') { return self; } var mpegTest = audioTest.canPlayType('audio/mpeg;').replace(/^no$/, ''); // Opera version <33 has mixed MP3 support, so we need to check for and block it. var checkOpera = self._navigator && self._navigator.userAgent.match(/OPR\/([0-6].)/g); var isOldOpera = (checkOpera && parseInt(checkOpera[0].split('/')[1], 10) < 33); self._codecs = { mp3: !!(!isOldOpera && (mpegTest || audioTest.canPlayType('audio/mp3;').replace(/^no$/, ''))), mpeg: !!mpegTest, opus: !!audioTest.canPlayType('audio/ogg; codecs="opus"').replace(/^no$/, ''), ogg: !!audioTest.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, ''), oga: !!audioTest.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, ''), wav: !!audioTest.canPlayType('audio/wav; codecs="1"').replace(/^no$/, ''), aac: !!audioTest.canPlayType('audio/aac;').replace(/^no$/, ''), caf: !!audioTest.canPlayType('audio/x-caf;').replace(/^no$/, ''), m4a: !!(audioTest.canPlayType('audio/x-m4a;') || audioTest.canPlayType('audio/m4a;') || audioTest.canPlayType('audio/aac;')).replace(/^no$/, ''), mp4: !!(audioTest.canPlayType('audio/x-mp4;') || audioTest.canPlayType('audio/mp4;') || audioTest.canPlayType('audio/aac;')).replace(/^no$/, ''), weba: !!audioTest.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/, ''), webm: !!audioTest.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/, ''), dolby: !!audioTest.canPlayType('audio/mp4; codecs="ec-3"').replace(/^no$/, ''), flac: !!(audioTest.canPlayType('audio/x-flac;') || audioTest.canPlayType('audio/flac;')).replace(/^no$/, '') }; return self; }
javascript
function() { var self = this || Howler; var audioTest = null; // Must wrap in a try/catch because IE11 in server mode throws an error. try { audioTest = (typeof Audio !== 'undefined') ? new Audio() : null; } catch (err) { return self; } if (!audioTest || typeof audioTest.canPlayType !== 'function') { return self; } var mpegTest = audioTest.canPlayType('audio/mpeg;').replace(/^no$/, ''); // Opera version <33 has mixed MP3 support, so we need to check for and block it. var checkOpera = self._navigator && self._navigator.userAgent.match(/OPR\/([0-6].)/g); var isOldOpera = (checkOpera && parseInt(checkOpera[0].split('/')[1], 10) < 33); self._codecs = { mp3: !!(!isOldOpera && (mpegTest || audioTest.canPlayType('audio/mp3;').replace(/^no$/, ''))), mpeg: !!mpegTest, opus: !!audioTest.canPlayType('audio/ogg; codecs="opus"').replace(/^no$/, ''), ogg: !!audioTest.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, ''), oga: !!audioTest.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, ''), wav: !!audioTest.canPlayType('audio/wav; codecs="1"').replace(/^no$/, ''), aac: !!audioTest.canPlayType('audio/aac;').replace(/^no$/, ''), caf: !!audioTest.canPlayType('audio/x-caf;').replace(/^no$/, ''), m4a: !!(audioTest.canPlayType('audio/x-m4a;') || audioTest.canPlayType('audio/m4a;') || audioTest.canPlayType('audio/aac;')).replace(/^no$/, ''), mp4: !!(audioTest.canPlayType('audio/x-mp4;') || audioTest.canPlayType('audio/mp4;') || audioTest.canPlayType('audio/aac;')).replace(/^no$/, ''), weba: !!audioTest.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/, ''), webm: !!audioTest.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/, ''), dolby: !!audioTest.canPlayType('audio/mp4; codecs="ec-3"').replace(/^no$/, ''), flac: !!(audioTest.canPlayType('audio/x-flac;') || audioTest.canPlayType('audio/flac;')).replace(/^no$/, '') }; return self; }
[ "function", "(", ")", "{", "var", "self", "=", "this", "||", "Howler", ";", "var", "audioTest", "=", "null", ";", "// Must wrap in a try/catch because IE11 in server mode throws an error.", "try", "{", "audioTest", "=", "(", "typeof", "Audio", "!==", "'undefined'", ")", "?", "new", "Audio", "(", ")", ":", "null", ";", "}", "catch", "(", "err", ")", "{", "return", "self", ";", "}", "if", "(", "!", "audioTest", "||", "typeof", "audioTest", ".", "canPlayType", "!==", "'function'", ")", "{", "return", "self", ";", "}", "var", "mpegTest", "=", "audioTest", ".", "canPlayType", "(", "'audio/mpeg;'", ")", ".", "replace", "(", "/", "^no$", "/", ",", "''", ")", ";", "// Opera version <33 has mixed MP3 support, so we need to check for and block it.", "var", "checkOpera", "=", "self", ".", "_navigator", "&&", "self", ".", "_navigator", ".", "userAgent", ".", "match", "(", "/", "OPR\\/([0-6].)", "/", "g", ")", ";", "var", "isOldOpera", "=", "(", "checkOpera", "&&", "parseInt", "(", "checkOpera", "[", "0", "]", ".", "split", "(", "'/'", ")", "[", "1", "]", ",", "10", ")", "<", "33", ")", ";", "self", ".", "_codecs", "=", "{", "mp3", ":", "!", "!", "(", "!", "isOldOpera", "&&", "(", "mpegTest", "||", "audioTest", ".", "canPlayType", "(", "'audio/mp3;'", ")", ".", "replace", "(", "/", "^no$", "/", ",", "''", ")", ")", ")", ",", "mpeg", ":", "!", "!", "mpegTest", ",", "opus", ":", "!", "!", "audioTest", ".", "canPlayType", "(", "'audio/ogg; codecs=\"opus\"'", ")", ".", "replace", "(", "/", "^no$", "/", ",", "''", ")", ",", "ogg", ":", "!", "!", "audioTest", ".", "canPlayType", "(", "'audio/ogg; codecs=\"vorbis\"'", ")", ".", "replace", "(", "/", "^no$", "/", ",", "''", ")", ",", "oga", ":", "!", "!", "audioTest", ".", "canPlayType", "(", "'audio/ogg; codecs=\"vorbis\"'", ")", ".", "replace", "(", "/", "^no$", "/", ",", "''", ")", ",", "wav", ":", "!", "!", "audioTest", ".", "canPlayType", "(", "'audio/wav; codecs=\"1\"'", ")", ".", "replace", "(", "/", "^no$", "/", ",", "''", ")", ",", "aac", ":", "!", "!", "audioTest", ".", "canPlayType", "(", "'audio/aac;'", ")", ".", "replace", "(", "/", "^no$", "/", ",", "''", ")", ",", "caf", ":", "!", "!", "audioTest", ".", "canPlayType", "(", "'audio/x-caf;'", ")", ".", "replace", "(", "/", "^no$", "/", ",", "''", ")", ",", "m4a", ":", "!", "!", "(", "audioTest", ".", "canPlayType", "(", "'audio/x-m4a;'", ")", "||", "audioTest", ".", "canPlayType", "(", "'audio/m4a;'", ")", "||", "audioTest", ".", "canPlayType", "(", "'audio/aac;'", ")", ")", ".", "replace", "(", "/", "^no$", "/", ",", "''", ")", ",", "mp4", ":", "!", "!", "(", "audioTest", ".", "canPlayType", "(", "'audio/x-mp4;'", ")", "||", "audioTest", ".", "canPlayType", "(", "'audio/mp4;'", ")", "||", "audioTest", ".", "canPlayType", "(", "'audio/aac;'", ")", ")", ".", "replace", "(", "/", "^no$", "/", ",", "''", ")", ",", "weba", ":", "!", "!", "audioTest", ".", "canPlayType", "(", "'audio/webm; codecs=\"vorbis\"'", ")", ".", "replace", "(", "/", "^no$", "/", ",", "''", ")", ",", "webm", ":", "!", "!", "audioTest", ".", "canPlayType", "(", "'audio/webm; codecs=\"vorbis\"'", ")", ".", "replace", "(", "/", "^no$", "/", ",", "''", ")", ",", "dolby", ":", "!", "!", "audioTest", ".", "canPlayType", "(", "'audio/mp4; codecs=\"ec-3\"'", ")", ".", "replace", "(", "/", "^no$", "/", ",", "''", ")", ",", "flac", ":", "!", "!", "(", "audioTest", ".", "canPlayType", "(", "'audio/x-flac;'", ")", "||", "audioTest", ".", "canPlayType", "(", "'audio/flac;'", ")", ")", ".", "replace", "(", "/", "^no$", "/", ",", "''", ")", "}", ";", "return", "self", ";", "}" ]
Check for browser support for various codecs and cache the results. @return {Howler}
[ "Check", "for", "browser", "support", "for", "various", "codecs", "and", "cache", "the", "results", "." ]
030db918dd8ce640afd57e172418472497e8f113
https://github.com/goldfire/howler.js/blob/030db918dd8ce640afd57e172418472497e8f113/dist/howler.js#L235-L274
1,466
goldfire/howler.js
dist/howler.js
function() { var self = this || Howler; // Return the next object from the pool if one exists. if (self._html5AudioPool.length) { return self._html5AudioPool.pop(); } //.Check if the audio is locked and throw a warning. var testPlay = new Audio().play(); if (testPlay && typeof Promise !== 'undefined' && (testPlay instanceof Promise || typeof testPlay.then === 'function')) { testPlay.catch(function() { console.warn('HTML5 Audio pool exhausted, returning potentially locked audio object.'); }); } return new Audio(); }
javascript
function() { var self = this || Howler; // Return the next object from the pool if one exists. if (self._html5AudioPool.length) { return self._html5AudioPool.pop(); } //.Check if the audio is locked and throw a warning. var testPlay = new Audio().play(); if (testPlay && typeof Promise !== 'undefined' && (testPlay instanceof Promise || typeof testPlay.then === 'function')) { testPlay.catch(function() { console.warn('HTML5 Audio pool exhausted, returning potentially locked audio object.'); }); } return new Audio(); }
[ "function", "(", ")", "{", "var", "self", "=", "this", "||", "Howler", ";", "// Return the next object from the pool if one exists.", "if", "(", "self", ".", "_html5AudioPool", ".", "length", ")", "{", "return", "self", ".", "_html5AudioPool", ".", "pop", "(", ")", ";", "}", "//.Check if the audio is locked and throw a warning.", "var", "testPlay", "=", "new", "Audio", "(", ")", ".", "play", "(", ")", ";", "if", "(", "testPlay", "&&", "typeof", "Promise", "!==", "'undefined'", "&&", "(", "testPlay", "instanceof", "Promise", "||", "typeof", "testPlay", ".", "then", "===", "'function'", ")", ")", "{", "testPlay", ".", "catch", "(", "function", "(", ")", "{", "console", ".", "warn", "(", "'HTML5 Audio pool exhausted, returning potentially locked audio object.'", ")", ";", "}", ")", ";", "}", "return", "new", "Audio", "(", ")", ";", "}" ]
Get an unlocked HTML5 Audio object from the pool. If none are left, return a new Audio object and throw a warning. @return {Audio} HTML5 Audio object.
[ "Get", "an", "unlocked", "HTML5", "Audio", "object", "from", "the", "pool", ".", "If", "none", "are", "left", "return", "a", "new", "Audio", "object", "and", "throw", "a", "warning", "." ]
030db918dd8ce640afd57e172418472497e8f113
https://github.com/goldfire/howler.js/blob/030db918dd8ce640afd57e172418472497e8f113/dist/howler.js#L400-L417
1,467
goldfire/howler.js
dist/howler.js
function(audio) { var self = this || Howler; // Don't add audio to the pool if we don't know if it has been unlocked. if (audio._unlocked) { self._html5AudioPool.push(audio); } return self; }
javascript
function(audio) { var self = this || Howler; // Don't add audio to the pool if we don't know if it has been unlocked. if (audio._unlocked) { self._html5AudioPool.push(audio); } return self; }
[ "function", "(", "audio", ")", "{", "var", "self", "=", "this", "||", "Howler", ";", "// Don't add audio to the pool if we don't know if it has been unlocked.", "if", "(", "audio", ".", "_unlocked", ")", "{", "self", ".", "_html5AudioPool", ".", "push", "(", "audio", ")", ";", "}", "return", "self", ";", "}" ]
Return an activated HTML5 Audio object to the pool. @return {Howler}
[ "Return", "an", "activated", "HTML5", "Audio", "object", "to", "the", "pool", "." ]
030db918dd8ce640afd57e172418472497e8f113
https://github.com/goldfire/howler.js/blob/030db918dd8ce640afd57e172418472497e8f113/dist/howler.js#L423-L432
1,468
goldfire/howler.js
dist/howler.js
function() { var self = this; if (!self.ctx || typeof self.ctx.resume === 'undefined' || !Howler.usingWebAudio) { return; } if (self.state === 'running' && self._suspendTimer) { clearTimeout(self._suspendTimer); self._suspendTimer = null; } else if (self.state === 'suspended') { self.ctx.resume().then(function() { self.state = 'running'; // Emit to all Howls that the audio has resumed. for (var i=0; i<self._howls.length; i++) { self._howls[i]._emit('resume'); } }); if (self._suspendTimer) { clearTimeout(self._suspendTimer); self._suspendTimer = null; } } else if (self.state === 'suspending') { self._resumeAfterSuspend = true; } return self; }
javascript
function() { var self = this; if (!self.ctx || typeof self.ctx.resume === 'undefined' || !Howler.usingWebAudio) { return; } if (self.state === 'running' && self._suspendTimer) { clearTimeout(self._suspendTimer); self._suspendTimer = null; } else if (self.state === 'suspended') { self.ctx.resume().then(function() { self.state = 'running'; // Emit to all Howls that the audio has resumed. for (var i=0; i<self._howls.length; i++) { self._howls[i]._emit('resume'); } }); if (self._suspendTimer) { clearTimeout(self._suspendTimer); self._suspendTimer = null; } } else if (self.state === 'suspending') { self._resumeAfterSuspend = true; } return self; }
[ "function", "(", ")", "{", "var", "self", "=", "this", ";", "if", "(", "!", "self", ".", "ctx", "||", "typeof", "self", ".", "ctx", ".", "resume", "===", "'undefined'", "||", "!", "Howler", ".", "usingWebAudio", ")", "{", "return", ";", "}", "if", "(", "self", ".", "state", "===", "'running'", "&&", "self", ".", "_suspendTimer", ")", "{", "clearTimeout", "(", "self", ".", "_suspendTimer", ")", ";", "self", ".", "_suspendTimer", "=", "null", ";", "}", "else", "if", "(", "self", ".", "state", "===", "'suspended'", ")", "{", "self", ".", "ctx", ".", "resume", "(", ")", ".", "then", "(", "function", "(", ")", "{", "self", ".", "state", "=", "'running'", ";", "// Emit to all Howls that the audio has resumed.", "for", "(", "var", "i", "=", "0", ";", "i", "<", "self", ".", "_howls", ".", "length", ";", "i", "++", ")", "{", "self", ".", "_howls", "[", "i", "]", ".", "_emit", "(", "'resume'", ")", ";", "}", "}", ")", ";", "if", "(", "self", ".", "_suspendTimer", ")", "{", "clearTimeout", "(", "self", ".", "_suspendTimer", ")", ";", "self", ".", "_suspendTimer", "=", "null", ";", "}", "}", "else", "if", "(", "self", ".", "state", "===", "'suspending'", ")", "{", "self", ".", "_resumeAfterSuspend", "=", "true", ";", "}", "return", "self", ";", "}" ]
Automatically resume the Web Audio AudioContext when a new sound is played. @return {Howler}
[ "Automatically", "resume", "the", "Web", "Audio", "AudioContext", "when", "a", "new", "sound", "is", "played", "." ]
030db918dd8ce640afd57e172418472497e8f113
https://github.com/goldfire/howler.js/blob/030db918dd8ce640afd57e172418472497e8f113/dist/howler.js#L486-L515
1,469
goldfire/howler.js
dist/howler.js
function() { var self = this; var url = null; // If no audio is available, quit immediately. if (Howler.noAudio) { self._emit('loaderror', null, 'No audio support.'); return; } // Make sure our source is in an array. if (typeof self._src === 'string') { self._src = [self._src]; } // Loop through the sources and pick the first one that is compatible. for (var i=0; i<self._src.length; i++) { var ext, str; if (self._format && self._format[i]) { // If an extension was specified, use that instead. ext = self._format[i]; } else { // Make sure the source is a string. str = self._src[i]; if (typeof str !== 'string') { self._emit('loaderror', null, 'Non-string found in selected audio sources - ignoring.'); continue; } // Extract the file extension from the URL or base64 data URI. ext = /^data:audio\/([^;,]+);/i.exec(str); if (!ext) { ext = /\.([^.]+)$/.exec(str.split('?', 1)[0]); } if (ext) { ext = ext[1].toLowerCase(); } } // Log a warning if no extension was found. if (!ext) { console.warn('No file extension was found. Consider using the "format" property or specify an extension.'); } // Check if this extension is available. if (ext && Howler.codecs(ext)) { url = self._src[i]; break; } } if (!url) { self._emit('loaderror', null, 'No codec support for selected audio sources.'); return; } self._src = url; self._state = 'loading'; // If the hosting page is HTTPS and the source isn't, // drop down to HTML5 Audio to avoid Mixed Content errors. if (window.location.protocol === 'https:' && url.slice(0, 5) === 'http:') { self._html5 = true; self._webAudio = false; } // Create a new sound object and add it to the pool. new Sound(self); // Load and decode the audio data for playback. if (self._webAudio) { loadBuffer(self); } return self; }
javascript
function() { var self = this; var url = null; // If no audio is available, quit immediately. if (Howler.noAudio) { self._emit('loaderror', null, 'No audio support.'); return; } // Make sure our source is in an array. if (typeof self._src === 'string') { self._src = [self._src]; } // Loop through the sources and pick the first one that is compatible. for (var i=0; i<self._src.length; i++) { var ext, str; if (self._format && self._format[i]) { // If an extension was specified, use that instead. ext = self._format[i]; } else { // Make sure the source is a string. str = self._src[i]; if (typeof str !== 'string') { self._emit('loaderror', null, 'Non-string found in selected audio sources - ignoring.'); continue; } // Extract the file extension from the URL or base64 data URI. ext = /^data:audio\/([^;,]+);/i.exec(str); if (!ext) { ext = /\.([^.]+)$/.exec(str.split('?', 1)[0]); } if (ext) { ext = ext[1].toLowerCase(); } } // Log a warning if no extension was found. if (!ext) { console.warn('No file extension was found. Consider using the "format" property or specify an extension.'); } // Check if this extension is available. if (ext && Howler.codecs(ext)) { url = self._src[i]; break; } } if (!url) { self._emit('loaderror', null, 'No codec support for selected audio sources.'); return; } self._src = url; self._state = 'loading'; // If the hosting page is HTTPS and the source isn't, // drop down to HTML5 Audio to avoid Mixed Content errors. if (window.location.protocol === 'https:' && url.slice(0, 5) === 'http:') { self._html5 = true; self._webAudio = false; } // Create a new sound object and add it to the pool. new Sound(self); // Load and decode the audio data for playback. if (self._webAudio) { loadBuffer(self); } return self; }
[ "function", "(", ")", "{", "var", "self", "=", "this", ";", "var", "url", "=", "null", ";", "// If no audio is available, quit immediately.", "if", "(", "Howler", ".", "noAudio", ")", "{", "self", ".", "_emit", "(", "'loaderror'", ",", "null", ",", "'No audio support.'", ")", ";", "return", ";", "}", "// Make sure our source is in an array.", "if", "(", "typeof", "self", ".", "_src", "===", "'string'", ")", "{", "self", ".", "_src", "=", "[", "self", ".", "_src", "]", ";", "}", "// Loop through the sources and pick the first one that is compatible.", "for", "(", "var", "i", "=", "0", ";", "i", "<", "self", ".", "_src", ".", "length", ";", "i", "++", ")", "{", "var", "ext", ",", "str", ";", "if", "(", "self", ".", "_format", "&&", "self", ".", "_format", "[", "i", "]", ")", "{", "// If an extension was specified, use that instead.", "ext", "=", "self", ".", "_format", "[", "i", "]", ";", "}", "else", "{", "// Make sure the source is a string.", "str", "=", "self", ".", "_src", "[", "i", "]", ";", "if", "(", "typeof", "str", "!==", "'string'", ")", "{", "self", ".", "_emit", "(", "'loaderror'", ",", "null", ",", "'Non-string found in selected audio sources - ignoring.'", ")", ";", "continue", ";", "}", "// Extract the file extension from the URL or base64 data URI.", "ext", "=", "/", "^data:audio\\/([^;,]+);", "/", "i", ".", "exec", "(", "str", ")", ";", "if", "(", "!", "ext", ")", "{", "ext", "=", "/", "\\.([^.]+)$", "/", ".", "exec", "(", "str", ".", "split", "(", "'?'", ",", "1", ")", "[", "0", "]", ")", ";", "}", "if", "(", "ext", ")", "{", "ext", "=", "ext", "[", "1", "]", ".", "toLowerCase", "(", ")", ";", "}", "}", "// Log a warning if no extension was found.", "if", "(", "!", "ext", ")", "{", "console", ".", "warn", "(", "'No file extension was found. Consider using the \"format\" property or specify an extension.'", ")", ";", "}", "// Check if this extension is available.", "if", "(", "ext", "&&", "Howler", ".", "codecs", "(", "ext", ")", ")", "{", "url", "=", "self", ".", "_src", "[", "i", "]", ";", "break", ";", "}", "}", "if", "(", "!", "url", ")", "{", "self", ".", "_emit", "(", "'loaderror'", ",", "null", ",", "'No codec support for selected audio sources.'", ")", ";", "return", ";", "}", "self", ".", "_src", "=", "url", ";", "self", ".", "_state", "=", "'loading'", ";", "// If the hosting page is HTTPS and the source isn't,", "// drop down to HTML5 Audio to avoid Mixed Content errors.", "if", "(", "window", ".", "location", ".", "protocol", "===", "'https:'", "&&", "url", ".", "slice", "(", "0", ",", "5", ")", "===", "'http:'", ")", "{", "self", ".", "_html5", "=", "true", ";", "self", ".", "_webAudio", "=", "false", ";", "}", "// Create a new sound object and add it to the pool.", "new", "Sound", "(", "self", ")", ";", "// Load and decode the audio data for playback.", "if", "(", "self", ".", "_webAudio", ")", "{", "loadBuffer", "(", "self", ")", ";", "}", "return", "self", ";", "}" ]
Load the audio file. @return {Howler}
[ "Load", "the", "audio", "file", "." ]
030db918dd8ce640afd57e172418472497e8f113
https://github.com/goldfire/howler.js/blob/030db918dd8ce640afd57e172418472497e8f113/dist/howler.js#L624-L701
1,470
goldfire/howler.js
dist/howler.js
function() { sound._paused = false; sound._seek = seek; sound._start = start; sound._stop = stop; sound._loop = loop; }
javascript
function() { sound._paused = false; sound._seek = seek; sound._start = start; sound._stop = stop; sound._loop = loop; }
[ "function", "(", ")", "{", "sound", ".", "_paused", "=", "false", ";", "sound", ".", "_seek", "=", "seek", ";", "sound", ".", "_start", "=", "start", ";", "sound", ".", "_stop", "=", "stop", ";", "sound", ".", "_loop", "=", "loop", ";", "}" ]
Update the parameters of the sound.
[ "Update", "the", "parameters", "of", "the", "sound", "." ]
030db918dd8ce640afd57e172418472497e8f113
https://github.com/goldfire/howler.js/blob/030db918dd8ce640afd57e172418472497e8f113/dist/howler.js#L807-L813
1,471
goldfire/howler.js
dist/howler.js
function() { self._playLock = false; setParams(); self._refreshBuffer(sound); // Setup the playback params. var vol = (sound._muted || self._muted) ? 0 : sound._volume; node.gain.setValueAtTime(vol, Howler.ctx.currentTime); sound._playStart = Howler.ctx.currentTime; // Play the sound using the supported method. if (typeof node.bufferSource.start === 'undefined') { sound._loop ? node.bufferSource.noteGrainOn(0, seek, 86400) : node.bufferSource.noteGrainOn(0, seek, duration); } else { sound._loop ? node.bufferSource.start(0, seek, 86400) : node.bufferSource.start(0, seek, duration); } // Start a new timer if none is present. if (timeout !== Infinity) { self._endTimers[sound._id] = setTimeout(self._ended.bind(self, sound), timeout); } if (!internal) { setTimeout(function() { self._emit('play', sound._id); self._loadQueue(); }, 0); } }
javascript
function() { self._playLock = false; setParams(); self._refreshBuffer(sound); // Setup the playback params. var vol = (sound._muted || self._muted) ? 0 : sound._volume; node.gain.setValueAtTime(vol, Howler.ctx.currentTime); sound._playStart = Howler.ctx.currentTime; // Play the sound using the supported method. if (typeof node.bufferSource.start === 'undefined') { sound._loop ? node.bufferSource.noteGrainOn(0, seek, 86400) : node.bufferSource.noteGrainOn(0, seek, duration); } else { sound._loop ? node.bufferSource.start(0, seek, 86400) : node.bufferSource.start(0, seek, duration); } // Start a new timer if none is present. if (timeout !== Infinity) { self._endTimers[sound._id] = setTimeout(self._ended.bind(self, sound), timeout); } if (!internal) { setTimeout(function() { self._emit('play', sound._id); self._loadQueue(); }, 0); } }
[ "function", "(", ")", "{", "self", ".", "_playLock", "=", "false", ";", "setParams", "(", ")", ";", "self", ".", "_refreshBuffer", "(", "sound", ")", ";", "// Setup the playback params.", "var", "vol", "=", "(", "sound", ".", "_muted", "||", "self", ".", "_muted", ")", "?", "0", ":", "sound", ".", "_volume", ";", "node", ".", "gain", ".", "setValueAtTime", "(", "vol", ",", "Howler", ".", "ctx", ".", "currentTime", ")", ";", "sound", ".", "_playStart", "=", "Howler", ".", "ctx", ".", "currentTime", ";", "// Play the sound using the supported method.", "if", "(", "typeof", "node", ".", "bufferSource", ".", "start", "===", "'undefined'", ")", "{", "sound", ".", "_loop", "?", "node", ".", "bufferSource", ".", "noteGrainOn", "(", "0", ",", "seek", ",", "86400", ")", ":", "node", ".", "bufferSource", ".", "noteGrainOn", "(", "0", ",", "seek", ",", "duration", ")", ";", "}", "else", "{", "sound", ".", "_loop", "?", "node", ".", "bufferSource", ".", "start", "(", "0", ",", "seek", ",", "86400", ")", ":", "node", ".", "bufferSource", ".", "start", "(", "0", ",", "seek", ",", "duration", ")", ";", "}", "// Start a new timer if none is present.", "if", "(", "timeout", "!==", "Infinity", ")", "{", "self", ".", "_endTimers", "[", "sound", ".", "_id", "]", "=", "setTimeout", "(", "self", ".", "_ended", ".", "bind", "(", "self", ",", "sound", ")", ",", "timeout", ")", ";", "}", "if", "(", "!", "internal", ")", "{", "setTimeout", "(", "function", "(", ")", "{", "self", ".", "_emit", "(", "'play'", ",", "sound", ".", "_id", ")", ";", "self", ".", "_loadQueue", "(", ")", ";", "}", ",", "0", ")", ";", "}", "}" ]
Fire this when the sound is ready to play to begin Web Audio playback.
[ "Fire", "this", "when", "the", "sound", "is", "ready", "to", "play", "to", "begin", "Web", "Audio", "playback", "." ]
030db918dd8ce640afd57e172418472497e8f113
https://github.com/goldfire/howler.js/blob/030db918dd8ce640afd57e172418472497e8f113/dist/howler.js#L825-L853
1,472
goldfire/howler.js
dist/howler.js
function() { node.currentTime = seek; node.muted = sound._muted || self._muted || Howler._muted || node.muted; node.volume = sound._volume * Howler.volume(); node.playbackRate = sound._rate; // Some browsers will throw an error if this is called without user interaction. try { var play = node.play(); // Support older browsers that don't support promises, and thus don't have this issue. if (play && typeof Promise !== 'undefined' && (play instanceof Promise || typeof play.then === 'function')) { // Implements a lock to prevent DOMException: The play() request was interrupted by a call to pause(). self._playLock = true; // Set param values immediately. setParams(); // Releases the lock and executes queued actions. play .then(function() { self._playLock = false; node._unlocked = true; if (!internal) { self._emit('play', sound._id); self._loadQueue(); } }) .catch(function() { self._playLock = false; self._emit('playerror', sound._id, 'Playback was unable to start. This is most commonly an issue ' + 'on mobile devices and Chrome where playback was not within a user interaction.'); // Reset the ended and paused values. sound._ended = true; sound._paused = true; }); } else if (!internal) { self._playLock = false; setParams(); self._emit('play', sound._id); self._loadQueue(); } // Setting rate before playing won't work in IE, so we set it again here. node.playbackRate = sound._rate; // If the node is still paused, then we can assume there was a playback issue. if (node.paused) { self._emit('playerror', sound._id, 'Playback was unable to start. This is most commonly an issue ' + 'on mobile devices and Chrome where playback was not within a user interaction.'); return; } // Setup the end timer on sprites or listen for the ended event. if (sprite !== '__default' || sound._loop) { self._endTimers[sound._id] = setTimeout(self._ended.bind(self, sound), timeout); } else { self._endTimers[sound._id] = function() { // Fire ended on this audio node. self._ended(sound); // Clear this listener. node.removeEventListener('ended', self._endTimers[sound._id], false); }; node.addEventListener('ended', self._endTimers[sound._id], false); } } catch (err) { self._emit('playerror', sound._id, err); } }
javascript
function() { node.currentTime = seek; node.muted = sound._muted || self._muted || Howler._muted || node.muted; node.volume = sound._volume * Howler.volume(); node.playbackRate = sound._rate; // Some browsers will throw an error if this is called without user interaction. try { var play = node.play(); // Support older browsers that don't support promises, and thus don't have this issue. if (play && typeof Promise !== 'undefined' && (play instanceof Promise || typeof play.then === 'function')) { // Implements a lock to prevent DOMException: The play() request was interrupted by a call to pause(). self._playLock = true; // Set param values immediately. setParams(); // Releases the lock and executes queued actions. play .then(function() { self._playLock = false; node._unlocked = true; if (!internal) { self._emit('play', sound._id); self._loadQueue(); } }) .catch(function() { self._playLock = false; self._emit('playerror', sound._id, 'Playback was unable to start. This is most commonly an issue ' + 'on mobile devices and Chrome where playback was not within a user interaction.'); // Reset the ended and paused values. sound._ended = true; sound._paused = true; }); } else if (!internal) { self._playLock = false; setParams(); self._emit('play', sound._id); self._loadQueue(); } // Setting rate before playing won't work in IE, so we set it again here. node.playbackRate = sound._rate; // If the node is still paused, then we can assume there was a playback issue. if (node.paused) { self._emit('playerror', sound._id, 'Playback was unable to start. This is most commonly an issue ' + 'on mobile devices and Chrome where playback was not within a user interaction.'); return; } // Setup the end timer on sprites or listen for the ended event. if (sprite !== '__default' || sound._loop) { self._endTimers[sound._id] = setTimeout(self._ended.bind(self, sound), timeout); } else { self._endTimers[sound._id] = function() { // Fire ended on this audio node. self._ended(sound); // Clear this listener. node.removeEventListener('ended', self._endTimers[sound._id], false); }; node.addEventListener('ended', self._endTimers[sound._id], false); } } catch (err) { self._emit('playerror', sound._id, err); } }
[ "function", "(", ")", "{", "node", ".", "currentTime", "=", "seek", ";", "node", ".", "muted", "=", "sound", ".", "_muted", "||", "self", ".", "_muted", "||", "Howler", ".", "_muted", "||", "node", ".", "muted", ";", "node", ".", "volume", "=", "sound", ".", "_volume", "*", "Howler", ".", "volume", "(", ")", ";", "node", ".", "playbackRate", "=", "sound", ".", "_rate", ";", "// Some browsers will throw an error if this is called without user interaction.", "try", "{", "var", "play", "=", "node", ".", "play", "(", ")", ";", "// Support older browsers that don't support promises, and thus don't have this issue.", "if", "(", "play", "&&", "typeof", "Promise", "!==", "'undefined'", "&&", "(", "play", "instanceof", "Promise", "||", "typeof", "play", ".", "then", "===", "'function'", ")", ")", "{", "// Implements a lock to prevent DOMException: The play() request was interrupted by a call to pause().", "self", ".", "_playLock", "=", "true", ";", "// Set param values immediately.", "setParams", "(", ")", ";", "// Releases the lock and executes queued actions.", "play", ".", "then", "(", "function", "(", ")", "{", "self", ".", "_playLock", "=", "false", ";", "node", ".", "_unlocked", "=", "true", ";", "if", "(", "!", "internal", ")", "{", "self", ".", "_emit", "(", "'play'", ",", "sound", ".", "_id", ")", ";", "self", ".", "_loadQueue", "(", ")", ";", "}", "}", ")", ".", "catch", "(", "function", "(", ")", "{", "self", ".", "_playLock", "=", "false", ";", "self", ".", "_emit", "(", "'playerror'", ",", "sound", ".", "_id", ",", "'Playback was unable to start. This is most commonly an issue '", "+", "'on mobile devices and Chrome where playback was not within a user interaction.'", ")", ";", "// Reset the ended and paused values.", "sound", ".", "_ended", "=", "true", ";", "sound", ".", "_paused", "=", "true", ";", "}", ")", ";", "}", "else", "if", "(", "!", "internal", ")", "{", "self", ".", "_playLock", "=", "false", ";", "setParams", "(", ")", ";", "self", ".", "_emit", "(", "'play'", ",", "sound", ".", "_id", ")", ";", "self", ".", "_loadQueue", "(", ")", ";", "}", "// Setting rate before playing won't work in IE, so we set it again here.", "node", ".", "playbackRate", "=", "sound", ".", "_rate", ";", "// If the node is still paused, then we can assume there was a playback issue.", "if", "(", "node", ".", "paused", ")", "{", "self", ".", "_emit", "(", "'playerror'", ",", "sound", ".", "_id", ",", "'Playback was unable to start. This is most commonly an issue '", "+", "'on mobile devices and Chrome where playback was not within a user interaction.'", ")", ";", "return", ";", "}", "// Setup the end timer on sprites or listen for the ended event.", "if", "(", "sprite", "!==", "'__default'", "||", "sound", ".", "_loop", ")", "{", "self", ".", "_endTimers", "[", "sound", ".", "_id", "]", "=", "setTimeout", "(", "self", ".", "_ended", ".", "bind", "(", "self", ",", "sound", ")", ",", "timeout", ")", ";", "}", "else", "{", "self", ".", "_endTimers", "[", "sound", ".", "_id", "]", "=", "function", "(", ")", "{", "// Fire ended on this audio node.", "self", ".", "_ended", "(", "sound", ")", ";", "// Clear this listener.", "node", ".", "removeEventListener", "(", "'ended'", ",", "self", ".", "_endTimers", "[", "sound", ".", "_id", "]", ",", "false", ")", ";", "}", ";", "node", ".", "addEventListener", "(", "'ended'", ",", "self", ".", "_endTimers", "[", "sound", ".", "_id", "]", ",", "false", ")", ";", "}", "}", "catch", "(", "err", ")", "{", "self", ".", "_emit", "(", "'playerror'", ",", "sound", ".", "_id", ",", "err", ")", ";", "}", "}" ]
Fire this when the sound is ready to play to begin HTML5 Audio playback.
[ "Fire", "this", "when", "the", "sound", "is", "ready", "to", "play", "to", "begin", "HTML5", "Audio", "playback", "." ]
030db918dd8ce640afd57e172418472497e8f113
https://github.com/goldfire/howler.js/blob/030db918dd8ce640afd57e172418472497e8f113/dist/howler.js#L868-L938
1,473
goldfire/howler.js
dist/howler.js
function(sound, from, to, len, id, isGroup) { var self = this; var vol = from; var diff = to - from; var steps = Math.abs(diff / 0.01); var stepLen = Math.max(4, (steps > 0) ? len / steps : len); var lastTick = Date.now(); // Store the value being faded to. sound._fadeTo = to; // Update the volume value on each interval tick. sound._interval = setInterval(function() { // Update the volume based on the time since the last tick. var tick = (Date.now() - lastTick) / len; lastTick = Date.now(); vol += diff * tick; // Make sure the volume is in the right bounds. vol = Math.max(0, vol); vol = Math.min(1, vol); // Round to within 2 decimal points. vol = Math.round(vol * 100) / 100; // Change the volume. if (self._webAudio) { sound._volume = vol; } else { self.volume(vol, sound._id, true); } // Set the group's volume. if (isGroup) { self._volume = vol; } // When the fade is complete, stop it and fire event. if ((to < from && vol <= to) || (to > from && vol >= to)) { clearInterval(sound._interval); sound._interval = null; sound._fadeTo = null; self.volume(to, sound._id); self._emit('fade', sound._id); } }, stepLen); }
javascript
function(sound, from, to, len, id, isGroup) { var self = this; var vol = from; var diff = to - from; var steps = Math.abs(diff / 0.01); var stepLen = Math.max(4, (steps > 0) ? len / steps : len); var lastTick = Date.now(); // Store the value being faded to. sound._fadeTo = to; // Update the volume value on each interval tick. sound._interval = setInterval(function() { // Update the volume based on the time since the last tick. var tick = (Date.now() - lastTick) / len; lastTick = Date.now(); vol += diff * tick; // Make sure the volume is in the right bounds. vol = Math.max(0, vol); vol = Math.min(1, vol); // Round to within 2 decimal points. vol = Math.round(vol * 100) / 100; // Change the volume. if (self._webAudio) { sound._volume = vol; } else { self.volume(vol, sound._id, true); } // Set the group's volume. if (isGroup) { self._volume = vol; } // When the fade is complete, stop it and fire event. if ((to < from && vol <= to) || (to > from && vol >= to)) { clearInterval(sound._interval); sound._interval = null; sound._fadeTo = null; self.volume(to, sound._id); self._emit('fade', sound._id); } }, stepLen); }
[ "function", "(", "sound", ",", "from", ",", "to", ",", "len", ",", "id", ",", "isGroup", ")", "{", "var", "self", "=", "this", ";", "var", "vol", "=", "from", ";", "var", "diff", "=", "to", "-", "from", ";", "var", "steps", "=", "Math", ".", "abs", "(", "diff", "/", "0.01", ")", ";", "var", "stepLen", "=", "Math", ".", "max", "(", "4", ",", "(", "steps", ">", "0", ")", "?", "len", "/", "steps", ":", "len", ")", ";", "var", "lastTick", "=", "Date", ".", "now", "(", ")", ";", "// Store the value being faded to.", "sound", ".", "_fadeTo", "=", "to", ";", "// Update the volume value on each interval tick.", "sound", ".", "_interval", "=", "setInterval", "(", "function", "(", ")", "{", "// Update the volume based on the time since the last tick.", "var", "tick", "=", "(", "Date", ".", "now", "(", ")", "-", "lastTick", ")", "/", "len", ";", "lastTick", "=", "Date", ".", "now", "(", ")", ";", "vol", "+=", "diff", "*", "tick", ";", "// Make sure the volume is in the right bounds.", "vol", "=", "Math", ".", "max", "(", "0", ",", "vol", ")", ";", "vol", "=", "Math", ".", "min", "(", "1", ",", "vol", ")", ";", "// Round to within 2 decimal points.", "vol", "=", "Math", ".", "round", "(", "vol", "*", "100", ")", "/", "100", ";", "// Change the volume.", "if", "(", "self", ".", "_webAudio", ")", "{", "sound", ".", "_volume", "=", "vol", ";", "}", "else", "{", "self", ".", "volume", "(", "vol", ",", "sound", ".", "_id", ",", "true", ")", ";", "}", "// Set the group's volume.", "if", "(", "isGroup", ")", "{", "self", ".", "_volume", "=", "vol", ";", "}", "// When the fade is complete, stop it and fire event.", "if", "(", "(", "to", "<", "from", "&&", "vol", "<=", "to", ")", "||", "(", "to", ">", "from", "&&", "vol", ">=", "to", ")", ")", "{", "clearInterval", "(", "sound", ".", "_interval", ")", ";", "sound", ".", "_interval", "=", "null", ";", "sound", ".", "_fadeTo", "=", "null", ";", "self", ".", "volume", "(", "to", ",", "sound", ".", "_id", ")", ";", "self", ".", "_emit", "(", "'fade'", ",", "sound", ".", "_id", ")", ";", "}", "}", ",", "stepLen", ")", ";", "}" ]
Starts the internal interval to fade a sound. @param {Object} sound Reference to sound to fade. @param {Number} from The value to fade from (0.0 to 1.0). @param {Number} to The volume to fade to (0.0 to 1.0). @param {Number} len Time in milliseconds to fade. @param {Number} id The sound id to fade. @param {Boolean} isGroup If true, set the volume on the group.
[ "Starts", "the", "internal", "interval", "to", "fade", "a", "sound", "." ]
030db918dd8ce640afd57e172418472497e8f113
https://github.com/goldfire/howler.js/blob/030db918dd8ce640afd57e172418472497e8f113/dist/howler.js#L1322-L1368
1,474
goldfire/howler.js
dist/howler.js
function(id) { var self = this; var sound = self._soundById(id); if (sound && sound._interval) { if (self._webAudio) { sound._node.gain.cancelScheduledValues(Howler.ctx.currentTime); } clearInterval(sound._interval); sound._interval = null; self.volume(sound._fadeTo, id); sound._fadeTo = null; self._emit('fade', id); } return self; }
javascript
function(id) { var self = this; var sound = self._soundById(id); if (sound && sound._interval) { if (self._webAudio) { sound._node.gain.cancelScheduledValues(Howler.ctx.currentTime); } clearInterval(sound._interval); sound._interval = null; self.volume(sound._fadeTo, id); sound._fadeTo = null; self._emit('fade', id); } return self; }
[ "function", "(", "id", ")", "{", "var", "self", "=", "this", ";", "var", "sound", "=", "self", ".", "_soundById", "(", "id", ")", ";", "if", "(", "sound", "&&", "sound", ".", "_interval", ")", "{", "if", "(", "self", ".", "_webAudio", ")", "{", "sound", ".", "_node", ".", "gain", ".", "cancelScheduledValues", "(", "Howler", ".", "ctx", ".", "currentTime", ")", ";", "}", "clearInterval", "(", "sound", ".", "_interval", ")", ";", "sound", ".", "_interval", "=", "null", ";", "self", ".", "volume", "(", "sound", ".", "_fadeTo", ",", "id", ")", ";", "sound", ".", "_fadeTo", "=", "null", ";", "self", ".", "_emit", "(", "'fade'", ",", "id", ")", ";", "}", "return", "self", ";", "}" ]
Internal method that stops the currently playing fade when a new fade starts, volume is changed or the sound is stopped. @param {Number} id The sound id. @return {Howl}
[ "Internal", "method", "that", "stops", "the", "currently", "playing", "fade", "when", "a", "new", "fade", "starts", "volume", "is", "changed", "or", "the", "sound", "is", "stopped", "." ]
030db918dd8ce640afd57e172418472497e8f113
https://github.com/goldfire/howler.js/blob/030db918dd8ce640afd57e172418472497e8f113/dist/howler.js#L1376-L1393
1,475
goldfire/howler.js
dist/howler.js
function(id) { var self = this; var duration = self._duration; // If we pass an ID, get the sound and return the sprite length. var sound = self._soundById(id); if (sound) { duration = self._sprite[sound._sprite][1] / 1000; } return duration; }
javascript
function(id) { var self = this; var duration = self._duration; // If we pass an ID, get the sound and return the sprite length. var sound = self._soundById(id); if (sound) { duration = self._sprite[sound._sprite][1] / 1000; } return duration; }
[ "function", "(", "id", ")", "{", "var", "self", "=", "this", ";", "var", "duration", "=", "self", ".", "_duration", ";", "// If we pass an ID, get the sound and return the sprite length.", "var", "sound", "=", "self", ".", "_soundById", "(", "id", ")", ";", "if", "(", "sound", ")", "{", "duration", "=", "self", ".", "_sprite", "[", "sound", ".", "_sprite", "]", "[", "1", "]", "/", "1000", ";", "}", "return", "duration", ";", "}" ]
Get the duration of this sound. Passing a sound id will return the sprite duration. @param {Number} id The sound id to check. If none is passed, return full source duration. @return {Number} Audio duration in seconds.
[ "Get", "the", "duration", "of", "this", "sound", ".", "Passing", "a", "sound", "id", "will", "return", "the", "sprite", "duration", "." ]
030db918dd8ce640afd57e172418472497e8f113
https://github.com/goldfire/howler.js/blob/030db918dd8ce640afd57e172418472497e8f113/dist/howler.js#L1677-L1688
1,476
goldfire/howler.js
dist/howler.js
function(event, fn, id, once) { var self = this; var events = self['_on' + event]; if (typeof fn === 'function') { events.push(once ? {id: id, fn: fn, once: once} : {id: id, fn: fn}); } return self; }
javascript
function(event, fn, id, once) { var self = this; var events = self['_on' + event]; if (typeof fn === 'function') { events.push(once ? {id: id, fn: fn, once: once} : {id: id, fn: fn}); } return self; }
[ "function", "(", "event", ",", "fn", ",", "id", ",", "once", ")", "{", "var", "self", "=", "this", ";", "var", "events", "=", "self", "[", "'_on'", "+", "event", "]", ";", "if", "(", "typeof", "fn", "===", "'function'", ")", "{", "events", ".", "push", "(", "once", "?", "{", "id", ":", "id", ",", "fn", ":", "fn", ",", "once", ":", "once", "}", ":", "{", "id", ":", "id", ",", "fn", ":", "fn", "}", ")", ";", "}", "return", "self", ";", "}" ]
Listen to a custom event. @param {String} event Event name. @param {Function} fn Listener to call. @param {Number} id (optional) Only listen to events for this sound. @param {Number} once (INTERNAL) Marks event to fire only once. @return {Howl}
[ "Listen", "to", "a", "custom", "event", "." ]
030db918dd8ce640afd57e172418472497e8f113
https://github.com/goldfire/howler.js/blob/030db918dd8ce640afd57e172418472497e8f113/dist/howler.js#L1771-L1780
1,477
goldfire/howler.js
dist/howler.js
function(event, fn, id) { var self = this; var events = self['_on' + event]; var i = 0; // Allow passing just an event and ID. if (typeof fn === 'number') { id = fn; fn = null; } if (fn || id) { // Loop through event store and remove the passed function. for (i=0; i<events.length; i++) { var isId = (id === events[i].id); if (fn === events[i].fn && isId || !fn && isId) { events.splice(i, 1); break; } } } else if (event) { // Clear out all events of this type. self['_on' + event] = []; } else { // Clear out all events of every type. var keys = Object.keys(self); for (i=0; i<keys.length; i++) { if ((keys[i].indexOf('_on') === 0) && Array.isArray(self[keys[i]])) { self[keys[i]] = []; } } } return self; }
javascript
function(event, fn, id) { var self = this; var events = self['_on' + event]; var i = 0; // Allow passing just an event and ID. if (typeof fn === 'number') { id = fn; fn = null; } if (fn || id) { // Loop through event store and remove the passed function. for (i=0; i<events.length; i++) { var isId = (id === events[i].id); if (fn === events[i].fn && isId || !fn && isId) { events.splice(i, 1); break; } } } else if (event) { // Clear out all events of this type. self['_on' + event] = []; } else { // Clear out all events of every type. var keys = Object.keys(self); for (i=0; i<keys.length; i++) { if ((keys[i].indexOf('_on') === 0) && Array.isArray(self[keys[i]])) { self[keys[i]] = []; } } } return self; }
[ "function", "(", "event", ",", "fn", ",", "id", ")", "{", "var", "self", "=", "this", ";", "var", "events", "=", "self", "[", "'_on'", "+", "event", "]", ";", "var", "i", "=", "0", ";", "// Allow passing just an event and ID.", "if", "(", "typeof", "fn", "===", "'number'", ")", "{", "id", "=", "fn", ";", "fn", "=", "null", ";", "}", "if", "(", "fn", "||", "id", ")", "{", "// Loop through event store and remove the passed function.", "for", "(", "i", "=", "0", ";", "i", "<", "events", ".", "length", ";", "i", "++", ")", "{", "var", "isId", "=", "(", "id", "===", "events", "[", "i", "]", ".", "id", ")", ";", "if", "(", "fn", "===", "events", "[", "i", "]", ".", "fn", "&&", "isId", "||", "!", "fn", "&&", "isId", ")", "{", "events", ".", "splice", "(", "i", ",", "1", ")", ";", "break", ";", "}", "}", "}", "else", "if", "(", "event", ")", "{", "// Clear out all events of this type.", "self", "[", "'_on'", "+", "event", "]", "=", "[", "]", ";", "}", "else", "{", "// Clear out all events of every type.", "var", "keys", "=", "Object", ".", "keys", "(", "self", ")", ";", "for", "(", "i", "=", "0", ";", "i", "<", "keys", ".", "length", ";", "i", "++", ")", "{", "if", "(", "(", "keys", "[", "i", "]", ".", "indexOf", "(", "'_on'", ")", "===", "0", ")", "&&", "Array", ".", "isArray", "(", "self", "[", "keys", "[", "i", "]", "]", ")", ")", "{", "self", "[", "keys", "[", "i", "]", "]", "=", "[", "]", ";", "}", "}", "}", "return", "self", ";", "}" ]
Remove a custom event. Call without parameters to remove all events. @param {String} event Event name. @param {Function} fn Listener to remove. Leave empty to remove all. @param {Number} id (optional) Only remove events for this sound. @return {Howl}
[ "Remove", "a", "custom", "event", ".", "Call", "without", "parameters", "to", "remove", "all", "events", "." ]
030db918dd8ce640afd57e172418472497e8f113
https://github.com/goldfire/howler.js/blob/030db918dd8ce640afd57e172418472497e8f113/dist/howler.js#L1789-L1823
1,478
goldfire/howler.js
dist/howler.js
function(event, fn, id) { var self = this; // Setup the event listener. self.on(event, fn, id, 1); return self; }
javascript
function(event, fn, id) { var self = this; // Setup the event listener. self.on(event, fn, id, 1); return self; }
[ "function", "(", "event", ",", "fn", ",", "id", ")", "{", "var", "self", "=", "this", ";", "// Setup the event listener.", "self", ".", "on", "(", "event", ",", "fn", ",", "id", ",", "1", ")", ";", "return", "self", ";", "}" ]
Listen to a custom event and remove it once fired. @param {String} event Event name. @param {Function} fn Listener to call. @param {Number} id (optional) Only listen to events for this sound. @return {Howl}
[ "Listen", "to", "a", "custom", "event", "and", "remove", "it", "once", "fired", "." ]
030db918dd8ce640afd57e172418472497e8f113
https://github.com/goldfire/howler.js/blob/030db918dd8ce640afd57e172418472497e8f113/dist/howler.js#L1832-L1839
1,479
goldfire/howler.js
dist/howler.js
function(event, id, msg) { var self = this; var events = self['_on' + event]; // Loop through event store and fire all functions. for (var i=events.length-1; i>=0; i--) { // Only fire the listener if the correct ID is used. if (!events[i].id || events[i].id === id || event === 'load') { setTimeout(function(fn) { fn.call(this, id, msg); }.bind(self, events[i].fn), 0); // If this event was setup with `once`, remove it. if (events[i].once) { self.off(event, events[i].fn, events[i].id); } } } // Pass the event type into load queue so that it can continue stepping. self._loadQueue(event); return self; }
javascript
function(event, id, msg) { var self = this; var events = self['_on' + event]; // Loop through event store and fire all functions. for (var i=events.length-1; i>=0; i--) { // Only fire the listener if the correct ID is used. if (!events[i].id || events[i].id === id || event === 'load') { setTimeout(function(fn) { fn.call(this, id, msg); }.bind(self, events[i].fn), 0); // If this event was setup with `once`, remove it. if (events[i].once) { self.off(event, events[i].fn, events[i].id); } } } // Pass the event type into load queue so that it can continue stepping. self._loadQueue(event); return self; }
[ "function", "(", "event", ",", "id", ",", "msg", ")", "{", "var", "self", "=", "this", ";", "var", "events", "=", "self", "[", "'_on'", "+", "event", "]", ";", "// Loop through event store and fire all functions.", "for", "(", "var", "i", "=", "events", ".", "length", "-", "1", ";", "i", ">=", "0", ";", "i", "--", ")", "{", "// Only fire the listener if the correct ID is used.", "if", "(", "!", "events", "[", "i", "]", ".", "id", "||", "events", "[", "i", "]", ".", "id", "===", "id", "||", "event", "===", "'load'", ")", "{", "setTimeout", "(", "function", "(", "fn", ")", "{", "fn", ".", "call", "(", "this", ",", "id", ",", "msg", ")", ";", "}", ".", "bind", "(", "self", ",", "events", "[", "i", "]", ".", "fn", ")", ",", "0", ")", ";", "// If this event was setup with `once`, remove it.", "if", "(", "events", "[", "i", "]", ".", "once", ")", "{", "self", ".", "off", "(", "event", ",", "events", "[", "i", "]", ".", "fn", ",", "events", "[", "i", "]", ".", "id", ")", ";", "}", "}", "}", "// Pass the event type into load queue so that it can continue stepping.", "self", ".", "_loadQueue", "(", "event", ")", ";", "return", "self", ";", "}" ]
Emit all events of a specific type and pass the sound id. @param {String} event Event name. @param {Number} id Sound ID. @param {Number} msg Message to go with event. @return {Howl}
[ "Emit", "all", "events", "of", "a", "specific", "type", "and", "pass", "the", "sound", "id", "." ]
030db918dd8ce640afd57e172418472497e8f113
https://github.com/goldfire/howler.js/blob/030db918dd8ce640afd57e172418472497e8f113/dist/howler.js#L1848-L1871
1,480
goldfire/howler.js
dist/howler.js
function(sound) { var self = this; var sprite = sound._sprite; // If we are using IE and there was network latency we may be clipping // audio before it completes playing. Lets check the node to make sure it // believes it has completed, before ending the playback. if (!self._webAudio && sound._node && !sound._node.paused && !sound._node.ended && sound._node.currentTime < sound._stop) { setTimeout(self._ended.bind(self, sound), 100); return self; } // Should this sound loop? var loop = !!(sound._loop || self._sprite[sprite][2]); // Fire the ended event. self._emit('end', sound._id); // Restart the playback for HTML5 Audio loop. if (!self._webAudio && loop) { self.stop(sound._id, true).play(sound._id); } // Restart this timer if on a Web Audio loop. if (self._webAudio && loop) { self._emit('play', sound._id); sound._seek = sound._start || 0; sound._rateSeek = 0; sound._playStart = Howler.ctx.currentTime; var timeout = ((sound._stop - sound._start) * 1000) / Math.abs(sound._rate); self._endTimers[sound._id] = setTimeout(self._ended.bind(self, sound), timeout); } // Mark the node as paused. if (self._webAudio && !loop) { sound._paused = true; sound._ended = true; sound._seek = sound._start || 0; sound._rateSeek = 0; self._clearTimer(sound._id); // Clean up the buffer source. self._cleanBuffer(sound._node); // Attempt to auto-suspend AudioContext if no sounds are still playing. Howler._autoSuspend(); } // When using a sprite, end the track. if (!self._webAudio && !loop) { self.stop(sound._id, true); } return self; }
javascript
function(sound) { var self = this; var sprite = sound._sprite; // If we are using IE and there was network latency we may be clipping // audio before it completes playing. Lets check the node to make sure it // believes it has completed, before ending the playback. if (!self._webAudio && sound._node && !sound._node.paused && !sound._node.ended && sound._node.currentTime < sound._stop) { setTimeout(self._ended.bind(self, sound), 100); return self; } // Should this sound loop? var loop = !!(sound._loop || self._sprite[sprite][2]); // Fire the ended event. self._emit('end', sound._id); // Restart the playback for HTML5 Audio loop. if (!self._webAudio && loop) { self.stop(sound._id, true).play(sound._id); } // Restart this timer if on a Web Audio loop. if (self._webAudio && loop) { self._emit('play', sound._id); sound._seek = sound._start || 0; sound._rateSeek = 0; sound._playStart = Howler.ctx.currentTime; var timeout = ((sound._stop - sound._start) * 1000) / Math.abs(sound._rate); self._endTimers[sound._id] = setTimeout(self._ended.bind(self, sound), timeout); } // Mark the node as paused. if (self._webAudio && !loop) { sound._paused = true; sound._ended = true; sound._seek = sound._start || 0; sound._rateSeek = 0; self._clearTimer(sound._id); // Clean up the buffer source. self._cleanBuffer(sound._node); // Attempt to auto-suspend AudioContext if no sounds are still playing. Howler._autoSuspend(); } // When using a sprite, end the track. if (!self._webAudio && !loop) { self.stop(sound._id, true); } return self; }
[ "function", "(", "sound", ")", "{", "var", "self", "=", "this", ";", "var", "sprite", "=", "sound", ".", "_sprite", ";", "// If we are using IE and there was network latency we may be clipping", "// audio before it completes playing. Lets check the node to make sure it", "// believes it has completed, before ending the playback.", "if", "(", "!", "self", ".", "_webAudio", "&&", "sound", ".", "_node", "&&", "!", "sound", ".", "_node", ".", "paused", "&&", "!", "sound", ".", "_node", ".", "ended", "&&", "sound", ".", "_node", ".", "currentTime", "<", "sound", ".", "_stop", ")", "{", "setTimeout", "(", "self", ".", "_ended", ".", "bind", "(", "self", ",", "sound", ")", ",", "100", ")", ";", "return", "self", ";", "}", "// Should this sound loop?", "var", "loop", "=", "!", "!", "(", "sound", ".", "_loop", "||", "self", ".", "_sprite", "[", "sprite", "]", "[", "2", "]", ")", ";", "// Fire the ended event.", "self", ".", "_emit", "(", "'end'", ",", "sound", ".", "_id", ")", ";", "// Restart the playback for HTML5 Audio loop.", "if", "(", "!", "self", ".", "_webAudio", "&&", "loop", ")", "{", "self", ".", "stop", "(", "sound", ".", "_id", ",", "true", ")", ".", "play", "(", "sound", ".", "_id", ")", ";", "}", "// Restart this timer if on a Web Audio loop.", "if", "(", "self", ".", "_webAudio", "&&", "loop", ")", "{", "self", ".", "_emit", "(", "'play'", ",", "sound", ".", "_id", ")", ";", "sound", ".", "_seek", "=", "sound", ".", "_start", "||", "0", ";", "sound", ".", "_rateSeek", "=", "0", ";", "sound", ".", "_playStart", "=", "Howler", ".", "ctx", ".", "currentTime", ";", "var", "timeout", "=", "(", "(", "sound", ".", "_stop", "-", "sound", ".", "_start", ")", "*", "1000", ")", "/", "Math", ".", "abs", "(", "sound", ".", "_rate", ")", ";", "self", ".", "_endTimers", "[", "sound", ".", "_id", "]", "=", "setTimeout", "(", "self", ".", "_ended", ".", "bind", "(", "self", ",", "sound", ")", ",", "timeout", ")", ";", "}", "// Mark the node as paused.", "if", "(", "self", ".", "_webAudio", "&&", "!", "loop", ")", "{", "sound", ".", "_paused", "=", "true", ";", "sound", ".", "_ended", "=", "true", ";", "sound", ".", "_seek", "=", "sound", ".", "_start", "||", "0", ";", "sound", ".", "_rateSeek", "=", "0", ";", "self", ".", "_clearTimer", "(", "sound", ".", "_id", ")", ";", "// Clean up the buffer source.", "self", ".", "_cleanBuffer", "(", "sound", ".", "_node", ")", ";", "// Attempt to auto-suspend AudioContext if no sounds are still playing.", "Howler", ".", "_autoSuspend", "(", ")", ";", "}", "// When using a sprite, end the track.", "if", "(", "!", "self", ".", "_webAudio", "&&", "!", "loop", ")", "{", "self", ".", "stop", "(", "sound", ".", "_id", ",", "true", ")", ";", "}", "return", "self", ";", "}" ]
Fired when playback ends at the end of the duration. @param {Sound} sound The sound object to work with. @return {Howl}
[ "Fired", "when", "playback", "ends", "at", "the", "end", "of", "the", "duration", "." ]
030db918dd8ce640afd57e172418472497e8f113
https://github.com/goldfire/howler.js/blob/030db918dd8ce640afd57e172418472497e8f113/dist/howler.js#L1905-L1960
1,481
goldfire/howler.js
dist/howler.js
function(id) { var self = this; if (self._endTimers[id]) { // Clear the timeout or remove the ended listener. if (typeof self._endTimers[id] !== 'function') { clearTimeout(self._endTimers[id]); } else { var sound = self._soundById(id); if (sound && sound._node) { sound._node.removeEventListener('ended', self._endTimers[id], false); } } delete self._endTimers[id]; } return self; }
javascript
function(id) { var self = this; if (self._endTimers[id]) { // Clear the timeout or remove the ended listener. if (typeof self._endTimers[id] !== 'function') { clearTimeout(self._endTimers[id]); } else { var sound = self._soundById(id); if (sound && sound._node) { sound._node.removeEventListener('ended', self._endTimers[id], false); } } delete self._endTimers[id]; } return self; }
[ "function", "(", "id", ")", "{", "var", "self", "=", "this", ";", "if", "(", "self", ".", "_endTimers", "[", "id", "]", ")", "{", "// Clear the timeout or remove the ended listener.", "if", "(", "typeof", "self", ".", "_endTimers", "[", "id", "]", "!==", "'function'", ")", "{", "clearTimeout", "(", "self", ".", "_endTimers", "[", "id", "]", ")", ";", "}", "else", "{", "var", "sound", "=", "self", ".", "_soundById", "(", "id", ")", ";", "if", "(", "sound", "&&", "sound", ".", "_node", ")", "{", "sound", ".", "_node", ".", "removeEventListener", "(", "'ended'", ",", "self", ".", "_endTimers", "[", "id", "]", ",", "false", ")", ";", "}", "}", "delete", "self", ".", "_endTimers", "[", "id", "]", ";", "}", "return", "self", ";", "}" ]
Clear the end timer for a sound playback. @param {Number} id The sound ID. @return {Howl}
[ "Clear", "the", "end", "timer", "for", "a", "sound", "playback", "." ]
030db918dd8ce640afd57e172418472497e8f113
https://github.com/goldfire/howler.js/blob/030db918dd8ce640afd57e172418472497e8f113/dist/howler.js#L1967-L1985
1,482
goldfire/howler.js
dist/howler.js
function(id) { var self = this; // Loop through all sounds and find the one with this ID. for (var i=0; i<self._sounds.length; i++) { if (id === self._sounds[i]._id) { return self._sounds[i]; } } return null; }
javascript
function(id) { var self = this; // Loop through all sounds and find the one with this ID. for (var i=0; i<self._sounds.length; i++) { if (id === self._sounds[i]._id) { return self._sounds[i]; } } return null; }
[ "function", "(", "id", ")", "{", "var", "self", "=", "this", ";", "// Loop through all sounds and find the one with this ID.", "for", "(", "var", "i", "=", "0", ";", "i", "<", "self", ".", "_sounds", ".", "length", ";", "i", "++", ")", "{", "if", "(", "id", "===", "self", ".", "_sounds", "[", "i", "]", ".", "_id", ")", "{", "return", "self", ".", "_sounds", "[", "i", "]", ";", "}", "}", "return", "null", ";", "}" ]
Return the sound identified by this ID, or return null. @param {Number} id Sound ID @return {Object} Sound object or null.
[ "Return", "the", "sound", "identified", "by", "this", "ID", "or", "return", "null", "." ]
030db918dd8ce640afd57e172418472497e8f113
https://github.com/goldfire/howler.js/blob/030db918dd8ce640afd57e172418472497e8f113/dist/howler.js#L1992-L2003
1,483
goldfire/howler.js
dist/howler.js
function() { var self = this; self._drain(); // Find the first inactive node to recycle. for (var i=0; i<self._sounds.length; i++) { if (self._sounds[i]._ended) { return self._sounds[i].reset(); } } // If no inactive node was found, create a new one. return new Sound(self); }
javascript
function() { var self = this; self._drain(); // Find the first inactive node to recycle. for (var i=0; i<self._sounds.length; i++) { if (self._sounds[i]._ended) { return self._sounds[i].reset(); } } // If no inactive node was found, create a new one. return new Sound(self); }
[ "function", "(", ")", "{", "var", "self", "=", "this", ";", "self", ".", "_drain", "(", ")", ";", "// Find the first inactive node to recycle.", "for", "(", "var", "i", "=", "0", ";", "i", "<", "self", ".", "_sounds", ".", "length", ";", "i", "++", ")", "{", "if", "(", "self", ".", "_sounds", "[", "i", "]", ".", "_ended", ")", "{", "return", "self", ".", "_sounds", "[", "i", "]", ".", "reset", "(", ")", ";", "}", "}", "// If no inactive node was found, create a new one.", "return", "new", "Sound", "(", "self", ")", ";", "}" ]
Return an inactive sound from the pool or create a new one. @return {Sound} Sound playback object.
[ "Return", "an", "inactive", "sound", "from", "the", "pool", "or", "create", "a", "new", "one", "." ]
030db918dd8ce640afd57e172418472497e8f113
https://github.com/goldfire/howler.js/blob/030db918dd8ce640afd57e172418472497e8f113/dist/howler.js#L2009-L2023
1,484
goldfire/howler.js
dist/howler.js
function() { var self = this; var limit = self._pool; var cnt = 0; var i = 0; // If there are less sounds than the max pool size, we are done. if (self._sounds.length < limit) { return; } // Count the number of inactive sounds. for (i=0; i<self._sounds.length; i++) { if (self._sounds[i]._ended) { cnt++; } } // Remove excess inactive sounds, going in reverse order. for (i=self._sounds.length - 1; i>=0; i--) { if (cnt <= limit) { return; } if (self._sounds[i]._ended) { // Disconnect the audio source when using Web Audio. if (self._webAudio && self._sounds[i]._node) { self._sounds[i]._node.disconnect(0); } // Remove sounds until we have the pool size. self._sounds.splice(i, 1); cnt--; } } }
javascript
function() { var self = this; var limit = self._pool; var cnt = 0; var i = 0; // If there are less sounds than the max pool size, we are done. if (self._sounds.length < limit) { return; } // Count the number of inactive sounds. for (i=0; i<self._sounds.length; i++) { if (self._sounds[i]._ended) { cnt++; } } // Remove excess inactive sounds, going in reverse order. for (i=self._sounds.length - 1; i>=0; i--) { if (cnt <= limit) { return; } if (self._sounds[i]._ended) { // Disconnect the audio source when using Web Audio. if (self._webAudio && self._sounds[i]._node) { self._sounds[i]._node.disconnect(0); } // Remove sounds until we have the pool size. self._sounds.splice(i, 1); cnt--; } } }
[ "function", "(", ")", "{", "var", "self", "=", "this", ";", "var", "limit", "=", "self", ".", "_pool", ";", "var", "cnt", "=", "0", ";", "var", "i", "=", "0", ";", "// If there are less sounds than the max pool size, we are done.", "if", "(", "self", ".", "_sounds", ".", "length", "<", "limit", ")", "{", "return", ";", "}", "// Count the number of inactive sounds.", "for", "(", "i", "=", "0", ";", "i", "<", "self", ".", "_sounds", ".", "length", ";", "i", "++", ")", "{", "if", "(", "self", ".", "_sounds", "[", "i", "]", ".", "_ended", ")", "{", "cnt", "++", ";", "}", "}", "// Remove excess inactive sounds, going in reverse order.", "for", "(", "i", "=", "self", ".", "_sounds", ".", "length", "-", "1", ";", "i", ">=", "0", ";", "i", "--", ")", "{", "if", "(", "cnt", "<=", "limit", ")", "{", "return", ";", "}", "if", "(", "self", ".", "_sounds", "[", "i", "]", ".", "_ended", ")", "{", "// Disconnect the audio source when using Web Audio.", "if", "(", "self", ".", "_webAudio", "&&", "self", ".", "_sounds", "[", "i", "]", ".", "_node", ")", "{", "self", ".", "_sounds", "[", "i", "]", ".", "_node", ".", "disconnect", "(", "0", ")", ";", "}", "// Remove sounds until we have the pool size.", "self", ".", "_sounds", ".", "splice", "(", "i", ",", "1", ")", ";", "cnt", "--", ";", "}", "}", "}" ]
Drain excess inactive sounds from the pool.
[ "Drain", "excess", "inactive", "sounds", "from", "the", "pool", "." ]
030db918dd8ce640afd57e172418472497e8f113
https://github.com/goldfire/howler.js/blob/030db918dd8ce640afd57e172418472497e8f113/dist/howler.js#L2028-L2063
1,485
goldfire/howler.js
dist/howler.js
function(id) { var self = this; if (typeof id === 'undefined') { var ids = []; for (var i=0; i<self._sounds.length; i++) { ids.push(self._sounds[i]._id); } return ids; } else { return [id]; } }
javascript
function(id) { var self = this; if (typeof id === 'undefined') { var ids = []; for (var i=0; i<self._sounds.length; i++) { ids.push(self._sounds[i]._id); } return ids; } else { return [id]; } }
[ "function", "(", "id", ")", "{", "var", "self", "=", "this", ";", "if", "(", "typeof", "id", "===", "'undefined'", ")", "{", "var", "ids", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "self", ".", "_sounds", ".", "length", ";", "i", "++", ")", "{", "ids", ".", "push", "(", "self", ".", "_sounds", "[", "i", "]", ".", "_id", ")", ";", "}", "return", "ids", ";", "}", "else", "{", "return", "[", "id", "]", ";", "}", "}" ]
Get all ID's from the sounds pool. @param {Number} id Only return one ID if one is passed. @return {Array} Array of IDs.
[ "Get", "all", "ID", "s", "from", "the", "sounds", "pool", "." ]
030db918dd8ce640afd57e172418472497e8f113
https://github.com/goldfire/howler.js/blob/030db918dd8ce640afd57e172418472497e8f113/dist/howler.js#L2070-L2083
1,486
goldfire/howler.js
dist/howler.js
function(sound) { var self = this; // Setup the buffer source for playback. sound._node.bufferSource = Howler.ctx.createBufferSource(); sound._node.bufferSource.buffer = cache[self._src]; // Connect to the correct node. if (sound._panner) { sound._node.bufferSource.connect(sound._panner); } else { sound._node.bufferSource.connect(sound._node); } // Setup looping and playback rate. sound._node.bufferSource.loop = sound._loop; if (sound._loop) { sound._node.bufferSource.loopStart = sound._start || 0; sound._node.bufferSource.loopEnd = sound._stop || 0; } sound._node.bufferSource.playbackRate.setValueAtTime(sound._rate, Howler.ctx.currentTime); return self; }
javascript
function(sound) { var self = this; // Setup the buffer source for playback. sound._node.bufferSource = Howler.ctx.createBufferSource(); sound._node.bufferSource.buffer = cache[self._src]; // Connect to the correct node. if (sound._panner) { sound._node.bufferSource.connect(sound._panner); } else { sound._node.bufferSource.connect(sound._node); } // Setup looping and playback rate. sound._node.bufferSource.loop = sound._loop; if (sound._loop) { sound._node.bufferSource.loopStart = sound._start || 0; sound._node.bufferSource.loopEnd = sound._stop || 0; } sound._node.bufferSource.playbackRate.setValueAtTime(sound._rate, Howler.ctx.currentTime); return self; }
[ "function", "(", "sound", ")", "{", "var", "self", "=", "this", ";", "// Setup the buffer source for playback.", "sound", ".", "_node", ".", "bufferSource", "=", "Howler", ".", "ctx", ".", "createBufferSource", "(", ")", ";", "sound", ".", "_node", ".", "bufferSource", ".", "buffer", "=", "cache", "[", "self", ".", "_src", "]", ";", "// Connect to the correct node.", "if", "(", "sound", ".", "_panner", ")", "{", "sound", ".", "_node", ".", "bufferSource", ".", "connect", "(", "sound", ".", "_panner", ")", ";", "}", "else", "{", "sound", ".", "_node", ".", "bufferSource", ".", "connect", "(", "sound", ".", "_node", ")", ";", "}", "// Setup looping and playback rate.", "sound", ".", "_node", ".", "bufferSource", ".", "loop", "=", "sound", ".", "_loop", ";", "if", "(", "sound", ".", "_loop", ")", "{", "sound", ".", "_node", ".", "bufferSource", ".", "loopStart", "=", "sound", ".", "_start", "||", "0", ";", "sound", ".", "_node", ".", "bufferSource", ".", "loopEnd", "=", "sound", ".", "_stop", "||", "0", ";", "}", "sound", ".", "_node", ".", "bufferSource", ".", "playbackRate", ".", "setValueAtTime", "(", "sound", ".", "_rate", ",", "Howler", ".", "ctx", ".", "currentTime", ")", ";", "return", "self", ";", "}" ]
Load the sound back into the buffer source. @param {Sound} sound The sound object to work with. @return {Howl}
[ "Load", "the", "sound", "back", "into", "the", "buffer", "source", "." ]
030db918dd8ce640afd57e172418472497e8f113
https://github.com/goldfire/howler.js/blob/030db918dd8ce640afd57e172418472497e8f113/dist/howler.js#L2090-L2113
1,487
goldfire/howler.js
dist/howler.js
function(node) { var self = this; var isIOS = Howler._navigator && Howler._navigator.vendor.indexOf('Apple') >= 0; if (Howler._scratchBuffer && node.bufferSource) { node.bufferSource.onended = null; node.bufferSource.disconnect(0); if (isIOS) { try { node.bufferSource.buffer = Howler._scratchBuffer; } catch(e) {} } } node.bufferSource = null; return self; }
javascript
function(node) { var self = this; var isIOS = Howler._navigator && Howler._navigator.vendor.indexOf('Apple') >= 0; if (Howler._scratchBuffer && node.bufferSource) { node.bufferSource.onended = null; node.bufferSource.disconnect(0); if (isIOS) { try { node.bufferSource.buffer = Howler._scratchBuffer; } catch(e) {} } } node.bufferSource = null; return self; }
[ "function", "(", "node", ")", "{", "var", "self", "=", "this", ";", "var", "isIOS", "=", "Howler", ".", "_navigator", "&&", "Howler", ".", "_navigator", ".", "vendor", ".", "indexOf", "(", "'Apple'", ")", ">=", "0", ";", "if", "(", "Howler", ".", "_scratchBuffer", "&&", "node", ".", "bufferSource", ")", "{", "node", ".", "bufferSource", ".", "onended", "=", "null", ";", "node", ".", "bufferSource", ".", "disconnect", "(", "0", ")", ";", "if", "(", "isIOS", ")", "{", "try", "{", "node", ".", "bufferSource", ".", "buffer", "=", "Howler", ".", "_scratchBuffer", ";", "}", "catch", "(", "e", ")", "{", "}", "}", "}", "node", ".", "bufferSource", "=", "null", ";", "return", "self", ";", "}" ]
Prevent memory leaks by cleaning up the buffer source after playback. @param {Object} node Sound's audio node containing the buffer source. @return {Howl}
[ "Prevent", "memory", "leaks", "by", "cleaning", "up", "the", "buffer", "source", "after", "playback", "." ]
030db918dd8ce640afd57e172418472497e8f113
https://github.com/goldfire/howler.js/blob/030db918dd8ce640afd57e172418472497e8f113/dist/howler.js#L2120-L2134
1,488
goldfire/howler.js
dist/howler.js
function() { var self = this; var parent = self._parent; // Setup the default parameters. self._muted = parent._muted; self._loop = parent._loop; self._volume = parent._volume; self._rate = parent._rate; self._seek = 0; self._paused = true; self._ended = true; self._sprite = '__default'; // Generate a unique ID for this sound. self._id = ++Howler._counter; // Add itself to the parent's pool. parent._sounds.push(self); // Create the new node. self.create(); return self; }
javascript
function() { var self = this; var parent = self._parent; // Setup the default parameters. self._muted = parent._muted; self._loop = parent._loop; self._volume = parent._volume; self._rate = parent._rate; self._seek = 0; self._paused = true; self._ended = true; self._sprite = '__default'; // Generate a unique ID for this sound. self._id = ++Howler._counter; // Add itself to the parent's pool. parent._sounds.push(self); // Create the new node. self.create(); return self; }
[ "function", "(", ")", "{", "var", "self", "=", "this", ";", "var", "parent", "=", "self", ".", "_parent", ";", "// Setup the default parameters.", "self", ".", "_muted", "=", "parent", ".", "_muted", ";", "self", ".", "_loop", "=", "parent", ".", "_loop", ";", "self", ".", "_volume", "=", "parent", ".", "_volume", ";", "self", ".", "_rate", "=", "parent", ".", "_rate", ";", "self", ".", "_seek", "=", "0", ";", "self", ".", "_paused", "=", "true", ";", "self", ".", "_ended", "=", "true", ";", "self", ".", "_sprite", "=", "'__default'", ";", "// Generate a unique ID for this sound.", "self", ".", "_id", "=", "++", "Howler", ".", "_counter", ";", "// Add itself to the parent's pool.", "parent", ".", "_sounds", ".", "push", "(", "self", ")", ";", "// Create the new node.", "self", ".", "create", "(", ")", ";", "return", "self", ";", "}" ]
Initialize a new Sound object. @return {Sound}
[ "Initialize", "a", "new", "Sound", "object", "." ]
030db918dd8ce640afd57e172418472497e8f113
https://github.com/goldfire/howler.js/blob/030db918dd8ce640afd57e172418472497e8f113/dist/howler.js#L2164-L2188
1,489
goldfire/howler.js
dist/howler.js
function() { var self = this; var parent = self._parent; var volume = (Howler._muted || self._muted || self._parent._muted) ? 0 : self._volume; if (parent._webAudio) { // Create the gain node for controlling volume (the source will connect to this). self._node = (typeof Howler.ctx.createGain === 'undefined') ? Howler.ctx.createGainNode() : Howler.ctx.createGain(); self._node.gain.setValueAtTime(volume, Howler.ctx.currentTime); self._node.paused = true; self._node.connect(Howler.masterGain); } else { // Get an unlocked Audio object from the pool. self._node = Howler._obtainHtml5Audio(); // Listen for errors (http://dev.w3.org/html5/spec-author-view/spec.html#mediaerror). self._errorFn = self._errorListener.bind(self); self._node.addEventListener('error', self._errorFn, false); // Listen for 'canplaythrough' event to let us know the sound is ready. self._loadFn = self._loadListener.bind(self); self._node.addEventListener(Howler._canPlayEvent, self._loadFn, false); // Setup the new audio node. self._node.src = parent._src; self._node.preload = 'auto'; self._node.volume = volume * Howler.volume(); // Begin loading the source. self._node.load(); } return self; }
javascript
function() { var self = this; var parent = self._parent; var volume = (Howler._muted || self._muted || self._parent._muted) ? 0 : self._volume; if (parent._webAudio) { // Create the gain node for controlling volume (the source will connect to this). self._node = (typeof Howler.ctx.createGain === 'undefined') ? Howler.ctx.createGainNode() : Howler.ctx.createGain(); self._node.gain.setValueAtTime(volume, Howler.ctx.currentTime); self._node.paused = true; self._node.connect(Howler.masterGain); } else { // Get an unlocked Audio object from the pool. self._node = Howler._obtainHtml5Audio(); // Listen for errors (http://dev.w3.org/html5/spec-author-view/spec.html#mediaerror). self._errorFn = self._errorListener.bind(self); self._node.addEventListener('error', self._errorFn, false); // Listen for 'canplaythrough' event to let us know the sound is ready. self._loadFn = self._loadListener.bind(self); self._node.addEventListener(Howler._canPlayEvent, self._loadFn, false); // Setup the new audio node. self._node.src = parent._src; self._node.preload = 'auto'; self._node.volume = volume * Howler.volume(); // Begin loading the source. self._node.load(); } return self; }
[ "function", "(", ")", "{", "var", "self", "=", "this", ";", "var", "parent", "=", "self", ".", "_parent", ";", "var", "volume", "=", "(", "Howler", ".", "_muted", "||", "self", ".", "_muted", "||", "self", ".", "_parent", ".", "_muted", ")", "?", "0", ":", "self", ".", "_volume", ";", "if", "(", "parent", ".", "_webAudio", ")", "{", "// Create the gain node for controlling volume (the source will connect to this).", "self", ".", "_node", "=", "(", "typeof", "Howler", ".", "ctx", ".", "createGain", "===", "'undefined'", ")", "?", "Howler", ".", "ctx", ".", "createGainNode", "(", ")", ":", "Howler", ".", "ctx", ".", "createGain", "(", ")", ";", "self", ".", "_node", ".", "gain", ".", "setValueAtTime", "(", "volume", ",", "Howler", ".", "ctx", ".", "currentTime", ")", ";", "self", ".", "_node", ".", "paused", "=", "true", ";", "self", ".", "_node", ".", "connect", "(", "Howler", ".", "masterGain", ")", ";", "}", "else", "{", "// Get an unlocked Audio object from the pool.", "self", ".", "_node", "=", "Howler", ".", "_obtainHtml5Audio", "(", ")", ";", "// Listen for errors (http://dev.w3.org/html5/spec-author-view/spec.html#mediaerror).", "self", ".", "_errorFn", "=", "self", ".", "_errorListener", ".", "bind", "(", "self", ")", ";", "self", ".", "_node", ".", "addEventListener", "(", "'error'", ",", "self", ".", "_errorFn", ",", "false", ")", ";", "// Listen for 'canplaythrough' event to let us know the sound is ready.", "self", ".", "_loadFn", "=", "self", ".", "_loadListener", ".", "bind", "(", "self", ")", ";", "self", ".", "_node", ".", "addEventListener", "(", "Howler", ".", "_canPlayEvent", ",", "self", ".", "_loadFn", ",", "false", ")", ";", "// Setup the new audio node.", "self", ".", "_node", ".", "src", "=", "parent", ".", "_src", ";", "self", ".", "_node", ".", "preload", "=", "'auto'", ";", "self", ".", "_node", ".", "volume", "=", "volume", "*", "Howler", ".", "volume", "(", ")", ";", "// Begin loading the source.", "self", ".", "_node", ".", "load", "(", ")", ";", "}", "return", "self", ";", "}" ]
Create and setup a new sound object, whether HTML5 Audio or Web Audio. @return {Sound}
[ "Create", "and", "setup", "a", "new", "sound", "object", "whether", "HTML5", "Audio", "or", "Web", "Audio", "." ]
030db918dd8ce640afd57e172418472497e8f113
https://github.com/goldfire/howler.js/blob/030db918dd8ce640afd57e172418472497e8f113/dist/howler.js#L2194-L2227
1,490
goldfire/howler.js
dist/howler.js
function() { var self = this; // Fire an error event and pass back the code. self._parent._emit('loaderror', self._id, self._node.error ? self._node.error.code : 0); // Clear the event listener. self._node.removeEventListener('error', self._errorFn, false); }
javascript
function() { var self = this; // Fire an error event and pass back the code. self._parent._emit('loaderror', self._id, self._node.error ? self._node.error.code : 0); // Clear the event listener. self._node.removeEventListener('error', self._errorFn, false); }
[ "function", "(", ")", "{", "var", "self", "=", "this", ";", "// Fire an error event and pass back the code.", "self", ".", "_parent", ".", "_emit", "(", "'loaderror'", ",", "self", ".", "_id", ",", "self", ".", "_node", ".", "error", "?", "self", ".", "_node", ".", "error", ".", "code", ":", "0", ")", ";", "// Clear the event listener.", "self", ".", "_node", ".", "removeEventListener", "(", "'error'", ",", "self", ".", "_errorFn", ",", "false", ")", ";", "}" ]
HTML5 Audio error listener callback.
[ "HTML5", "Audio", "error", "listener", "callback", "." ]
030db918dd8ce640afd57e172418472497e8f113
https://github.com/goldfire/howler.js/blob/030db918dd8ce640afd57e172418472497e8f113/dist/howler.js#L2257-L2265
1,491
goldfire/howler.js
dist/howler.js
function() { var self = this; var parent = self._parent; // Round up the duration to account for the lower precision in HTML5 Audio. parent._duration = Math.ceil(self._node.duration * 10) / 10; // Setup a sprite if none is defined. if (Object.keys(parent._sprite).length === 0) { parent._sprite = {__default: [0, parent._duration * 1000]}; } if (parent._state !== 'loaded') { parent._state = 'loaded'; parent._emit('load'); parent._loadQueue(); } // Clear the event listener. self._node.removeEventListener(Howler._canPlayEvent, self._loadFn, false); }
javascript
function() { var self = this; var parent = self._parent; // Round up the duration to account for the lower precision in HTML5 Audio. parent._duration = Math.ceil(self._node.duration * 10) / 10; // Setup a sprite if none is defined. if (Object.keys(parent._sprite).length === 0) { parent._sprite = {__default: [0, parent._duration * 1000]}; } if (parent._state !== 'loaded') { parent._state = 'loaded'; parent._emit('load'); parent._loadQueue(); } // Clear the event listener. self._node.removeEventListener(Howler._canPlayEvent, self._loadFn, false); }
[ "function", "(", ")", "{", "var", "self", "=", "this", ";", "var", "parent", "=", "self", ".", "_parent", ";", "// Round up the duration to account for the lower precision in HTML5 Audio.", "parent", ".", "_duration", "=", "Math", ".", "ceil", "(", "self", ".", "_node", ".", "duration", "*", "10", ")", "/", "10", ";", "// Setup a sprite if none is defined.", "if", "(", "Object", ".", "keys", "(", "parent", ".", "_sprite", ")", ".", "length", "===", "0", ")", "{", "parent", ".", "_sprite", "=", "{", "__default", ":", "[", "0", ",", "parent", ".", "_duration", "*", "1000", "]", "}", ";", "}", "if", "(", "parent", ".", "_state", "!==", "'loaded'", ")", "{", "parent", ".", "_state", "=", "'loaded'", ";", "parent", ".", "_emit", "(", "'load'", ")", ";", "parent", ".", "_loadQueue", "(", ")", ";", "}", "// Clear the event listener.", "self", ".", "_node", ".", "removeEventListener", "(", "Howler", ".", "_canPlayEvent", ",", "self", ".", "_loadFn", ",", "false", ")", ";", "}" ]
HTML5 Audio canplaythrough listener callback.
[ "HTML5", "Audio", "canplaythrough", "listener", "callback", "." ]
030db918dd8ce640afd57e172418472497e8f113
https://github.com/goldfire/howler.js/blob/030db918dd8ce640afd57e172418472497e8f113/dist/howler.js#L2270-L2290
1,492
goldfire/howler.js
dist/howler.js
function(arraybuffer, self) { // Fire a load error if something broke. var error = function() { self._emit('loaderror', null, 'Decoding audio data failed.'); }; // Load the sound on success. var success = function(buffer) { if (buffer && self._sounds.length > 0) { cache[self._src] = buffer; loadSound(self, buffer); } else { error(); } }; // Decode the buffer into an audio source. if (typeof Promise !== 'undefined' && Howler.ctx.decodeAudioData.length === 1) { Howler.ctx.decodeAudioData(arraybuffer).then(success).catch(error); } else { Howler.ctx.decodeAudioData(arraybuffer, success, error); } }
javascript
function(arraybuffer, self) { // Fire a load error if something broke. var error = function() { self._emit('loaderror', null, 'Decoding audio data failed.'); }; // Load the sound on success. var success = function(buffer) { if (buffer && self._sounds.length > 0) { cache[self._src] = buffer; loadSound(self, buffer); } else { error(); } }; // Decode the buffer into an audio source. if (typeof Promise !== 'undefined' && Howler.ctx.decodeAudioData.length === 1) { Howler.ctx.decodeAudioData(arraybuffer).then(success).catch(error); } else { Howler.ctx.decodeAudioData(arraybuffer, success, error); } }
[ "function", "(", "arraybuffer", ",", "self", ")", "{", "// Fire a load error if something broke.", "var", "error", "=", "function", "(", ")", "{", "self", ".", "_emit", "(", "'loaderror'", ",", "null", ",", "'Decoding audio data failed.'", ")", ";", "}", ";", "// Load the sound on success.", "var", "success", "=", "function", "(", "buffer", ")", "{", "if", "(", "buffer", "&&", "self", ".", "_sounds", ".", "length", ">", "0", ")", "{", "cache", "[", "self", ".", "_src", "]", "=", "buffer", ";", "loadSound", "(", "self", ",", "buffer", ")", ";", "}", "else", "{", "error", "(", ")", ";", "}", "}", ";", "// Decode the buffer into an audio source.", "if", "(", "typeof", "Promise", "!==", "'undefined'", "&&", "Howler", ".", "ctx", ".", "decodeAudioData", ".", "length", "===", "1", ")", "{", "Howler", ".", "ctx", ".", "decodeAudioData", "(", "arraybuffer", ")", ".", "then", "(", "success", ")", ".", "catch", "(", "error", ")", ";", "}", "else", "{", "Howler", ".", "ctx", ".", "decodeAudioData", "(", "arraybuffer", ",", "success", ",", "error", ")", ";", "}", "}" ]
Decode audio data from an array buffer. @param {ArrayBuffer} arraybuffer The audio data. @param {Howl} self
[ "Decode", "audio", "data", "from", "an", "array", "buffer", "." ]
030db918dd8ce640afd57e172418472497e8f113
https://github.com/goldfire/howler.js/blob/030db918dd8ce640afd57e172418472497e8f113/dist/howler.js#L2372-L2394
1,493
goldfire/howler.js
dist/howler.js
function(buffer) { if (buffer && self._sounds.length > 0) { cache[self._src] = buffer; loadSound(self, buffer); } else { error(); } }
javascript
function(buffer) { if (buffer && self._sounds.length > 0) { cache[self._src] = buffer; loadSound(self, buffer); } else { error(); } }
[ "function", "(", "buffer", ")", "{", "if", "(", "buffer", "&&", "self", ".", "_sounds", ".", "length", ">", "0", ")", "{", "cache", "[", "self", ".", "_src", "]", "=", "buffer", ";", "loadSound", "(", "self", ",", "buffer", ")", ";", "}", "else", "{", "error", "(", ")", ";", "}", "}" ]
Load the sound on success.
[ "Load", "the", "sound", "on", "success", "." ]
030db918dd8ce640afd57e172418472497e8f113
https://github.com/goldfire/howler.js/blob/030db918dd8ce640afd57e172418472497e8f113/dist/howler.js#L2379-L2386
1,494
goldfire/howler.js
dist/howler.js
function(self, buffer) { // Set the duration. if (buffer && !self._duration) { self._duration = buffer.duration; } // Setup a sprite if none is defined. if (Object.keys(self._sprite).length === 0) { self._sprite = {__default: [0, self._duration * 1000]}; } // Fire the loaded event. if (self._state !== 'loaded') { self._state = 'loaded'; self._emit('load'); self._loadQueue(); } }
javascript
function(self, buffer) { // Set the duration. if (buffer && !self._duration) { self._duration = buffer.duration; } // Setup a sprite if none is defined. if (Object.keys(self._sprite).length === 0) { self._sprite = {__default: [0, self._duration * 1000]}; } // Fire the loaded event. if (self._state !== 'loaded') { self._state = 'loaded'; self._emit('load'); self._loadQueue(); } }
[ "function", "(", "self", ",", "buffer", ")", "{", "// Set the duration.", "if", "(", "buffer", "&&", "!", "self", ".", "_duration", ")", "{", "self", ".", "_duration", "=", "buffer", ".", "duration", ";", "}", "// Setup a sprite if none is defined.", "if", "(", "Object", ".", "keys", "(", "self", ".", "_sprite", ")", ".", "length", "===", "0", ")", "{", "self", ".", "_sprite", "=", "{", "__default", ":", "[", "0", ",", "self", ".", "_duration", "*", "1000", "]", "}", ";", "}", "// Fire the loaded event.", "if", "(", "self", ".", "_state", "!==", "'loaded'", ")", "{", "self", ".", "_state", "=", "'loaded'", ";", "self", ".", "_emit", "(", "'load'", ")", ";", "self", ".", "_loadQueue", "(", ")", ";", "}", "}" ]
Sound is now loaded, so finish setting everything up and fire the loaded event. @param {Howl} self @param {Object} buffer The decoded buffer sound source.
[ "Sound", "is", "now", "loaded", "so", "finish", "setting", "everything", "up", "and", "fire", "the", "loaded", "event", "." ]
030db918dd8ce640afd57e172418472497e8f113
https://github.com/goldfire/howler.js/blob/030db918dd8ce640afd57e172418472497e8f113/dist/howler.js#L2401-L2418
1,495
goldfire/howler.js
dist/howler.js
function() { // If we have already detected that Web Audio isn't supported, don't run this step again. if (!Howler.usingWebAudio) { return; } // Check if we are using Web Audio and setup the AudioContext if we are. try { if (typeof AudioContext !== 'undefined') { Howler.ctx = new AudioContext(); } else if (typeof webkitAudioContext !== 'undefined') { Howler.ctx = new webkitAudioContext(); } else { Howler.usingWebAudio = false; } } catch(e) { Howler.usingWebAudio = false; } // If the audio context creation still failed, set using web audio to false. if (!Howler.ctx) { Howler.usingWebAudio = false; } // Check if a webview is being used on iOS8 or earlier (rather than the browser). // If it is, disable Web Audio as it causes crashing. var iOS = (/iP(hone|od|ad)/.test(Howler._navigator && Howler._navigator.platform)); var appVersion = Howler._navigator && Howler._navigator.appVersion.match(/OS (\d+)_(\d+)_?(\d+)?/); var version = appVersion ? parseInt(appVersion[1], 10) : null; if (iOS && version && version < 9) { var safari = /safari/.test(Howler._navigator && Howler._navigator.userAgent.toLowerCase()); if (Howler._navigator && Howler._navigator.standalone && !safari || Howler._navigator && !Howler._navigator.standalone && !safari) { Howler.usingWebAudio = false; } } // Create and expose the master GainNode when using Web Audio (useful for plugins or advanced usage). if (Howler.usingWebAudio) { Howler.masterGain = (typeof Howler.ctx.createGain === 'undefined') ? Howler.ctx.createGainNode() : Howler.ctx.createGain(); Howler.masterGain.gain.setValueAtTime(Howler._muted ? 0 : 1, Howler.ctx.currentTime); Howler.masterGain.connect(Howler.ctx.destination); } // Re-run the setup on Howler. Howler._setup(); }
javascript
function() { // If we have already detected that Web Audio isn't supported, don't run this step again. if (!Howler.usingWebAudio) { return; } // Check if we are using Web Audio and setup the AudioContext if we are. try { if (typeof AudioContext !== 'undefined') { Howler.ctx = new AudioContext(); } else if (typeof webkitAudioContext !== 'undefined') { Howler.ctx = new webkitAudioContext(); } else { Howler.usingWebAudio = false; } } catch(e) { Howler.usingWebAudio = false; } // If the audio context creation still failed, set using web audio to false. if (!Howler.ctx) { Howler.usingWebAudio = false; } // Check if a webview is being used on iOS8 or earlier (rather than the browser). // If it is, disable Web Audio as it causes crashing. var iOS = (/iP(hone|od|ad)/.test(Howler._navigator && Howler._navigator.platform)); var appVersion = Howler._navigator && Howler._navigator.appVersion.match(/OS (\d+)_(\d+)_?(\d+)?/); var version = appVersion ? parseInt(appVersion[1], 10) : null; if (iOS && version && version < 9) { var safari = /safari/.test(Howler._navigator && Howler._navigator.userAgent.toLowerCase()); if (Howler._navigator && Howler._navigator.standalone && !safari || Howler._navigator && !Howler._navigator.standalone && !safari) { Howler.usingWebAudio = false; } } // Create and expose the master GainNode when using Web Audio (useful for plugins or advanced usage). if (Howler.usingWebAudio) { Howler.masterGain = (typeof Howler.ctx.createGain === 'undefined') ? Howler.ctx.createGainNode() : Howler.ctx.createGain(); Howler.masterGain.gain.setValueAtTime(Howler._muted ? 0 : 1, Howler.ctx.currentTime); Howler.masterGain.connect(Howler.ctx.destination); } // Re-run the setup on Howler. Howler._setup(); }
[ "function", "(", ")", "{", "// If we have already detected that Web Audio isn't supported, don't run this step again.", "if", "(", "!", "Howler", ".", "usingWebAudio", ")", "{", "return", ";", "}", "// Check if we are using Web Audio and setup the AudioContext if we are.", "try", "{", "if", "(", "typeof", "AudioContext", "!==", "'undefined'", ")", "{", "Howler", ".", "ctx", "=", "new", "AudioContext", "(", ")", ";", "}", "else", "if", "(", "typeof", "webkitAudioContext", "!==", "'undefined'", ")", "{", "Howler", ".", "ctx", "=", "new", "webkitAudioContext", "(", ")", ";", "}", "else", "{", "Howler", ".", "usingWebAudio", "=", "false", ";", "}", "}", "catch", "(", "e", ")", "{", "Howler", ".", "usingWebAudio", "=", "false", ";", "}", "// If the audio context creation still failed, set using web audio to false.", "if", "(", "!", "Howler", ".", "ctx", ")", "{", "Howler", ".", "usingWebAudio", "=", "false", ";", "}", "// Check if a webview is being used on iOS8 or earlier (rather than the browser).", "// If it is, disable Web Audio as it causes crashing.", "var", "iOS", "=", "(", "/", "iP(hone|od|ad)", "/", ".", "test", "(", "Howler", ".", "_navigator", "&&", "Howler", ".", "_navigator", ".", "platform", ")", ")", ";", "var", "appVersion", "=", "Howler", ".", "_navigator", "&&", "Howler", ".", "_navigator", ".", "appVersion", ".", "match", "(", "/", "OS (\\d+)_(\\d+)_?(\\d+)?", "/", ")", ";", "var", "version", "=", "appVersion", "?", "parseInt", "(", "appVersion", "[", "1", "]", ",", "10", ")", ":", "null", ";", "if", "(", "iOS", "&&", "version", "&&", "version", "<", "9", ")", "{", "var", "safari", "=", "/", "safari", "/", ".", "test", "(", "Howler", ".", "_navigator", "&&", "Howler", ".", "_navigator", ".", "userAgent", ".", "toLowerCase", "(", ")", ")", ";", "if", "(", "Howler", ".", "_navigator", "&&", "Howler", ".", "_navigator", ".", "standalone", "&&", "!", "safari", "||", "Howler", ".", "_navigator", "&&", "!", "Howler", ".", "_navigator", ".", "standalone", "&&", "!", "safari", ")", "{", "Howler", ".", "usingWebAudio", "=", "false", ";", "}", "}", "// Create and expose the master GainNode when using Web Audio (useful for plugins or advanced usage).", "if", "(", "Howler", ".", "usingWebAudio", ")", "{", "Howler", ".", "masterGain", "=", "(", "typeof", "Howler", ".", "ctx", ".", "createGain", "===", "'undefined'", ")", "?", "Howler", ".", "ctx", ".", "createGainNode", "(", ")", ":", "Howler", ".", "ctx", ".", "createGain", "(", ")", ";", "Howler", ".", "masterGain", ".", "gain", ".", "setValueAtTime", "(", "Howler", ".", "_muted", "?", "0", ":", "1", ",", "Howler", ".", "ctx", ".", "currentTime", ")", ";", "Howler", ".", "masterGain", ".", "connect", "(", "Howler", ".", "ctx", ".", "destination", ")", ";", "}", "// Re-run the setup on Howler.", "Howler", ".", "_setup", "(", ")", ";", "}" ]
Setup the audio context when available, or switch to HTML5 Audio mode.
[ "Setup", "the", "audio", "context", "when", "available", "or", "switch", "to", "HTML5", "Audio", "mode", "." ]
030db918dd8ce640afd57e172418472497e8f113
https://github.com/goldfire/howler.js/blob/030db918dd8ce640afd57e172418472497e8f113/dist/howler.js#L2423-L2468
1,496
goldfire/howler.js
examples/3d/js/player.js
function(x, y, dir, speed) { this.x = x; this.y = y; this.dir = dir; this.speed = speed || 3; this.steps = 0; this.hand = new Texture('./assets/gun.png', 512, 360); // Update the position of the audio listener. Howler.pos(this.x, this.y, -0.5); // Update the direction and orientation. this.rotate(dir); }
javascript
function(x, y, dir, speed) { this.x = x; this.y = y; this.dir = dir; this.speed = speed || 3; this.steps = 0; this.hand = new Texture('./assets/gun.png', 512, 360); // Update the position of the audio listener. Howler.pos(this.x, this.y, -0.5); // Update the direction and orientation. this.rotate(dir); }
[ "function", "(", "x", ",", "y", ",", "dir", ",", "speed", ")", "{", "this", ".", "x", "=", "x", ";", "this", ".", "y", "=", "y", ";", "this", ".", "dir", "=", "dir", ";", "this", ".", "speed", "=", "speed", "||", "3", ";", "this", ".", "steps", "=", "0", ";", "this", ".", "hand", "=", "new", "Texture", "(", "'./assets/gun.png'", ",", "512", ",", "360", ")", ";", "// Update the position of the audio listener.", "Howler", ".", "pos", "(", "this", ".", "x", ",", "this", ".", "y", ",", "-", "0.5", ")", ";", "// Update the direction and orientation.", "this", ".", "rotate", "(", "dir", ")", ";", "}" ]
The player from which we cast the rays. @param {Number} x Starting x-position. @param {Number} y Starting y-position. @param {Number} dir Direction they are facing in radians. @param {Number} speed Speed they walk at.
[ "The", "player", "from", "which", "we", "cast", "the", "rays", "." ]
030db918dd8ce640afd57e172418472497e8f113
https://github.com/goldfire/howler.js/blob/030db918dd8ce640afd57e172418472497e8f113/examples/3d/js/player.js#L20-L33
1,497
goldfire/howler.js
examples/3d/js/player.js
function(angle) { this.dir = (this.dir + angle + circle) % circle; // Calculate the rotation vector and update the orientation of the listener. var x = Math.cos(this.dir); var y = 0; var z = Math.sin(this.dir); Howler.orientation(x, y, z, 0, 1, 0); }
javascript
function(angle) { this.dir = (this.dir + angle + circle) % circle; // Calculate the rotation vector and update the orientation of the listener. var x = Math.cos(this.dir); var y = 0; var z = Math.sin(this.dir); Howler.orientation(x, y, z, 0, 1, 0); }
[ "function", "(", "angle", ")", "{", "this", ".", "dir", "=", "(", "this", ".", "dir", "+", "angle", "+", "circle", ")", "%", "circle", ";", "// Calculate the rotation vector and update the orientation of the listener.", "var", "x", "=", "Math", ".", "cos", "(", "this", ".", "dir", ")", ";", "var", "y", "=", "0", ";", "var", "z", "=", "Math", ".", "sin", "(", "this", ".", "dir", ")", ";", "Howler", ".", "orientation", "(", "x", ",", "y", ",", "z", ",", "0", ",", "1", ",", "0", ")", ";", "}" ]
Rotate the player's viewing direction. @param {Number} angle Angle to rotate by.
[ "Rotate", "the", "player", "s", "viewing", "direction", "." ]
030db918dd8ce640afd57e172418472497e8f113
https://github.com/goldfire/howler.js/blob/030db918dd8ce640afd57e172418472497e8f113/examples/3d/js/player.js#L39-L47
1,498
goldfire/howler.js
examples/3d/js/player.js
function(dist) { var dx = Math.cos(this.dir) * dist; var dy = Math.sin(this.dir) * dist; // Move the player if they can walk here. this.x += (game.map.check(this.x + dx, this.y) <= 0) ? dx : 0; this.y += (game.map.check(this.x, this.y + dy) <= 0) ? dy : 0; this.steps += dist; // Update the position of the audio listener. Howler.pos(this.x, this.y, -0.5); }
javascript
function(dist) { var dx = Math.cos(this.dir) * dist; var dy = Math.sin(this.dir) * dist; // Move the player if they can walk here. this.x += (game.map.check(this.x + dx, this.y) <= 0) ? dx : 0; this.y += (game.map.check(this.x, this.y + dy) <= 0) ? dy : 0; this.steps += dist; // Update the position of the audio listener. Howler.pos(this.x, this.y, -0.5); }
[ "function", "(", "dist", ")", "{", "var", "dx", "=", "Math", ".", "cos", "(", "this", ".", "dir", ")", "*", "dist", ";", "var", "dy", "=", "Math", ".", "sin", "(", "this", ".", "dir", ")", "*", "dist", ";", "// Move the player if they can walk here.", "this", ".", "x", "+=", "(", "game", ".", "map", ".", "check", "(", "this", ".", "x", "+", "dx", ",", "this", ".", "y", ")", "<=", "0", ")", "?", "dx", ":", "0", ";", "this", ".", "y", "+=", "(", "game", ".", "map", ".", "check", "(", "this", ".", "x", ",", "this", ".", "y", "+", "dy", ")", "<=", "0", ")", "?", "dy", ":", "0", ";", "this", ".", "steps", "+=", "dist", ";", "// Update the position of the audio listener.", "Howler", ".", "pos", "(", "this", ".", "x", ",", "this", ".", "y", ",", "-", "0.5", ")", ";", "}" ]
Handle walking based on the state of inputs. @param {Number} dist Distance to walk based on time elapsed.
[ "Handle", "walking", "based", "on", "the", "state", "of", "inputs", "." ]
030db918dd8ce640afd57e172418472497e8f113
https://github.com/goldfire/howler.js/blob/030db918dd8ce640afd57e172418472497e8f113/examples/3d/js/player.js#L53-L65
1,499
goldfire/howler.js
examples/3d/js/player.js
function(secs) { var states = game.controls.states; if (states.left) this.rotate(-Math.PI * secs); if (states.right) this.rotate(Math.PI * secs); if (states.front) this.walk(this.speed * secs); if (states.back) this.walk(-this.speed * secs); }
javascript
function(secs) { var states = game.controls.states; if (states.left) this.rotate(-Math.PI * secs); if (states.right) this.rotate(Math.PI * secs); if (states.front) this.walk(this.speed * secs); if (states.back) this.walk(-this.speed * secs); }
[ "function", "(", "secs", ")", "{", "var", "states", "=", "game", ".", "controls", ".", "states", ";", "if", "(", "states", ".", "left", ")", "this", ".", "rotate", "(", "-", "Math", ".", "PI", "*", "secs", ")", ";", "if", "(", "states", ".", "right", ")", "this", ".", "rotate", "(", "Math", ".", "PI", "*", "secs", ")", ";", "if", "(", "states", ".", "front", ")", "this", ".", "walk", "(", "this", ".", "speed", "*", "secs", ")", ";", "if", "(", "states", ".", "back", ")", "this", ".", "walk", "(", "-", "this", ".", "speed", "*", "secs", ")", ";", "}" ]
Update the player position and rotation on each tick. @param {Number} secs Seconds since last update.
[ "Update", "the", "player", "position", "and", "rotation", "on", "each", "tick", "." ]
030db918dd8ce640afd57e172418472497e8f113
https://github.com/goldfire/howler.js/blob/030db918dd8ce640afd57e172418472497e8f113/examples/3d/js/player.js#L71-L78