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
list
docstring
stringlengths
4
11.8k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
86
226
22,100
gerhardberger/electron-pdf-window
pdfjs/web/viewer.js
function () { return this._pages.map(function (pageView) { var viewport = pageView.pdfPage.getViewport(1); return { width: viewport.width, height: viewport.height }; }); }
javascript
function () { return this._pages.map(function (pageView) { var viewport = pageView.pdfPage.getViewport(1); return { width: viewport.width, height: viewport.height }; }); }
[ "function", "(", ")", "{", "return", "this", ".", "_pages", ".", "map", "(", "function", "(", "pageView", ")", "{", "var", "viewport", "=", "pageView", ".", "pdfPage", ".", "getViewport", "(", "1", ")", ";", "return", "{", "width", ":", "viewport", ".", "width", ",", "height", ":", "viewport", ".", "height", "}", ";", "}", ")", ";", "}" ]
Returns sizes of the pages. @returns {Array} Array of objects with width/height fields.
[ "Returns", "sizes", "of", "the", "pages", "." ]
61fc00ab545ee5170f9832aaa37dedb542d3b3e8
https://github.com/gerhardberger/electron-pdf-window/blob/61fc00ab545ee5170f9832aaa37dedb542d3b3e8/pdfjs/web/viewer.js#L6435-L6443
22,101
gerhardberger/electron-pdf-window
pdfjs/web/viewer.js
pdfViewClose
function pdfViewClose() { var errorWrapper = this.appConfig.errorWrapper.container; errorWrapper.setAttribute('hidden', 'true'); if (!this.pdfLoadingTask) { return Promise.resolve(); } var promise = this.pdfLoadingTask.destroy(); this.pdfLoadingTask = null; if (this.pdfDocument) { this.pdfDocument = null; this.pdfThumbnailViewer.setDocument(null); this.pdfViewer.setDocument(null); this.pdfLinkService.setDocument(null, null); } this.store = null; this.isInitialViewSet = false; this.pdfSidebar.reset(); this.pdfOutlineViewer.reset(); this.pdfAttachmentViewer.reset(); this.findController.reset(); this.findBar.reset(); if (typeof PDFBug !== 'undefined') { PDFBug.cleanup(); } return promise; }
javascript
function pdfViewClose() { var errorWrapper = this.appConfig.errorWrapper.container; errorWrapper.setAttribute('hidden', 'true'); if (!this.pdfLoadingTask) { return Promise.resolve(); } var promise = this.pdfLoadingTask.destroy(); this.pdfLoadingTask = null; if (this.pdfDocument) { this.pdfDocument = null; this.pdfThumbnailViewer.setDocument(null); this.pdfViewer.setDocument(null); this.pdfLinkService.setDocument(null, null); } this.store = null; this.isInitialViewSet = false; this.pdfSidebar.reset(); this.pdfOutlineViewer.reset(); this.pdfAttachmentViewer.reset(); this.findController.reset(); this.findBar.reset(); if (typeof PDFBug !== 'undefined') { PDFBug.cleanup(); } return promise; }
[ "function", "pdfViewClose", "(", ")", "{", "var", "errorWrapper", "=", "this", ".", "appConfig", ".", "errorWrapper", ".", "container", ";", "errorWrapper", ".", "setAttribute", "(", "'hidden'", ",", "'true'", ")", ";", "if", "(", "!", "this", ".", "pdfLoadingTask", ")", "{", "return", "Promise", ".", "resolve", "(", ")", ";", "}", "var", "promise", "=", "this", ".", "pdfLoadingTask", ".", "destroy", "(", ")", ";", "this", ".", "pdfLoadingTask", "=", "null", ";", "if", "(", "this", ".", "pdfDocument", ")", "{", "this", ".", "pdfDocument", "=", "null", ";", "this", ".", "pdfThumbnailViewer", ".", "setDocument", "(", "null", ")", ";", "this", ".", "pdfViewer", ".", "setDocument", "(", "null", ")", ";", "this", ".", "pdfLinkService", ".", "setDocument", "(", "null", ",", "null", ")", ";", "}", "this", ".", "store", "=", "null", ";", "this", ".", "isInitialViewSet", "=", "false", ";", "this", ".", "pdfSidebar", ".", "reset", "(", ")", ";", "this", ".", "pdfOutlineViewer", ".", "reset", "(", ")", ";", "this", ".", "pdfAttachmentViewer", ".", "reset", "(", ")", ";", "this", ".", "findController", ".", "reset", "(", ")", ";", "this", ".", "findBar", ".", "reset", "(", ")", ";", "if", "(", "typeof", "PDFBug", "!==", "'undefined'", ")", "{", "PDFBug", ".", "cleanup", "(", ")", ";", "}", "return", "promise", ";", "}" ]
Closes opened PDF document. @returns {Promise} - Returns the promise, which is resolved when all destruction is completed.
[ "Closes", "opened", "PDF", "document", "." ]
61fc00ab545ee5170f9832aaa37dedb542d3b3e8
https://github.com/gerhardberger/electron-pdf-window/blob/61fc00ab545ee5170f9832aaa37dedb542d3b3e8/pdfjs/web/viewer.js#L6835-L6860
22,102
gerhardberger/electron-pdf-window
pdfjs/web/viewer.js
pdfViewOpen
function pdfViewOpen(file, args) { if (arguments.length > 2 || typeof args === 'number') { return Promise.reject(new Error('Call of open() with obsolete signature.')); } if (this.pdfLoadingTask) { // We need to destroy already opened document. return this.close().then(function () { // Reload the preferences if a document was previously opened. Preferences.reload(); // ... and repeat the open() call. return this.open(file, args); }.bind(this)); } var parameters = Object.create(null), scale; if (typeof file === 'string') { // URL this.setTitleUsingUrl(file); parameters.url = file; } else if (file && 'byteLength' in file) { // ArrayBuffer parameters.data = file; } else if (file.url && file.originalUrl) { this.setTitleUsingUrl(file.originalUrl); parameters.url = file.url; } if (args) { for (var prop in args) { parameters[prop] = args[prop]; } if (args.scale) { scale = args.scale; } if (args.length) { this.pdfDocumentProperties.setFileSize(args.length); } } var self = this; self.downloadComplete = false; var loadingTask = pdfjsLib.getDocument(parameters); this.pdfLoadingTask = loadingTask; loadingTask.onPassword = function passwordNeeded(updateCallback, reason) { self.passwordPrompt.setUpdateCallback(updateCallback, reason); self.passwordPrompt.open(); }; loadingTask.onProgress = function getDocumentProgress(progressData) { self.progress(progressData.loaded / progressData.total); }; // Listen for unsupported features to trigger the fallback UI. loadingTask.onUnsupportedFeature = this.fallback.bind(this); return loadingTask.promise.then(function getDocumentCallback(pdfDocument) { self.load(pdfDocument, scale); }, function getDocumentError(exception) { var message = exception && exception.message; var loadingErrorMessage = mozL10n.get('loading_error', null, 'An error occurred while loading the PDF.'); if (exception instanceof pdfjsLib.InvalidPDFException) { // change error message also for other builds loadingErrorMessage = mozL10n.get('invalid_file_error', null, 'Invalid or corrupted PDF file.'); } else if (exception instanceof pdfjsLib.MissingPDFException) { // special message for missing PDF's loadingErrorMessage = mozL10n.get('missing_file_error', null, 'Missing PDF file.'); } else if (exception instanceof pdfjsLib.UnexpectedResponseException) { loadingErrorMessage = mozL10n.get('unexpected_response_error', null, 'Unexpected server response.'); } var moreInfo = { message: message }; self.error(loadingErrorMessage, moreInfo); throw new Error(loadingErrorMessage); }); }
javascript
function pdfViewOpen(file, args) { if (arguments.length > 2 || typeof args === 'number') { return Promise.reject(new Error('Call of open() with obsolete signature.')); } if (this.pdfLoadingTask) { // We need to destroy already opened document. return this.close().then(function () { // Reload the preferences if a document was previously opened. Preferences.reload(); // ... and repeat the open() call. return this.open(file, args); }.bind(this)); } var parameters = Object.create(null), scale; if (typeof file === 'string') { // URL this.setTitleUsingUrl(file); parameters.url = file; } else if (file && 'byteLength' in file) { // ArrayBuffer parameters.data = file; } else if (file.url && file.originalUrl) { this.setTitleUsingUrl(file.originalUrl); parameters.url = file.url; } if (args) { for (var prop in args) { parameters[prop] = args[prop]; } if (args.scale) { scale = args.scale; } if (args.length) { this.pdfDocumentProperties.setFileSize(args.length); } } var self = this; self.downloadComplete = false; var loadingTask = pdfjsLib.getDocument(parameters); this.pdfLoadingTask = loadingTask; loadingTask.onPassword = function passwordNeeded(updateCallback, reason) { self.passwordPrompt.setUpdateCallback(updateCallback, reason); self.passwordPrompt.open(); }; loadingTask.onProgress = function getDocumentProgress(progressData) { self.progress(progressData.loaded / progressData.total); }; // Listen for unsupported features to trigger the fallback UI. loadingTask.onUnsupportedFeature = this.fallback.bind(this); return loadingTask.promise.then(function getDocumentCallback(pdfDocument) { self.load(pdfDocument, scale); }, function getDocumentError(exception) { var message = exception && exception.message; var loadingErrorMessage = mozL10n.get('loading_error', null, 'An error occurred while loading the PDF.'); if (exception instanceof pdfjsLib.InvalidPDFException) { // change error message also for other builds loadingErrorMessage = mozL10n.get('invalid_file_error', null, 'Invalid or corrupted PDF file.'); } else if (exception instanceof pdfjsLib.MissingPDFException) { // special message for missing PDF's loadingErrorMessage = mozL10n.get('missing_file_error', null, 'Missing PDF file.'); } else if (exception instanceof pdfjsLib.UnexpectedResponseException) { loadingErrorMessage = mozL10n.get('unexpected_response_error', null, 'Unexpected server response.'); } var moreInfo = { message: message }; self.error(loadingErrorMessage, moreInfo); throw new Error(loadingErrorMessage); }); }
[ "function", "pdfViewOpen", "(", "file", ",", "args", ")", "{", "if", "(", "arguments", ".", "length", ">", "2", "||", "typeof", "args", "===", "'number'", ")", "{", "return", "Promise", ".", "reject", "(", "new", "Error", "(", "'Call of open() with obsolete signature.'", ")", ")", ";", "}", "if", "(", "this", ".", "pdfLoadingTask", ")", "{", "// We need to destroy already opened document.", "return", "this", ".", "close", "(", ")", ".", "then", "(", "function", "(", ")", "{", "// Reload the preferences if a document was previously opened.", "Preferences", ".", "reload", "(", ")", ";", "// ... and repeat the open() call.", "return", "this", ".", "open", "(", "file", ",", "args", ")", ";", "}", ".", "bind", "(", "this", ")", ")", ";", "}", "var", "parameters", "=", "Object", ".", "create", "(", "null", ")", ",", "scale", ";", "if", "(", "typeof", "file", "===", "'string'", ")", "{", "// URL", "this", ".", "setTitleUsingUrl", "(", "file", ")", ";", "parameters", ".", "url", "=", "file", ";", "}", "else", "if", "(", "file", "&&", "'byteLength'", "in", "file", ")", "{", "// ArrayBuffer", "parameters", ".", "data", "=", "file", ";", "}", "else", "if", "(", "file", ".", "url", "&&", "file", ".", "originalUrl", ")", "{", "this", ".", "setTitleUsingUrl", "(", "file", ".", "originalUrl", ")", ";", "parameters", ".", "url", "=", "file", ".", "url", ";", "}", "if", "(", "args", ")", "{", "for", "(", "var", "prop", "in", "args", ")", "{", "parameters", "[", "prop", "]", "=", "args", "[", "prop", "]", ";", "}", "if", "(", "args", ".", "scale", ")", "{", "scale", "=", "args", ".", "scale", ";", "}", "if", "(", "args", ".", "length", ")", "{", "this", ".", "pdfDocumentProperties", ".", "setFileSize", "(", "args", ".", "length", ")", ";", "}", "}", "var", "self", "=", "this", ";", "self", ".", "downloadComplete", "=", "false", ";", "var", "loadingTask", "=", "pdfjsLib", ".", "getDocument", "(", "parameters", ")", ";", "this", ".", "pdfLoadingTask", "=", "loadingTask", ";", "loadingTask", ".", "onPassword", "=", "function", "passwordNeeded", "(", "updateCallback", ",", "reason", ")", "{", "self", ".", "passwordPrompt", ".", "setUpdateCallback", "(", "updateCallback", ",", "reason", ")", ";", "self", ".", "passwordPrompt", ".", "open", "(", ")", ";", "}", ";", "loadingTask", ".", "onProgress", "=", "function", "getDocumentProgress", "(", "progressData", ")", "{", "self", ".", "progress", "(", "progressData", ".", "loaded", "/", "progressData", ".", "total", ")", ";", "}", ";", "// Listen for unsupported features to trigger the fallback UI.", "loadingTask", ".", "onUnsupportedFeature", "=", "this", ".", "fallback", ".", "bind", "(", "this", ")", ";", "return", "loadingTask", ".", "promise", ".", "then", "(", "function", "getDocumentCallback", "(", "pdfDocument", ")", "{", "self", ".", "load", "(", "pdfDocument", ",", "scale", ")", ";", "}", ",", "function", "getDocumentError", "(", "exception", ")", "{", "var", "message", "=", "exception", "&&", "exception", ".", "message", ";", "var", "loadingErrorMessage", "=", "mozL10n", ".", "get", "(", "'loading_error'", ",", "null", ",", "'An error occurred while loading the PDF.'", ")", ";", "if", "(", "exception", "instanceof", "pdfjsLib", ".", "InvalidPDFException", ")", "{", "// change error message also for other builds", "loadingErrorMessage", "=", "mozL10n", ".", "get", "(", "'invalid_file_error'", ",", "null", ",", "'Invalid or corrupted PDF file.'", ")", ";", "}", "else", "if", "(", "exception", "instanceof", "pdfjsLib", ".", "MissingPDFException", ")", "{", "// special message for missing PDF's", "loadingErrorMessage", "=", "mozL10n", ".", "get", "(", "'missing_file_error'", ",", "null", ",", "'Missing PDF file.'", ")", ";", "}", "else", "if", "(", "exception", "instanceof", "pdfjsLib", ".", "UnexpectedResponseException", ")", "{", "loadingErrorMessage", "=", "mozL10n", ".", "get", "(", "'unexpected_response_error'", ",", "null", ",", "'Unexpected server response.'", ")", ";", "}", "var", "moreInfo", "=", "{", "message", ":", "message", "}", ";", "self", ".", "error", "(", "loadingErrorMessage", ",", "moreInfo", ")", ";", "throw", "new", "Error", "(", "loadingErrorMessage", ")", ";", "}", ")", ";", "}" ]
Opens PDF document specified by URL or array with additional arguments. @param {string|TypedArray|ArrayBuffer} file - PDF location or binary data. @param {Object} args - (optional) Additional arguments for the getDocument call, e.g. HTTP headers ('httpHeaders') or alternative data transport ('range'). @returns {Promise} - Returns the promise, which is resolved when document is opened.
[ "Opens", "PDF", "document", "specified", "by", "URL", "or", "array", "with", "additional", "arguments", "." ]
61fc00ab545ee5170f9832aaa37dedb542d3b3e8
https://github.com/gerhardberger/electron-pdf-window/blob/61fc00ab545ee5170f9832aaa37dedb542d3b3e8/pdfjs/web/viewer.js#L6870-L6937
22,103
gerhardberger/electron-pdf-window
pdfjs/web/viewer.js
pdfViewError
function pdfViewError(message, moreInfo) { var moreInfoText = mozL10n.get('error_version_info', { version: pdfjsLib.version || '?', build: pdfjsLib.build || '?' }, 'PDF.js v{{version}} (build: {{build}})') + '\n'; if (moreInfo) { moreInfoText += mozL10n.get('error_message', { message: moreInfo.message }, 'Message: {{message}}'); if (moreInfo.stack) { moreInfoText += '\n' + mozL10n.get('error_stack', { stack: moreInfo.stack }, 'Stack: {{stack}}'); } else { if (moreInfo.filename) { moreInfoText += '\n' + mozL10n.get('error_file', { file: moreInfo.filename }, 'File: {{file}}'); } if (moreInfo.lineNumber) { moreInfoText += '\n' + mozL10n.get('error_line', { line: moreInfo.lineNumber }, 'Line: {{line}}'); } } } var errorWrapperConfig = this.appConfig.errorWrapper; var errorWrapper = errorWrapperConfig.container; errorWrapper.removeAttribute('hidden'); var errorMessage = errorWrapperConfig.errorMessage; errorMessage.textContent = message; var closeButton = errorWrapperConfig.closeButton; closeButton.onclick = function () { errorWrapper.setAttribute('hidden', 'true'); }; var errorMoreInfo = errorWrapperConfig.errorMoreInfo; var moreInfoButton = errorWrapperConfig.moreInfoButton; var lessInfoButton = errorWrapperConfig.lessInfoButton; moreInfoButton.onclick = function () { errorMoreInfo.removeAttribute('hidden'); moreInfoButton.setAttribute('hidden', 'true'); lessInfoButton.removeAttribute('hidden'); errorMoreInfo.style.height = errorMoreInfo.scrollHeight + 'px'; }; lessInfoButton.onclick = function () { errorMoreInfo.setAttribute('hidden', 'true'); moreInfoButton.removeAttribute('hidden'); lessInfoButton.setAttribute('hidden', 'true'); }; moreInfoButton.oncontextmenu = noContextMenuHandler; lessInfoButton.oncontextmenu = noContextMenuHandler; closeButton.oncontextmenu = noContextMenuHandler; moreInfoButton.removeAttribute('hidden'); lessInfoButton.setAttribute('hidden', 'true'); errorMoreInfo.value = moreInfoText; }
javascript
function pdfViewError(message, moreInfo) { var moreInfoText = mozL10n.get('error_version_info', { version: pdfjsLib.version || '?', build: pdfjsLib.build || '?' }, 'PDF.js v{{version}} (build: {{build}})') + '\n'; if (moreInfo) { moreInfoText += mozL10n.get('error_message', { message: moreInfo.message }, 'Message: {{message}}'); if (moreInfo.stack) { moreInfoText += '\n' + mozL10n.get('error_stack', { stack: moreInfo.stack }, 'Stack: {{stack}}'); } else { if (moreInfo.filename) { moreInfoText += '\n' + mozL10n.get('error_file', { file: moreInfo.filename }, 'File: {{file}}'); } if (moreInfo.lineNumber) { moreInfoText += '\n' + mozL10n.get('error_line', { line: moreInfo.lineNumber }, 'Line: {{line}}'); } } } var errorWrapperConfig = this.appConfig.errorWrapper; var errorWrapper = errorWrapperConfig.container; errorWrapper.removeAttribute('hidden'); var errorMessage = errorWrapperConfig.errorMessage; errorMessage.textContent = message; var closeButton = errorWrapperConfig.closeButton; closeButton.onclick = function () { errorWrapper.setAttribute('hidden', 'true'); }; var errorMoreInfo = errorWrapperConfig.errorMoreInfo; var moreInfoButton = errorWrapperConfig.moreInfoButton; var lessInfoButton = errorWrapperConfig.lessInfoButton; moreInfoButton.onclick = function () { errorMoreInfo.removeAttribute('hidden'); moreInfoButton.setAttribute('hidden', 'true'); lessInfoButton.removeAttribute('hidden'); errorMoreInfo.style.height = errorMoreInfo.scrollHeight + 'px'; }; lessInfoButton.onclick = function () { errorMoreInfo.setAttribute('hidden', 'true'); moreInfoButton.removeAttribute('hidden'); lessInfoButton.setAttribute('hidden', 'true'); }; moreInfoButton.oncontextmenu = noContextMenuHandler; lessInfoButton.oncontextmenu = noContextMenuHandler; closeButton.oncontextmenu = noContextMenuHandler; moreInfoButton.removeAttribute('hidden'); lessInfoButton.setAttribute('hidden', 'true'); errorMoreInfo.value = moreInfoText; }
[ "function", "pdfViewError", "(", "message", ",", "moreInfo", ")", "{", "var", "moreInfoText", "=", "mozL10n", ".", "get", "(", "'error_version_info'", ",", "{", "version", ":", "pdfjsLib", ".", "version", "||", "'?'", ",", "build", ":", "pdfjsLib", ".", "build", "||", "'?'", "}", ",", "'PDF.js v{{version}} (build: {{build}})'", ")", "+", "'\\n'", ";", "if", "(", "moreInfo", ")", "{", "moreInfoText", "+=", "mozL10n", ".", "get", "(", "'error_message'", ",", "{", "message", ":", "moreInfo", ".", "message", "}", ",", "'Message: {{message}}'", ")", ";", "if", "(", "moreInfo", ".", "stack", ")", "{", "moreInfoText", "+=", "'\\n'", "+", "mozL10n", ".", "get", "(", "'error_stack'", ",", "{", "stack", ":", "moreInfo", ".", "stack", "}", ",", "'Stack: {{stack}}'", ")", ";", "}", "else", "{", "if", "(", "moreInfo", ".", "filename", ")", "{", "moreInfoText", "+=", "'\\n'", "+", "mozL10n", ".", "get", "(", "'error_file'", ",", "{", "file", ":", "moreInfo", ".", "filename", "}", ",", "'File: {{file}}'", ")", ";", "}", "if", "(", "moreInfo", ".", "lineNumber", ")", "{", "moreInfoText", "+=", "'\\n'", "+", "mozL10n", ".", "get", "(", "'error_line'", ",", "{", "line", ":", "moreInfo", ".", "lineNumber", "}", ",", "'Line: {{line}}'", ")", ";", "}", "}", "}", "var", "errorWrapperConfig", "=", "this", ".", "appConfig", ".", "errorWrapper", ";", "var", "errorWrapper", "=", "errorWrapperConfig", ".", "container", ";", "errorWrapper", ".", "removeAttribute", "(", "'hidden'", ")", ";", "var", "errorMessage", "=", "errorWrapperConfig", ".", "errorMessage", ";", "errorMessage", ".", "textContent", "=", "message", ";", "var", "closeButton", "=", "errorWrapperConfig", ".", "closeButton", ";", "closeButton", ".", "onclick", "=", "function", "(", ")", "{", "errorWrapper", ".", "setAttribute", "(", "'hidden'", ",", "'true'", ")", ";", "}", ";", "var", "errorMoreInfo", "=", "errorWrapperConfig", ".", "errorMoreInfo", ";", "var", "moreInfoButton", "=", "errorWrapperConfig", ".", "moreInfoButton", ";", "var", "lessInfoButton", "=", "errorWrapperConfig", ".", "lessInfoButton", ";", "moreInfoButton", ".", "onclick", "=", "function", "(", ")", "{", "errorMoreInfo", ".", "removeAttribute", "(", "'hidden'", ")", ";", "moreInfoButton", ".", "setAttribute", "(", "'hidden'", ",", "'true'", ")", ";", "lessInfoButton", ".", "removeAttribute", "(", "'hidden'", ")", ";", "errorMoreInfo", ".", "style", ".", "height", "=", "errorMoreInfo", ".", "scrollHeight", "+", "'px'", ";", "}", ";", "lessInfoButton", ".", "onclick", "=", "function", "(", ")", "{", "errorMoreInfo", ".", "setAttribute", "(", "'hidden'", ",", "'true'", ")", ";", "moreInfoButton", ".", "removeAttribute", "(", "'hidden'", ")", ";", "lessInfoButton", ".", "setAttribute", "(", "'hidden'", ",", "'true'", ")", ";", "}", ";", "moreInfoButton", ".", "oncontextmenu", "=", "noContextMenuHandler", ";", "lessInfoButton", ".", "oncontextmenu", "=", "noContextMenuHandler", ";", "closeButton", ".", "oncontextmenu", "=", "noContextMenuHandler", ";", "moreInfoButton", ".", "removeAttribute", "(", "'hidden'", ")", ";", "lessInfoButton", ".", "setAttribute", "(", "'hidden'", ",", "'true'", ")", ";", "errorMoreInfo", ".", "value", "=", "moreInfoText", ";", "}" ]
Show the error box. @param {String} message A message that is human readable. @param {Object} moreInfo (optional) Further information about the error that is more technical. Should have a 'message' and optionally a 'stack' property.
[ "Show", "the", "error", "box", "." ]
61fc00ab545ee5170f9832aaa37dedb542d3b3e8
https://github.com/gerhardberger/electron-pdf-window/blob/61fc00ab545ee5170f9832aaa37dedb542d3b3e8/pdfjs/web/viewer.js#L6974-L7021
22,104
thegecko/webusb
gulpfile.js
lint
function lint() { return gulp.src(srcFiles) .pipe(gulpTslint({ program: tslint.Linter.createProgram("./tsconfig.json"), formatter: "stylish" })) .pipe(gulpTslint.report({ emitError: !watching })) }
javascript
function lint() { return gulp.src(srcFiles) .pipe(gulpTslint({ program: tslint.Linter.createProgram("./tsconfig.json"), formatter: "stylish" })) .pipe(gulpTslint.report({ emitError: !watching })) }
[ "function", "lint", "(", ")", "{", "return", "gulp", ".", "src", "(", "srcFiles", ")", ".", "pipe", "(", "gulpTslint", "(", "{", "program", ":", "tslint", ".", "Linter", ".", "createProgram", "(", "\"./tsconfig.json\"", ")", ",", "formatter", ":", "\"stylish\"", "}", ")", ")", ".", "pipe", "(", "gulpTslint", ".", "report", "(", "{", "emitError", ":", "!", "watching", "}", ")", ")", "}" ]
Lint the source
[ "Lint", "the", "source" ]
9e6e7f8872dcf5115f056f8b337b0d6aa28c952e
https://github.com/thegecko/webusb/blob/9e6e7f8872dcf5115f056f8b337b0d6aa28c952e/gulpfile.js#L41-L50
22,105
vkiryukhin/jsonfn
html/rainbow/rainbow.js
_attr
function _attr(el, attr, attrs, i) { var result = (el.getAttribute && el.getAttribute(attr)) || 0; if (!result) { attrs = el.attributes; for (i = 0; i < attrs.length; ++i) { if (attrs[i].nodeName === attr) { return attrs[i].nodeValue; } } } return result; }
javascript
function _attr(el, attr, attrs, i) { var result = (el.getAttribute && el.getAttribute(attr)) || 0; if (!result) { attrs = el.attributes; for (i = 0; i < attrs.length; ++i) { if (attrs[i].nodeName === attr) { return attrs[i].nodeValue; } } } return result; }
[ "function", "_attr", "(", "el", ",", "attr", ",", "attrs", ",", "i", ")", "{", "var", "result", "=", "(", "el", ".", "getAttribute", "&&", "el", ".", "getAttribute", "(", "attr", ")", ")", "||", "0", ";", "if", "(", "!", "result", ")", "{", "attrs", "=", "el", ".", "attributes", ";", "for", "(", "i", "=", "0", ";", "i", "<", "attrs", ".", "length", ";", "++", "i", ")", "{", "if", "(", "attrs", "[", "i", "]", ".", "nodeName", "===", "attr", ")", "{", "return", "attrs", "[", "i", "]", ".", "nodeValue", ";", "}", "}", "}", "return", "result", ";", "}" ]
cross browser get attribute for an element @see http://stackoverflow.com/questions/3755227/cross-browser-javascript-getattribute-method @param {Node} el @param {string} attr attribute you are trying to get @returns {string|number}
[ "cross", "browser", "get", "attribute", "for", "an", "element" ]
299b4beb4818f7ca98f5e01f0d2a6675b8b2e4ac
https://github.com/vkiryukhin/jsonfn/blob/299b4beb4818f7ca98f5e01f0d2a6675b8b2e4ac/html/rainbow/rainbow.js#L100-L114
22,106
vkiryukhin/jsonfn
html/rainbow/rainbow.js
_getLanguageForBlock
function _getLanguageForBlock(block) { // if this doesn't have a language but the parent does then use that // this means if for example you have: <pre data-language="php"> // with a bunch of <code> blocks inside then you do not have // to specify the language for each block var language = _attr(block, 'data-language') || _attr(block.parentNode, 'data-language'); // this adds support for specifying language via a css class // you can use the Google Code Prettify style: <pre class="lang-php"> // or the HTML5 style: <pre><code class="language-php"> if (!language) { var pattern = /\blang(?:uage)?-(\w+)/, match = block.className.match(pattern) || block.parentNode.className.match(pattern); if (match) { language = match[1]; } } return language; }
javascript
function _getLanguageForBlock(block) { // if this doesn't have a language but the parent does then use that // this means if for example you have: <pre data-language="php"> // with a bunch of <code> blocks inside then you do not have // to specify the language for each block var language = _attr(block, 'data-language') || _attr(block.parentNode, 'data-language'); // this adds support for specifying language via a css class // you can use the Google Code Prettify style: <pre class="lang-php"> // or the HTML5 style: <pre><code class="language-php"> if (!language) { var pattern = /\blang(?:uage)?-(\w+)/, match = block.className.match(pattern) || block.parentNode.className.match(pattern); if (match) { language = match[1]; } } return language; }
[ "function", "_getLanguageForBlock", "(", "block", ")", "{", "// if this doesn't have a language but the parent does then use that", "// this means if for example you have: <pre data-language=\"php\">", "// with a bunch of <code> blocks inside then you do not have", "// to specify the language for each block", "var", "language", "=", "_attr", "(", "block", ",", "'data-language'", ")", "||", "_attr", "(", "block", ".", "parentNode", ",", "'data-language'", ")", ";", "// this adds support for specifying language via a css class", "// you can use the Google Code Prettify style: <pre class=\"lang-php\">", "// or the HTML5 style: <pre><code class=\"language-php\">", "if", "(", "!", "language", ")", "{", "var", "pattern", "=", "/", "\\blang(?:uage)?-(\\w+)", "/", ",", "match", "=", "block", ".", "className", ".", "match", "(", "pattern", ")", "||", "block", ".", "parentNode", ".", "className", ".", "match", "(", "pattern", ")", ";", "if", "(", "match", ")", "{", "language", "=", "match", "[", "1", "]", ";", "}", "}", "return", "language", ";", "}" ]
gets the language for this block of code @param {Element} block @returns {string|null}
[ "gets", "the", "language", "for", "this", "block", "of", "code" ]
299b4beb4818f7ca98f5e01f0d2a6675b8b2e4ac
https://github.com/vkiryukhin/jsonfn/blob/299b4beb4818f7ca98f5e01f0d2a6675b8b2e4ac/html/rainbow/rainbow.js#L144-L165
22,107
vkiryukhin/jsonfn
html/rainbow/rainbow.js
_intersects
function _intersects(start1, end1, start2, end2) { if (start2 >= start1 && start2 < end1) { return true; } return end2 > start1 && end2 < end1; }
javascript
function _intersects(start1, end1, start2, end2) { if (start2 >= start1 && start2 < end1) { return true; } return end2 > start1 && end2 < end1; }
[ "function", "_intersects", "(", "start1", ",", "end1", ",", "start2", ",", "end2", ")", "{", "if", "(", "start2", ">=", "start1", "&&", "start2", "<", "end1", ")", "{", "return", "true", ";", "}", "return", "end2", ">", "start1", "&&", "end2", "<", "end1", ";", "}" ]
determines if a new match intersects with an existing one @param {number} start1 start position of existing match @param {number} end1 end position of existing match @param {number} start2 start position of new match @param {number} end2 end position of new match @returns {boolean}
[ "determines", "if", "a", "new", "match", "intersects", "with", "an", "existing", "one" ]
299b4beb4818f7ca98f5e01f0d2a6675b8b2e4ac
https://github.com/vkiryukhin/jsonfn/blob/299b4beb4818f7ca98f5e01f0d2a6675b8b2e4ac/html/rainbow/rainbow.js#L186-L192
22,108
vkiryukhin/jsonfn
html/rainbow/rainbow.js
_hasCompleteOverlap
function _hasCompleteOverlap(start1, end1, start2, end2) { // if the starting and end positions are exactly the same // then the first one should stay and this one should be ignored if (start2 == start1 && end2 == end1) { return false; } return start2 <= start1 && end2 >= end1; }
javascript
function _hasCompleteOverlap(start1, end1, start2, end2) { // if the starting and end positions are exactly the same // then the first one should stay and this one should be ignored if (start2 == start1 && end2 == end1) { return false; } return start2 <= start1 && end2 >= end1; }
[ "function", "_hasCompleteOverlap", "(", "start1", ",", "end1", ",", "start2", ",", "end2", ")", "{", "// if the starting and end positions are exactly the same", "// then the first one should stay and this one should be ignored", "if", "(", "start2", "==", "start1", "&&", "end2", "==", "end1", ")", "{", "return", "false", ";", "}", "return", "start2", "<=", "start1", "&&", "end2", ">=", "end1", ";", "}" ]
determines if two different matches have complete overlap with each other @param {number} start1 start position of existing match @param {number} end1 end position of existing match @param {number} start2 start position of new match @param {number} end2 end position of new match @returns {boolean}
[ "determines", "if", "two", "different", "matches", "have", "complete", "overlap", "with", "each", "other" ]
299b4beb4818f7ca98f5e01f0d2a6675b8b2e4ac
https://github.com/vkiryukhin/jsonfn/blob/299b4beb4818f7ca98f5e01f0d2a6675b8b2e4ac/html/rainbow/rainbow.js#L203-L212
22,109
vkiryukhin/jsonfn
html/rainbow/rainbow.js
_matchIsInsideOtherMatch
function _matchIsInsideOtherMatch(start, end) { for (var key in replacement_positions[CURRENT_LEVEL]) { key = parseInt(key, 10); // if this block completely overlaps with another block // then we should remove the other block and return false if (_hasCompleteOverlap(key, replacement_positions[CURRENT_LEVEL][key], start, end)) { delete replacement_positions[CURRENT_LEVEL][key]; delete replacements[CURRENT_LEVEL][key]; } if (_intersects(key, replacement_positions[CURRENT_LEVEL][key], start, end)) { return true; } } return false; }
javascript
function _matchIsInsideOtherMatch(start, end) { for (var key in replacement_positions[CURRENT_LEVEL]) { key = parseInt(key, 10); // if this block completely overlaps with another block // then we should remove the other block and return false if (_hasCompleteOverlap(key, replacement_positions[CURRENT_LEVEL][key], start, end)) { delete replacement_positions[CURRENT_LEVEL][key]; delete replacements[CURRENT_LEVEL][key]; } if (_intersects(key, replacement_positions[CURRENT_LEVEL][key], start, end)) { return true; } } return false; }
[ "function", "_matchIsInsideOtherMatch", "(", "start", ",", "end", ")", "{", "for", "(", "var", "key", "in", "replacement_positions", "[", "CURRENT_LEVEL", "]", ")", "{", "key", "=", "parseInt", "(", "key", ",", "10", ")", ";", "// if this block completely overlaps with another block", "// then we should remove the other block and return false", "if", "(", "_hasCompleteOverlap", "(", "key", ",", "replacement_positions", "[", "CURRENT_LEVEL", "]", "[", "key", "]", ",", "start", ",", "end", ")", ")", "{", "delete", "replacement_positions", "[", "CURRENT_LEVEL", "]", "[", "key", "]", ";", "delete", "replacements", "[", "CURRENT_LEVEL", "]", "[", "key", "]", ";", "}", "if", "(", "_intersects", "(", "key", ",", "replacement_positions", "[", "CURRENT_LEVEL", "]", "[", "key", "]", ",", "start", ",", "end", ")", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
determines if the match passed in falls inside of an existing match this prevents a regex pattern from matching inside of a bigger pattern @param {number} start - start position of new match @param {number} end - end position of new match @returns {boolean}
[ "determines", "if", "the", "match", "passed", "in", "falls", "inside", "of", "an", "existing", "match", "this", "prevents", "a", "regex", "pattern", "from", "matching", "inside", "of", "a", "bigger", "pattern" ]
299b4beb4818f7ca98f5e01f0d2a6675b8b2e4ac
https://github.com/vkiryukhin/jsonfn/blob/299b4beb4818f7ca98f5e01f0d2a6675b8b2e4ac/html/rainbow/rainbow.js#L222-L239
22,110
vkiryukhin/jsonfn
html/rainbow/rainbow.js
_indexOfGroup
function _indexOfGroup(match, group_number) { var index = 0, i; for (i = 1; i < group_number; ++i) { if (match[i]) { index += match[i].length; } } return index; }
javascript
function _indexOfGroup(match, group_number) { var index = 0, i; for (i = 1; i < group_number; ++i) { if (match[i]) { index += match[i].length; } } return index; }
[ "function", "_indexOfGroup", "(", "match", ",", "group_number", ")", "{", "var", "index", "=", "0", ",", "i", ";", "for", "(", "i", "=", "1", ";", "i", "<", "group_number", ";", "++", "i", ")", "{", "if", "(", "match", "[", "i", "]", ")", "{", "index", "+=", "match", "[", "i", "]", ".", "length", ";", "}", "}", "return", "index", ";", "}" ]
finds out the position of group match for a regular expression @see http://stackoverflow.com/questions/1985594/how-to-find-index-of-groups-in-match @param {Object} match @param {number} group_number @returns {number}
[ "finds", "out", "the", "position", "of", "group", "match", "for", "a", "regular", "expression" ]
299b4beb4818f7ca98f5e01f0d2a6675b8b2e4ac
https://github.com/vkiryukhin/jsonfn/blob/299b4beb4818f7ca98f5e01f0d2a6675b8b2e4ac/html/rainbow/rainbow.js#L261-L272
22,111
vkiryukhin/jsonfn
html/rainbow/rainbow.js
_getPatternsForLanguage
function _getPatternsForLanguage(language) { var patterns = language_patterns[language] || [], default_patterns = language_patterns[DEFAULT_LANGUAGE] || []; return _bypassDefaultPatterns(language) ? patterns : patterns.concat(default_patterns); }
javascript
function _getPatternsForLanguage(language) { var patterns = language_patterns[language] || [], default_patterns = language_patterns[DEFAULT_LANGUAGE] || []; return _bypassDefaultPatterns(language) ? patterns : patterns.concat(default_patterns); }
[ "function", "_getPatternsForLanguage", "(", "language", ")", "{", "var", "patterns", "=", "language_patterns", "[", "language", "]", "||", "[", "]", ",", "default_patterns", "=", "language_patterns", "[", "DEFAULT_LANGUAGE", "]", "||", "[", "]", ";", "return", "_bypassDefaultPatterns", "(", "language", ")", "?", "patterns", ":", "patterns", ".", "concat", "(", "default_patterns", ")", ";", "}" ]
returns a list of regex patterns for this language @param {string} language @returns {Array}
[ "returns", "a", "list", "of", "regex", "patterns", "for", "this", "language" ]
299b4beb4818f7ca98f5e01f0d2a6675b8b2e4ac
https://github.com/vkiryukhin/jsonfn/blob/299b4beb4818f7ca98f5e01f0d2a6675b8b2e4ac/html/rainbow/rainbow.js#L471-L476
22,112
vkiryukhin/jsonfn
html/rainbow/rainbow.js
_replaceAtPosition
function _replaceAtPosition(position, replace, replace_with, code) { var sub_string = code.substr(position); return code.substr(0, position) + sub_string.replace(replace, replace_with); }
javascript
function _replaceAtPosition(position, replace, replace_with, code) { var sub_string = code.substr(position); return code.substr(0, position) + sub_string.replace(replace, replace_with); }
[ "function", "_replaceAtPosition", "(", "position", ",", "replace", ",", "replace_with", ",", "code", ")", "{", "var", "sub_string", "=", "code", ".", "substr", "(", "position", ")", ";", "return", "code", ".", "substr", "(", "0", ",", "position", ")", "+", "sub_string", ".", "replace", "(", "replace", ",", "replace_with", ")", ";", "}" ]
substring replace call to replace part of a string at a certain position @param {number} position the position where the replacement should happen @param {string} replace the text we want to replace @param {string} replace_with the text we want to replace it with @param {string} code the code we are doing the replacing in @returns {string}
[ "substring", "replace", "call", "to", "replace", "part", "of", "a", "string", "at", "a", "certain", "position" ]
299b4beb4818f7ca98f5e01f0d2a6675b8b2e4ac
https://github.com/vkiryukhin/jsonfn/blob/299b4beb4818f7ca98f5e01f0d2a6675b8b2e4ac/html/rainbow/rainbow.js#L487-L490
22,113
vkiryukhin/jsonfn
html/rainbow/rainbow.js
keys
function keys(object) { var locations = [], replacement, pos; for(var location in object) { if (object.hasOwnProperty(location)) { locations.push(location); } } // numeric descending return locations.sort(function(a, b) { return b - a; }); }
javascript
function keys(object) { var locations = [], replacement, pos; for(var location in object) { if (object.hasOwnProperty(location)) { locations.push(location); } } // numeric descending return locations.sort(function(a, b) { return b - a; }); }
[ "function", "keys", "(", "object", ")", "{", "var", "locations", "=", "[", "]", ",", "replacement", ",", "pos", ";", "for", "(", "var", "location", "in", "object", ")", "{", "if", "(", "object", ".", "hasOwnProperty", "(", "location", ")", ")", "{", "locations", ".", "push", "(", "location", ")", ";", "}", "}", "// numeric descending", "return", "locations", ".", "sort", "(", "function", "(", "a", ",", "b", ")", "{", "return", "b", "-", "a", ";", "}", ")", ";", "}" ]
sorts an object by index descending @param {Object} object @return {Array}
[ "sorts", "an", "object", "by", "index", "descending" ]
299b4beb4818f7ca98f5e01f0d2a6675b8b2e4ac
https://github.com/vkiryukhin/jsonfn/blob/299b4beb4818f7ca98f5e01f0d2a6675b8b2e4ac/html/rainbow/rainbow.js#L498-L513
22,114
vkiryukhin/jsonfn
html/rainbow/rainbow.js
_processCodeWithPatterns
function _processCodeWithPatterns(code, patterns, callback) { // we have to increase the level here so that the // replacements will not conflict with each other when // processing sub blocks of code ++CURRENT_LEVEL; // patterns are processed one at a time through this function function _workOnPatterns(patterns, i) { // still have patterns to process, keep going if (i < patterns.length) { return _processPattern(patterns[i]['pattern'], patterns[i], code, function() { _workOnPatterns(patterns, ++i); }); } // we are done processing the patterns // process the replacements and update the DOM _processReplacements(code, function(code) { // when we are done processing replacements // we are done at this level so we can go back down delete replacements[CURRENT_LEVEL]; delete replacement_positions[CURRENT_LEVEL]; --CURRENT_LEVEL; callback(code); }); } _workOnPatterns(patterns, 0); }
javascript
function _processCodeWithPatterns(code, patterns, callback) { // we have to increase the level here so that the // replacements will not conflict with each other when // processing sub blocks of code ++CURRENT_LEVEL; // patterns are processed one at a time through this function function _workOnPatterns(patterns, i) { // still have patterns to process, keep going if (i < patterns.length) { return _processPattern(patterns[i]['pattern'], patterns[i], code, function() { _workOnPatterns(patterns, ++i); }); } // we are done processing the patterns // process the replacements and update the DOM _processReplacements(code, function(code) { // when we are done processing replacements // we are done at this level so we can go back down delete replacements[CURRENT_LEVEL]; delete replacement_positions[CURRENT_LEVEL]; --CURRENT_LEVEL; callback(code); }); } _workOnPatterns(patterns, 0); }
[ "function", "_processCodeWithPatterns", "(", "code", ",", "patterns", ",", "callback", ")", "{", "// we have to increase the level here so that the", "// replacements will not conflict with each other when", "// processing sub blocks of code", "++", "CURRENT_LEVEL", ";", "// patterns are processed one at a time through this function", "function", "_workOnPatterns", "(", "patterns", ",", "i", ")", "{", "// still have patterns to process, keep going", "if", "(", "i", "<", "patterns", ".", "length", ")", "{", "return", "_processPattern", "(", "patterns", "[", "i", "]", "[", "'pattern'", "]", ",", "patterns", "[", "i", "]", ",", "code", ",", "function", "(", ")", "{", "_workOnPatterns", "(", "patterns", ",", "++", "i", ")", ";", "}", ")", ";", "}", "// we are done processing the patterns", "// process the replacements and update the DOM", "_processReplacements", "(", "code", ",", "function", "(", "code", ")", "{", "// when we are done processing replacements", "// we are done at this level so we can go back down", "delete", "replacements", "[", "CURRENT_LEVEL", "]", ";", "delete", "replacement_positions", "[", "CURRENT_LEVEL", "]", ";", "--", "CURRENT_LEVEL", ";", "callback", "(", "code", ")", ";", "}", ")", ";", "}", "_workOnPatterns", "(", "patterns", ",", "0", ")", ";", "}" ]
processes a block of code using specified patterns @param {string} code @param {Array} patterns @returns void
[ "processes", "a", "block", "of", "code", "using", "specified", "patterns" ]
299b4beb4818f7ca98f5e01f0d2a6675b8b2e4ac
https://github.com/vkiryukhin/jsonfn/blob/299b4beb4818f7ca98f5e01f0d2a6675b8b2e4ac/html/rainbow/rainbow.js#L522-L553
22,115
vkiryukhin/jsonfn
html/rainbow/rainbow.js
_processReplacements
function _processReplacements(code, onComplete) { /** * processes a single replacement * * @param {string} code * @param {Array} positions * @param {number} i * @param {Function} onComplete * @returns void */ function _processReplacement(code, positions, i, onComplete) { if (i < positions.length) { ++replacement_counter; var pos = positions[i], replacement = replacements[CURRENT_LEVEL][pos]; code = _replaceAtPosition(pos, replacement['replace'], replacement['with'], code); // process next function var next = function() { _processReplacement(code, positions, ++i, onComplete); }; // use a timeout every 250 to not freeze up the UI return replacement_counter % 250 > 0 ? next() : setTimeout(next, 0); } onComplete(code); } var string_positions = keys(replacements[CURRENT_LEVEL]); _processReplacement(code, string_positions, 0, onComplete); }
javascript
function _processReplacements(code, onComplete) { /** * processes a single replacement * * @param {string} code * @param {Array} positions * @param {number} i * @param {Function} onComplete * @returns void */ function _processReplacement(code, positions, i, onComplete) { if (i < positions.length) { ++replacement_counter; var pos = positions[i], replacement = replacements[CURRENT_LEVEL][pos]; code = _replaceAtPosition(pos, replacement['replace'], replacement['with'], code); // process next function var next = function() { _processReplacement(code, positions, ++i, onComplete); }; // use a timeout every 250 to not freeze up the UI return replacement_counter % 250 > 0 ? next() : setTimeout(next, 0); } onComplete(code); } var string_positions = keys(replacements[CURRENT_LEVEL]); _processReplacement(code, string_positions, 0, onComplete); }
[ "function", "_processReplacements", "(", "code", ",", "onComplete", ")", "{", "/**\n * processes a single replacement\n *\n * @param {string} code\n * @param {Array} positions\n * @param {number} i\n * @param {Function} onComplete\n * @returns void\n */", "function", "_processReplacement", "(", "code", ",", "positions", ",", "i", ",", "onComplete", ")", "{", "if", "(", "i", "<", "positions", ".", "length", ")", "{", "++", "replacement_counter", ";", "var", "pos", "=", "positions", "[", "i", "]", ",", "replacement", "=", "replacements", "[", "CURRENT_LEVEL", "]", "[", "pos", "]", ";", "code", "=", "_replaceAtPosition", "(", "pos", ",", "replacement", "[", "'replace'", "]", ",", "replacement", "[", "'with'", "]", ",", "code", ")", ";", "// process next function", "var", "next", "=", "function", "(", ")", "{", "_processReplacement", "(", "code", ",", "positions", ",", "++", "i", ",", "onComplete", ")", ";", "}", ";", "// use a timeout every 250 to not freeze up the UI", "return", "replacement_counter", "%", "250", ">", "0", "?", "next", "(", ")", ":", "setTimeout", "(", "next", ",", "0", ")", ";", "}", "onComplete", "(", "code", ")", ";", "}", "var", "string_positions", "=", "keys", "(", "replacements", "[", "CURRENT_LEVEL", "]", ")", ";", "_processReplacement", "(", "code", ",", "string_positions", ",", "0", ",", "onComplete", ")", ";", "}" ]
process replacements in the string of code to actually update the markup @param {string} code the code to process replacements in @param {Function} onComplete what to do when we are done processing @returns void
[ "process", "replacements", "in", "the", "string", "of", "code", "to", "actually", "update", "the", "markup" ]
299b4beb4818f7ca98f5e01f0d2a6675b8b2e4ac
https://github.com/vkiryukhin/jsonfn/blob/299b4beb4818f7ca98f5e01f0d2a6675b8b2e4ac/html/rainbow/rainbow.js#L562-L594
22,116
vkiryukhin/jsonfn
html/rainbow/rainbow.js
_highlightBlockForLanguage
function _highlightBlockForLanguage(code, language, onComplete) { var patterns = _getPatternsForLanguage(language); _processCodeWithPatterns(_htmlEntities(code), patterns, onComplete); }
javascript
function _highlightBlockForLanguage(code, language, onComplete) { var patterns = _getPatternsForLanguage(language); _processCodeWithPatterns(_htmlEntities(code), patterns, onComplete); }
[ "function", "_highlightBlockForLanguage", "(", "code", ",", "language", ",", "onComplete", ")", "{", "var", "patterns", "=", "_getPatternsForLanguage", "(", "language", ")", ";", "_processCodeWithPatterns", "(", "_htmlEntities", "(", "code", ")", ",", "patterns", ",", "onComplete", ")", ";", "}" ]
takes a string of code and highlights it according to the language specified @param {string} code @param {string} language @param {Function} onComplete @returns void
[ "takes", "a", "string", "of", "code", "and", "highlights", "it", "according", "to", "the", "language", "specified" ]
299b4beb4818f7ca98f5e01f0d2a6675b8b2e4ac
https://github.com/vkiryukhin/jsonfn/blob/299b4beb4818f7ca98f5e01f0d2a6675b8b2e4ac/html/rainbow/rainbow.js#L604-L607
22,117
vkiryukhin/jsonfn
html/rainbow/rainbow.js
_highlightCodeBlock
function _highlightCodeBlock(code_blocks, i, onComplete) { if (i < code_blocks.length) { var block = code_blocks[i], language = _getLanguageForBlock(block); if (!_hasClass(block, 'rainbow') && language) { language = language.toLowerCase(); _addClass(block, 'rainbow'); return _highlightBlockForLanguage(block.innerHTML, language, function(code) { block.innerHTML = code; // reset the replacement arrays replacements = {}; replacement_positions = {}; // if you have a listener attached tell it that this block is now highlighted if (onHighlight) { onHighlight(block, language); } // process the next block setTimeout(function() { _highlightCodeBlock(code_blocks, ++i, onComplete); }, 0); }); } return _highlightCodeBlock(code_blocks, ++i, onComplete); } if (onComplete) { onComplete(); } }
javascript
function _highlightCodeBlock(code_blocks, i, onComplete) { if (i < code_blocks.length) { var block = code_blocks[i], language = _getLanguageForBlock(block); if (!_hasClass(block, 'rainbow') && language) { language = language.toLowerCase(); _addClass(block, 'rainbow'); return _highlightBlockForLanguage(block.innerHTML, language, function(code) { block.innerHTML = code; // reset the replacement arrays replacements = {}; replacement_positions = {}; // if you have a listener attached tell it that this block is now highlighted if (onHighlight) { onHighlight(block, language); } // process the next block setTimeout(function() { _highlightCodeBlock(code_blocks, ++i, onComplete); }, 0); }); } return _highlightCodeBlock(code_blocks, ++i, onComplete); } if (onComplete) { onComplete(); } }
[ "function", "_highlightCodeBlock", "(", "code_blocks", ",", "i", ",", "onComplete", ")", "{", "if", "(", "i", "<", "code_blocks", ".", "length", ")", "{", "var", "block", "=", "code_blocks", "[", "i", "]", ",", "language", "=", "_getLanguageForBlock", "(", "block", ")", ";", "if", "(", "!", "_hasClass", "(", "block", ",", "'rainbow'", ")", "&&", "language", ")", "{", "language", "=", "language", ".", "toLowerCase", "(", ")", ";", "_addClass", "(", "block", ",", "'rainbow'", ")", ";", "return", "_highlightBlockForLanguage", "(", "block", ".", "innerHTML", ",", "language", ",", "function", "(", "code", ")", "{", "block", ".", "innerHTML", "=", "code", ";", "// reset the replacement arrays", "replacements", "=", "{", "}", ";", "replacement_positions", "=", "{", "}", ";", "// if you have a listener attached tell it that this block is now highlighted", "if", "(", "onHighlight", ")", "{", "onHighlight", "(", "block", ",", "language", ")", ";", "}", "// process the next block", "setTimeout", "(", "function", "(", ")", "{", "_highlightCodeBlock", "(", "code_blocks", ",", "++", "i", ",", "onComplete", ")", ";", "}", ",", "0", ")", ";", "}", ")", ";", "}", "return", "_highlightCodeBlock", "(", "code_blocks", ",", "++", "i", ",", "onComplete", ")", ";", "}", "if", "(", "onComplete", ")", "{", "onComplete", "(", ")", ";", "}", "}" ]
highlight an individual code block @param {Array} code_blocks @param {number} i @returns void
[ "highlight", "an", "individual", "code", "block" ]
299b4beb4818f7ca98f5e01f0d2a6675b8b2e4ac
https://github.com/vkiryukhin/jsonfn/blob/299b4beb4818f7ca98f5e01f0d2a6675b8b2e4ac/html/rainbow/rainbow.js#L616-L650
22,118
vkiryukhin/jsonfn
html/rainbow/rainbow.js
function(language, patterns, bypass) { // if there is only one argument then we assume that we want to // extend the default language rules if (arguments.length == 1) { patterns = language; language = DEFAULT_LANGUAGE; } bypass_defaults[language] = bypass; language_patterns[language] = patterns.concat(language_patterns[language] || []); }
javascript
function(language, patterns, bypass) { // if there is only one argument then we assume that we want to // extend the default language rules if (arguments.length == 1) { patterns = language; language = DEFAULT_LANGUAGE; } bypass_defaults[language] = bypass; language_patterns[language] = patterns.concat(language_patterns[language] || []); }
[ "function", "(", "language", ",", "patterns", ",", "bypass", ")", "{", "// if there is only one argument then we assume that we want to", "// extend the default language rules", "if", "(", "arguments", ".", "length", "==", "1", ")", "{", "patterns", "=", "language", ";", "language", "=", "DEFAULT_LANGUAGE", ";", "}", "bypass_defaults", "[", "language", "]", "=", "bypass", ";", "language_patterns", "[", "language", "]", "=", "patterns", ".", "concat", "(", "language_patterns", "[", "language", "]", "||", "[", "]", ")", ";", "}" ]
extends the language pattern matches @param {*} language name of language @param {*} patterns array of patterns to add on @param {boolean|null} bypass if true this will bypass the default language patterns
[ "extends", "the", "language", "pattern", "matches" ]
299b4beb4818f7ca98f5e01f0d2a6675b8b2e4ac
https://github.com/vkiryukhin/jsonfn/blob/299b4beb4818f7ca98f5e01f0d2a6675b8b2e4ac/html/rainbow/rainbow.js#L723-L734
22,119
vkiryukhin/jsonfn
html/rainbow/rainbow.js
function() { // if you want to straight up highlight a string you can pass the string of code, // the language, and a callback function if (typeof arguments[0] == 'string') { return _highlightBlockForLanguage(arguments[0], arguments[1], arguments[2]); } // if you pass a callback function then we rerun the color function // on all the code and call the callback function on complete if (typeof arguments[0] == 'function') { return _highlight(0, arguments[0]); } // otherwise we use whatever node you passed in with an optional // callback function as the second parameter _highlight(arguments[0], arguments[1]); }
javascript
function() { // if you want to straight up highlight a string you can pass the string of code, // the language, and a callback function if (typeof arguments[0] == 'string') { return _highlightBlockForLanguage(arguments[0], arguments[1], arguments[2]); } // if you pass a callback function then we rerun the color function // on all the code and call the callback function on complete if (typeof arguments[0] == 'function') { return _highlight(0, arguments[0]); } // otherwise we use whatever node you passed in with an optional // callback function as the second parameter _highlight(arguments[0], arguments[1]); }
[ "function", "(", ")", "{", "// if you want to straight up highlight a string you can pass the string of code,", "// the language, and a callback function", "if", "(", "typeof", "arguments", "[", "0", "]", "==", "'string'", ")", "{", "return", "_highlightBlockForLanguage", "(", "arguments", "[", "0", "]", ",", "arguments", "[", "1", "]", ",", "arguments", "[", "2", "]", ")", ";", "}", "// if you pass a callback function then we rerun the color function", "// on all the code and call the callback function on complete", "if", "(", "typeof", "arguments", "[", "0", "]", "==", "'function'", ")", "{", "return", "_highlight", "(", "0", ",", "arguments", "[", "0", "]", ")", ";", "}", "// otherwise we use whatever node you passed in with an optional", "// callback function as the second parameter", "_highlight", "(", "arguments", "[", "0", "]", ",", "arguments", "[", "1", "]", ")", ";", "}" ]
starts the magic rainbow @returns void
[ "starts", "the", "magic", "rainbow" ]
299b4beb4818f7ca98f5e01f0d2a6675b8b2e4ac
https://github.com/vkiryukhin/jsonfn/blob/299b4beb4818f7ca98f5e01f0d2a6675b8b2e4ac/html/rainbow/rainbow.js#L759-L776
22,120
webroo/dummy-json
lib/helpers.js
getNumber
function getNumber (type, min, max, format, options) { var ret; // Juggle the arguments if the user didn't supply a format string if (!options) { options = format; format = null; } if (type === 'int') { ret = utils.randomInt(min, max); } else if (type === 'float') { ret = utils.randomFloat(min, max); } if (typeof options.hash.round === 'number') { ret = Math.round(ret / options.hash.round) * options.hash.round; } if (format) { ret = numbro(ret).format(format); } return ret; }
javascript
function getNumber (type, min, max, format, options) { var ret; // Juggle the arguments if the user didn't supply a format string if (!options) { options = format; format = null; } if (type === 'int') { ret = utils.randomInt(min, max); } else if (type === 'float') { ret = utils.randomFloat(min, max); } if (typeof options.hash.round === 'number') { ret = Math.round(ret / options.hash.round) * options.hash.round; } if (format) { ret = numbro(ret).format(format); } return ret; }
[ "function", "getNumber", "(", "type", ",", "min", ",", "max", ",", "format", ",", "options", ")", "{", "var", "ret", ";", "// Juggle the arguments if the user didn't supply a format string", "if", "(", "!", "options", ")", "{", "options", "=", "format", ";", "format", "=", "null", ";", "}", "if", "(", "type", "===", "'int'", ")", "{", "ret", "=", "utils", ".", "randomInt", "(", "min", ",", "max", ")", ";", "}", "else", "if", "(", "type", "===", "'float'", ")", "{", "ret", "=", "utils", ".", "randomFloat", "(", "min", ",", "max", ")", ";", "}", "if", "(", "typeof", "options", ".", "hash", ".", "round", "===", "'number'", ")", "{", "ret", "=", "Math", ".", "round", "(", "ret", "/", "options", ".", "hash", ".", "round", ")", "*", "options", ".", "hash", ".", "round", ";", "}", "if", "(", "format", ")", "{", "ret", "=", "numbro", "(", "ret", ")", ".", "format", "(", "format", ")", ";", "}", "return", "ret", ";", "}" ]
Generating int and floats is very similar so we route both to this single function
[ "Generating", "int", "and", "floats", "is", "very", "similar", "so", "we", "route", "both", "to", "this", "single", "function" ]
4a89d2533d5bf401eee59e6aee66e2fbbdfe7a46
https://github.com/webroo/dummy-json/blob/4a89d2533d5bf401eee59e6aee66e2fbbdfe7a46/lib/helpers.js#L8-L32
22,121
webroo/dummy-json
lib/helpers.js
getDate
function getDate (type, min, max, format, options) { var ret; // Juggle the arguments if the user didn't supply a format string if (!options) { options = format; format = null; } if (type === 'date') { min = Date.parse(min); max = Date.parse(max); } else if (type === 'time') { min = Date.parse('1970-01-01T' + min); max = Date.parse('1970-01-01T' + max); } ret = utils.randomDate(min, max); if (format === 'unix') { // We need to undo the timezone offset fix from utils.randomDate() ret = Math.floor((ret.getTime() - ret.getTimezoneOffset() * 60000) / 1000); } else if (format) { ret = fecha.format(ret, format); } else if (type === 'time') { // Time has a default format if one is not specified ret = fecha.format(ret, 'HH:mm'); } return ret; }
javascript
function getDate (type, min, max, format, options) { var ret; // Juggle the arguments if the user didn't supply a format string if (!options) { options = format; format = null; } if (type === 'date') { min = Date.parse(min); max = Date.parse(max); } else if (type === 'time') { min = Date.parse('1970-01-01T' + min); max = Date.parse('1970-01-01T' + max); } ret = utils.randomDate(min, max); if (format === 'unix') { // We need to undo the timezone offset fix from utils.randomDate() ret = Math.floor((ret.getTime() - ret.getTimezoneOffset() * 60000) / 1000); } else if (format) { ret = fecha.format(ret, format); } else if (type === 'time') { // Time has a default format if one is not specified ret = fecha.format(ret, 'HH:mm'); } return ret; }
[ "function", "getDate", "(", "type", ",", "min", ",", "max", ",", "format", ",", "options", ")", "{", "var", "ret", ";", "// Juggle the arguments if the user didn't supply a format string", "if", "(", "!", "options", ")", "{", "options", "=", "format", ";", "format", "=", "null", ";", "}", "if", "(", "type", "===", "'date'", ")", "{", "min", "=", "Date", ".", "parse", "(", "min", ")", ";", "max", "=", "Date", ".", "parse", "(", "max", ")", ";", "}", "else", "if", "(", "type", "===", "'time'", ")", "{", "min", "=", "Date", ".", "parse", "(", "'1970-01-01T'", "+", "min", ")", ";", "max", "=", "Date", ".", "parse", "(", "'1970-01-01T'", "+", "max", ")", ";", "}", "ret", "=", "utils", ".", "randomDate", "(", "min", ",", "max", ")", ";", "if", "(", "format", "===", "'unix'", ")", "{", "// We need to undo the timezone offset fix from utils.randomDate()", "ret", "=", "Math", ".", "floor", "(", "(", "ret", ".", "getTime", "(", ")", "-", "ret", ".", "getTimezoneOffset", "(", ")", "*", "60000", ")", "/", "1000", ")", ";", "}", "else", "if", "(", "format", ")", "{", "ret", "=", "fecha", ".", "format", "(", "ret", ",", "format", ")", ";", "}", "else", "if", "(", "type", "===", "'time'", ")", "{", "// Time has a default format if one is not specified", "ret", "=", "fecha", ".", "format", "(", "ret", ",", "'HH:mm'", ")", ";", "}", "return", "ret", ";", "}" ]
Generating time and dates is very similar so we route both to this single function
[ "Generating", "time", "and", "dates", "is", "very", "similar", "so", "we", "route", "both", "to", "this", "single", "function" ]
4a89d2533d5bf401eee59e6aee66e2fbbdfe7a46
https://github.com/webroo/dummy-json/blob/4a89d2533d5bf401eee59e6aee66e2fbbdfe7a46/lib/helpers.js#L35-L65
22,122
kentcdodds/genie
src/index.js
_createWish
function _createWish(wish) { const id = wish.id || `g-${_previousId++}` const newWish = { id, context: _createContext(wish.context), data: wish.data || {}, magicWords: _arrayify(wish.magicWords), action: _createAction(wish.action), } newWish.data.timesMade = { total: 0, magicWords: {}, } return newWish }
javascript
function _createWish(wish) { const id = wish.id || `g-${_previousId++}` const newWish = { id, context: _createContext(wish.context), data: wish.data || {}, magicWords: _arrayify(wish.magicWords), action: _createAction(wish.action), } newWish.data.timesMade = { total: 0, magicWords: {}, } return newWish }
[ "function", "_createWish", "(", "wish", ")", "{", "const", "id", "=", "wish", ".", "id", "||", "`", "${", "_previousId", "++", "}", "`", "const", "newWish", "=", "{", "id", ",", "context", ":", "_createContext", "(", "wish", ".", "context", ")", ",", "data", ":", "wish", ".", "data", "||", "{", "}", ",", "magicWords", ":", "_arrayify", "(", "wish", ".", "magicWords", ")", ",", "action", ":", "_createAction", "(", "wish", ".", "action", ")", ",", "}", "newWish", ".", "data", ".", "timesMade", "=", "{", "total", ":", "0", ",", "magicWords", ":", "{", "}", ",", "}", "return", "newWish", "}" ]
Creates a new wish object. @param {object} wish @returns {wish} New wish object @private
[ "Creates", "a", "new", "wish", "object", "." ]
9b868ea9dd41f4ce931abc7e37b3467a356443cf
https://github.com/kentcdodds/genie/blob/9b868ea9dd41f4ce931abc7e37b3467a356443cf/src/index.js#L156-L170
22,123
kentcdodds/genie
src/index.js
_createContext
function _createContext(context) { let newContext = context || _defaultContext if (_isString(newContext) || _isArray(newContext)) { newContext = { any: _arrayify(newContext), } } else { newContext = _arrayizeContext(context) } return newContext }
javascript
function _createContext(context) { let newContext = context || _defaultContext if (_isString(newContext) || _isArray(newContext)) { newContext = { any: _arrayify(newContext), } } else { newContext = _arrayizeContext(context) } return newContext }
[ "function", "_createContext", "(", "context", ")", "{", "let", "newContext", "=", "context", "||", "_defaultContext", "if", "(", "_isString", "(", "newContext", ")", "||", "_isArray", "(", "newContext", ")", ")", "{", "newContext", "=", "{", "any", ":", "_arrayify", "(", "newContext", ")", ",", "}", "}", "else", "{", "newContext", "=", "_arrayizeContext", "(", "context", ")", "}", "return", "newContext", "}" ]
Transforms the given context to a context object. @param {object|string|Array.<string>} context @returns {context} @private
[ "Transforms", "the", "given", "context", "to", "a", "context", "object", "." ]
9b868ea9dd41f4ce931abc7e37b3467a356443cf
https://github.com/kentcdodds/genie/blob/9b868ea9dd41f4ce931abc7e37b3467a356443cf/src/index.js#L178-L188
22,124
kentcdodds/genie
src/index.js
_arrayizeContext
function _arrayizeContext(context) { function checkAndAdd(type) { if (context[type]) { context[type] = _arrayify(context[type]) } } checkAndAdd('all') checkAndAdd('any') checkAndAdd('none') return context }
javascript
function _arrayizeContext(context) { function checkAndAdd(type) { if (context[type]) { context[type] = _arrayify(context[type]) } } checkAndAdd('all') checkAndAdd('any') checkAndAdd('none') return context }
[ "function", "_arrayizeContext", "(", "context", ")", "{", "function", "checkAndAdd", "(", "type", ")", "{", "if", "(", "context", "[", "type", "]", ")", "{", "context", "[", "type", "]", "=", "_arrayify", "(", "context", "[", "type", "]", ")", "}", "}", "checkAndAdd", "(", "'all'", ")", "checkAndAdd", "(", "'any'", ")", "checkAndAdd", "(", "'none'", ")", "return", "context", "}" ]
Makes all the context properties arrays. @param {object|string|Array.<string>} context @returns {context} @private
[ "Makes", "all", "the", "context", "properties", "arrays", "." ]
9b868ea9dd41f4ce931abc7e37b3467a356443cf
https://github.com/kentcdodds/genie/blob/9b868ea9dd41f4ce931abc7e37b3467a356443cf/src/index.js#L196-L206
22,125
kentcdodds/genie
src/index.js
_createAction
function _createAction(action) { if (_isString(action)) { action = { destination: action, } } if (_isObject(action)) { action = (function() { const openNewTab = action.openNewTab const destination = action.destination return function() { if (openNewTab) { window.open(destination, '_blank') } else { window.location.href = destination } } })() } return action }
javascript
function _createAction(action) { if (_isString(action)) { action = { destination: action, } } if (_isObject(action)) { action = (function() { const openNewTab = action.openNewTab const destination = action.destination return function() { if (openNewTab) { window.open(destination, '_blank') } else { window.location.href = destination } } })() } return action }
[ "function", "_createAction", "(", "action", ")", "{", "if", "(", "_isString", "(", "action", ")", ")", "{", "action", "=", "{", "destination", ":", "action", ",", "}", "}", "if", "(", "_isObject", "(", "action", ")", ")", "{", "action", "=", "(", "function", "(", ")", "{", "const", "openNewTab", "=", "action", ".", "openNewTab", "const", "destination", "=", "action", ".", "destination", "return", "function", "(", ")", "{", "if", "(", "openNewTab", ")", "{", "window", ".", "open", "(", "destination", ",", "'_blank'", ")", "}", "else", "{", "window", ".", "location", ".", "href", "=", "destination", "}", "}", "}", ")", "(", ")", "}", "return", "action", "}" ]
Transforms the given action into an action callback. @param {Function|object|string} action @returns {WishAction} @private
[ "Transforms", "the", "given", "action", "into", "an", "action", "callback", "." ]
9b868ea9dd41f4ce931abc7e37b3467a356443cf
https://github.com/kentcdodds/genie/blob/9b868ea9dd41f4ce931abc7e37b3467a356443cf/src/index.js#L215-L236
22,126
kentcdodds/genie
src/index.js
deregisterWish
function deregisterWish(wish) { let indexOfWish = _wishes.indexOf(wish) if (!indexOfWish) { _each(_wishes, (aWish, index) => { // the given parameter could be an id. if (wish === aWish.id || wish.id === aWish.id) { indexOfWish = index wish = aWish return false } }) } _wishes.splice(indexOfWish, 1) _removeWishIdFromEnteredMagicWords(wish.id) return wish }
javascript
function deregisterWish(wish) { let indexOfWish = _wishes.indexOf(wish) if (!indexOfWish) { _each(_wishes, (aWish, index) => { // the given parameter could be an id. if (wish === aWish.id || wish.id === aWish.id) { indexOfWish = index wish = aWish return false } }) } _wishes.splice(indexOfWish, 1) _removeWishIdFromEnteredMagicWords(wish.id) return wish }
[ "function", "deregisterWish", "(", "wish", ")", "{", "let", "indexOfWish", "=", "_wishes", ".", "indexOf", "(", "wish", ")", "if", "(", "!", "indexOfWish", ")", "{", "_each", "(", "_wishes", ",", "(", "aWish", ",", "index", ")", "=>", "{", "// the given parameter could be an id.", "if", "(", "wish", "===", "aWish", ".", "id", "||", "wish", ".", "id", "===", "aWish", ".", "id", ")", "{", "indexOfWish", "=", "index", "wish", "=", "aWish", "return", "false", "}", "}", ")", "}", "_wishes", ".", "splice", "(", "indexOfWish", ",", "1", ")", "_removeWishIdFromEnteredMagicWords", "(", "wish", ".", "id", ")", "return", "wish", "}" ]
Deregisters the given wish. Removes it from the registry and from the _enteredMagicWords map. This will delete an _enteredMagicWords listing if this is the only wish in the list. @param {object|string} wish The wish to deregister @returns {wish} The deregistered wish @public
[ "Deregisters", "the", "given", "wish", ".", "Removes", "it", "from", "the", "registry", "and", "from", "the", "_enteredMagicWords", "map", ".", "This", "will", "delete", "an", "_enteredMagicWords", "listing", "if", "this", "is", "the", "only", "wish", "in", "the", "list", "." ]
9b868ea9dd41f4ce931abc7e37b3467a356443cf
https://github.com/kentcdodds/genie/blob/9b868ea9dd41f4ce931abc7e37b3467a356443cf/src/index.js#L247-L263
22,127
kentcdodds/genie
src/index.js
_removeWishIdFromEnteredMagicWords
function _removeWishIdFromEnteredMagicWords(id) { function removeIdFromWishes(charObj, parent, charObjName) { _each(charObj, (childProp, propName) => { if (propName === 'wishes') { const index = childProp.indexOf(id) if (index !== -1) { childProp.splice(index, 1) } if (!childProp.length) { delete charObj[propName] } } else { removeIdFromWishes(childProp, charObj, propName) } }) const keepCharObj = _getPropFromPosterity(charObj, 'wishes').length > 0 if (!keepCharObj && parent && charObjName) { delete parent[charObjName] } } removeIdFromWishes(_enteredMagicWords) }
javascript
function _removeWishIdFromEnteredMagicWords(id) { function removeIdFromWishes(charObj, parent, charObjName) { _each(charObj, (childProp, propName) => { if (propName === 'wishes') { const index = childProp.indexOf(id) if (index !== -1) { childProp.splice(index, 1) } if (!childProp.length) { delete charObj[propName] } } else { removeIdFromWishes(childProp, charObj, propName) } }) const keepCharObj = _getPropFromPosterity(charObj, 'wishes').length > 0 if (!keepCharObj && parent && charObjName) { delete parent[charObjName] } } removeIdFromWishes(_enteredMagicWords) }
[ "function", "_removeWishIdFromEnteredMagicWords", "(", "id", ")", "{", "function", "removeIdFromWishes", "(", "charObj", ",", "parent", ",", "charObjName", ")", "{", "_each", "(", "charObj", ",", "(", "childProp", ",", "propName", ")", "=>", "{", "if", "(", "propName", "===", "'wishes'", ")", "{", "const", "index", "=", "childProp", ".", "indexOf", "(", "id", ")", "if", "(", "index", "!==", "-", "1", ")", "{", "childProp", ".", "splice", "(", "index", ",", "1", ")", "}", "if", "(", "!", "childProp", ".", "length", ")", "{", "delete", "charObj", "[", "propName", "]", "}", "}", "else", "{", "removeIdFromWishes", "(", "childProp", ",", "charObj", ",", "propName", ")", "}", "}", ")", "const", "keepCharObj", "=", "_getPropFromPosterity", "(", "charObj", ",", "'wishes'", ")", ".", "length", ">", "0", "if", "(", "!", "keepCharObj", "&&", "parent", "&&", "charObjName", ")", "{", "delete", "parent", "[", "charObjName", "]", "}", "}", "removeIdFromWishes", "(", "_enteredMagicWords", ")", "}" ]
Iterates through _enteredMagicWords and removes all instances of this id. If this leaves the letter empty it removes the letter. @param {string} id @private
[ "Iterates", "through", "_enteredMagicWords", "and", "removes", "all", "instances", "of", "this", "id", ".", "If", "this", "leaves", "the", "letter", "empty", "it", "removes", "the", "letter", "." ]
9b868ea9dd41f4ce931abc7e37b3467a356443cf
https://github.com/kentcdodds/genie/blob/9b868ea9dd41f4ce931abc7e37b3467a356443cf/src/index.js#L272-L293
22,128
kentcdodds/genie
src/index.js
deregisterWishesWithContext
function deregisterWishesWithContext(context, type, wishContextTypes) { const deregisteredWishes = getWishesWithContext( context, type, wishContextTypes, ) _each(deregisteredWishes, (wish, i) => { deregisteredWishes[i] = deregisterWish(wish) }) return deregisteredWishes }
javascript
function deregisterWishesWithContext(context, type, wishContextTypes) { const deregisteredWishes = getWishesWithContext( context, type, wishContextTypes, ) _each(deregisteredWishes, (wish, i) => { deregisteredWishes[i] = deregisterWish(wish) }) return deregisteredWishes }
[ "function", "deregisterWishesWithContext", "(", "context", ",", "type", ",", "wishContextTypes", ")", "{", "const", "deregisteredWishes", "=", "getWishesWithContext", "(", "context", ",", "type", ",", "wishContextTypes", ",", ")", "_each", "(", "deregisteredWishes", ",", "(", "wish", ",", "i", ")", "=>", "{", "deregisteredWishes", "[", "i", "]", "=", "deregisterWish", "(", "wish", ")", "}", ")", "return", "deregisteredWishes", "}" ]
Convenience method which calls getWishesWithContext and passes the arguments which are passed to this function. Then deregisters each of these. @param {string|Array.<string>} context The context the lookup @param {string} [type='any'] 'all', 'any', or 'none' referring to the context parameter @param {string|Array.<string>} [wishContextTypes=['any', 'all', 'none']] The type of wish contexts to compare @returns {Array.<object>} the deregistered wishes. @public
[ "Convenience", "method", "which", "calls", "getWishesWithContext", "and", "passes", "the", "arguments", "which", "are", "passed", "to", "this", "function", ".", "Then", "deregisters", "each", "of", "these", "." ]
9b868ea9dd41f4ce931abc7e37b3467a356443cf
https://github.com/kentcdodds/genie/blob/9b868ea9dd41f4ce931abc7e37b3467a356443cf/src/index.js#L306-L316
22,129
kentcdodds/genie
src/index.js
_getWishContext
function _getWishContext(wish, wishContextTypes) { let wishContext = [] wishContextTypes = wishContextTypes || ['all', 'any', 'none'] wishContextTypes = _arrayify(wishContextTypes) _each(wishContextTypes, wishContextType => { if (wish.context[wishContextType]) { wishContext = wishContext.concat(wish.context[wishContextType]) } }) return wishContext }
javascript
function _getWishContext(wish, wishContextTypes) { let wishContext = [] wishContextTypes = wishContextTypes || ['all', 'any', 'none'] wishContextTypes = _arrayify(wishContextTypes) _each(wishContextTypes, wishContextType => { if (wish.context[wishContextType]) { wishContext = wishContext.concat(wish.context[wishContextType]) } }) return wishContext }
[ "function", "_getWishContext", "(", "wish", ",", "wishContextTypes", ")", "{", "let", "wishContext", "=", "[", "]", "wishContextTypes", "=", "wishContextTypes", "||", "[", "'all'", ",", "'any'", ",", "'none'", "]", "wishContextTypes", "=", "_arrayify", "(", "wishContextTypes", ")", "_each", "(", "wishContextTypes", ",", "wishContextType", "=>", "{", "if", "(", "wish", ".", "context", "[", "wishContextType", "]", ")", "{", "wishContext", "=", "wishContext", ".", "concat", "(", "wish", ".", "context", "[", "wishContextType", "]", ")", "}", "}", ")", "return", "wishContext", "}" ]
Gets the wish context based on the wishContextTypes. @param {object} wish @param {string|Array.<string>} wishContextTypes @returns {Array.<string>} @private
[ "Gets", "the", "wish", "context", "based", "on", "the", "wishContextTypes", "." ]
9b868ea9dd41f4ce931abc7e37b3467a356443cf
https://github.com/kentcdodds/genie/blob/9b868ea9dd41f4ce931abc7e37b3467a356443cf/src/index.js#L380-L392
22,130
kentcdodds/genie
src/index.js
_getWishIndexById
function _getWishIndexById(id) { let wishIndex = -1 if (_isArray(id)) { const wishIndexes = [] _each(id, wishId => { wishIndexes.push(_getWishIndexById(wishId)) }) return wishIndexes } else { _each(_wishes, (aWish, index) => { if (aWish.id === id) { wishIndex = index return false } }) return wishIndex } }
javascript
function _getWishIndexById(id) { let wishIndex = -1 if (_isArray(id)) { const wishIndexes = [] _each(id, wishId => { wishIndexes.push(_getWishIndexById(wishId)) }) return wishIndexes } else { _each(_wishes, (aWish, index) => { if (aWish.id === id) { wishIndex = index return false } }) return wishIndex } }
[ "function", "_getWishIndexById", "(", "id", ")", "{", "let", "wishIndex", "=", "-", "1", "if", "(", "_isArray", "(", "id", ")", ")", "{", "const", "wishIndexes", "=", "[", "]", "_each", "(", "id", ",", "wishId", "=>", "{", "wishIndexes", ".", "push", "(", "_getWishIndexById", "(", "wishId", ")", ")", "}", ")", "return", "wishIndexes", "}", "else", "{", "_each", "(", "_wishes", ",", "(", "aWish", ",", "index", ")", "=>", "{", "if", "(", "aWish", ".", "id", "===", "id", ")", "{", "wishIndex", "=", "index", "return", "false", "}", "}", ")", "return", "wishIndex", "}", "}" ]
Gets a wish from the _wishes array by its ID @param {wishIds} id @returns {wish|Array.<wish>} @private
[ "Gets", "a", "wish", "from", "the", "_wishes", "array", "by", "its", "ID" ]
9b868ea9dd41f4ce931abc7e37b3467a356443cf
https://github.com/kentcdodds/genie/blob/9b868ea9dd41f4ce931abc7e37b3467a356443cf/src/index.js#L428-L445
22,131
kentcdodds/genie
src/index.js
reset
function reset() { const oldOptions = options() options({ wishes: [], noWishMerge: true, previousId: 0, enteredMagicWords: {}, context: _defaultContext, previousContext: _defaultContext, enabled: true, }) return oldOptions }
javascript
function reset() { const oldOptions = options() options({ wishes: [], noWishMerge: true, previousId: 0, enteredMagicWords: {}, context: _defaultContext, previousContext: _defaultContext, enabled: true, }) return oldOptions }
[ "function", "reset", "(", ")", "{", "const", "oldOptions", "=", "options", "(", ")", "options", "(", "{", "wishes", ":", "[", "]", ",", "noWishMerge", ":", "true", ",", "previousId", ":", "0", ",", "enteredMagicWords", ":", "{", "}", ",", "context", ":", "_defaultContext", ",", "previousContext", ":", "_defaultContext", ",", "enabled", ":", "true", ",", "}", ")", "return", "oldOptions", "}" ]
Sets genie's options to the default options @returns {GenieOptions} Genie's old options @public
[ "Sets", "genie", "s", "options", "to", "the", "default", "options" ]
9b868ea9dd41f4ce931abc7e37b3467a356443cf
https://github.com/kentcdodds/genie/blob/9b868ea9dd41f4ce931abc7e37b3467a356443cf/src/index.js#L452-L464
22,132
kentcdodds/genie
src/index.js
_getWishIdsInEnteredMagicWords
function _getWishIdsInEnteredMagicWords(word) { const startingCharWishesObj = _climbDownChain( _enteredMagicWords, word.split(''), ) if (startingCharWishesObj) { return _getPropFromPosterity(startingCharWishesObj, 'wishes', true) } else { return [] } }
javascript
function _getWishIdsInEnteredMagicWords(word) { const startingCharWishesObj = _climbDownChain( _enteredMagicWords, word.split(''), ) if (startingCharWishesObj) { return _getPropFromPosterity(startingCharWishesObj, 'wishes', true) } else { return [] } }
[ "function", "_getWishIdsInEnteredMagicWords", "(", "word", ")", "{", "const", "startingCharWishesObj", "=", "_climbDownChain", "(", "_enteredMagicWords", ",", "word", ".", "split", "(", "''", ")", ",", ")", "if", "(", "startingCharWishesObj", ")", "{", "return", "_getPropFromPosterity", "(", "startingCharWishesObj", ",", "'wishes'", ",", "true", ")", "}", "else", "{", "return", "[", "]", "}", "}" ]
Climbs down the chain with the _enteredMagicWords object to find where the word ends and then gets the 'wish' property from the posterity at that point in the _enteredMagicWords object. @param {string} word @returns {Array.<wish>} @private
[ "Climbs", "down", "the", "chain", "with", "the", "_enteredMagicWords", "object", "to", "find", "where", "the", "word", "ends", "and", "then", "gets", "the", "wish", "property", "from", "the", "posterity", "at", "that", "point", "in", "the", "_enteredMagicWords", "object", "." ]
9b868ea9dd41f4ce931abc7e37b3467a356443cf
https://github.com/kentcdodds/genie/blob/9b868ea9dd41f4ce931abc7e37b3467a356443cf/src/index.js#L499-L509
22,133
kentcdodds/genie
src/index.js
_filterInContextWishes
function _filterInContextWishes(wishes) { const inContextWishes = [] _each(wishes, wish => { if (wish && _wishInContext(wish)) { inContextWishes.push(wish) } }) return inContextWishes }
javascript
function _filterInContextWishes(wishes) { const inContextWishes = [] _each(wishes, wish => { if (wish && _wishInContext(wish)) { inContextWishes.push(wish) } }) return inContextWishes }
[ "function", "_filterInContextWishes", "(", "wishes", ")", "{", "const", "inContextWishes", "=", "[", "]", "_each", "(", "wishes", ",", "wish", "=>", "{", "if", "(", "wish", "&&", "_wishInContext", "(", "wish", ")", ")", "{", "inContextWishes", ".", "push", "(", "wish", ")", "}", "}", ")", "return", "inContextWishes", "}" ]
Returns a filtered array of the wishes which are in context. @param {Array.<wish>} wishes - the wishes to filter @returns {Array.<wish>} wishes - the wishes which are in context @private
[ "Returns", "a", "filtered", "array", "of", "the", "wishes", "which", "are", "in", "context", "." ]
9b868ea9dd41f4ce931abc7e37b3467a356443cf
https://github.com/kentcdodds/genie/blob/9b868ea9dd41f4ce931abc7e37b3467a356443cf/src/index.js#L517-L525
22,134
kentcdodds/genie
src/index.js
_getPropFromPosterity
function _getPropFromPosterity(objToStartWith, prop, unique) { let values = [] function loadValues(obj) { if (obj[prop]) { const propsToAdd = _arrayify(obj[prop]) _each(propsToAdd, propToAdd => { if (!unique || !_contains(values, propToAdd)) { values.push(propToAdd) } }) } _each(obj, (oProp, oPropName) => { if (oPropName !== prop && !_isPrimitive(oProp)) { values = values.concat(loadValues(oProp)) } }) } loadValues(objToStartWith) return values }
javascript
function _getPropFromPosterity(objToStartWith, prop, unique) { let values = [] function loadValues(obj) { if (obj[prop]) { const propsToAdd = _arrayify(obj[prop]) _each(propsToAdd, propToAdd => { if (!unique || !_contains(values, propToAdd)) { values.push(propToAdd) } }) } _each(obj, (oProp, oPropName) => { if (oPropName !== prop && !_isPrimitive(oProp)) { values = values.concat(loadValues(oProp)) } }) } loadValues(objToStartWith) return values }
[ "function", "_getPropFromPosterity", "(", "objToStartWith", ",", "prop", ",", "unique", ")", "{", "let", "values", "=", "[", "]", "function", "loadValues", "(", "obj", ")", "{", "if", "(", "obj", "[", "prop", "]", ")", "{", "const", "propsToAdd", "=", "_arrayify", "(", "obj", "[", "prop", "]", ")", "_each", "(", "propsToAdd", ",", "propToAdd", "=>", "{", "if", "(", "!", "unique", "||", "!", "_contains", "(", "values", ",", "propToAdd", ")", ")", "{", "values", ".", "push", "(", "propToAdd", ")", "}", "}", ")", "}", "_each", "(", "obj", ",", "(", "oProp", ",", "oPropName", ")", "=>", "{", "if", "(", "oPropName", "!==", "prop", "&&", "!", "_isPrimitive", "(", "oProp", ")", ")", "{", "values", "=", "values", ".", "concat", "(", "loadValues", "(", "oProp", ")", ")", "}", "}", ")", "}", "loadValues", "(", "objToStartWith", ")", "return", "values", "}" ]
Iterates through all child properties of the given object and if it has the given property, it will add that property to the array that's returned at the end. @param {*} objToStartWith @param {string} prop @param {boolean} [unique=false] @returns {Array.<object>} @private @examples _getPropFromPosterity({a: {p: 1, b: {p: 2}}}, 'p') // => [1,2]
[ "Iterates", "through", "all", "child", "properties", "of", "the", "given", "object", "and", "if", "it", "has", "the", "given", "property", "it", "will", "add", "that", "property", "to", "the", "array", "that", "s", "returned", "at", "the", "end", "." ]
9b868ea9dd41f4ce931abc7e37b3467a356443cf
https://github.com/kentcdodds/genie/blob/9b868ea9dd41f4ce931abc7e37b3467a356443cf/src/index.js#L568-L587
22,135
kentcdodds/genie
src/index.js
_sortWishesByMatchingPriority
function _sortWishesByMatchingPriority( wishes, currentMatchingWishIds, givenMagicWord, ) { const matchPriorityArrays = [] let returnedIds = [] _each( wishes, wish => { if (_wishInContext(wish)) { const matchPriority = _bestMagicWordsMatch( wish.magicWords, givenMagicWord, ) _maybeAddWishToMatchPriorityArray( wish, matchPriority, matchPriorityArrays, currentMatchingWishIds, ) } }, true, ) _each( matchPriorityArrays, matchTypeArray => { if (matchTypeArray) { _each(matchTypeArray, magicWordIndexArray => { if (magicWordIndexArray) { returnedIds = returnedIds.concat(magicWordIndexArray) } }) } }, true, ) return returnedIds }
javascript
function _sortWishesByMatchingPriority( wishes, currentMatchingWishIds, givenMagicWord, ) { const matchPriorityArrays = [] let returnedIds = [] _each( wishes, wish => { if (_wishInContext(wish)) { const matchPriority = _bestMagicWordsMatch( wish.magicWords, givenMagicWord, ) _maybeAddWishToMatchPriorityArray( wish, matchPriority, matchPriorityArrays, currentMatchingWishIds, ) } }, true, ) _each( matchPriorityArrays, matchTypeArray => { if (matchTypeArray) { _each(matchTypeArray, magicWordIndexArray => { if (magicWordIndexArray) { returnedIds = returnedIds.concat(magicWordIndexArray) } }) } }, true, ) return returnedIds }
[ "function", "_sortWishesByMatchingPriority", "(", "wishes", ",", "currentMatchingWishIds", ",", "givenMagicWord", ",", ")", "{", "const", "matchPriorityArrays", "=", "[", "]", "let", "returnedIds", "=", "[", "]", "_each", "(", "wishes", ",", "wish", "=>", "{", "if", "(", "_wishInContext", "(", "wish", ")", ")", "{", "const", "matchPriority", "=", "_bestMagicWordsMatch", "(", "wish", ".", "magicWords", ",", "givenMagicWord", ",", ")", "_maybeAddWishToMatchPriorityArray", "(", "wish", ",", "matchPriority", ",", "matchPriorityArrays", ",", "currentMatchingWishIds", ",", ")", "}", "}", ",", "true", ",", ")", "_each", "(", "matchPriorityArrays", ",", "matchTypeArray", "=>", "{", "if", "(", "matchTypeArray", ")", "{", "_each", "(", "matchTypeArray", ",", "magicWordIndexArray", "=>", "{", "if", "(", "magicWordIndexArray", ")", "{", "returnedIds", "=", "returnedIds", ".", "concat", "(", "magicWordIndexArray", ")", "}", "}", ")", "}", "}", ",", "true", ",", ")", "return", "returnedIds", "}" ]
A matchPriority for a wish @typedef {object} MatchPriority @property {number} matchType - based on _matchRankMap @property {number} magicWordIndex - the index of the magic word in the wish's array of magic words. Takes the given wishes and sorts them by how well they match the givenMagicWord. The wish must be in context, and they follow the order defined in the {@link "#_matchRankMap"} @param {*} wishes @param {Array.<string>} currentMatchingWishIds @param givenMagicWord @returns {Array.<string>} @private
[ "A", "matchPriority", "for", "a", "wish" ]
9b868ea9dd41f4ce931abc7e37b3467a356443cf
https://github.com/kentcdodds/genie/blob/9b868ea9dd41f4ce931abc7e37b3467a356443cf/src/index.js#L607-L648
22,136
kentcdodds/genie
src/index.js
_bestMagicWordsMatch
function _bestMagicWordsMatch(wishesMagicWords, givenMagicWord) { const bestMatch = { matchType: _matchRankMap.noMatch, magicWordIndex: -1, } _each(wishesMagicWords, (wishesMagicWord, index) => { const matchRank = _stringsMatch(wishesMagicWord, givenMagicWord) if (matchRank > bestMatch.matchType) { bestMatch.matchType = matchRank bestMatch.magicWordIndex = index } return bestMatch.matchType !== _matchRankMap.equals }) return bestMatch }
javascript
function _bestMagicWordsMatch(wishesMagicWords, givenMagicWord) { const bestMatch = { matchType: _matchRankMap.noMatch, magicWordIndex: -1, } _each(wishesMagicWords, (wishesMagicWord, index) => { const matchRank = _stringsMatch(wishesMagicWord, givenMagicWord) if (matchRank > bestMatch.matchType) { bestMatch.matchType = matchRank bestMatch.magicWordIndex = index } return bestMatch.matchType !== _matchRankMap.equals }) return bestMatch }
[ "function", "_bestMagicWordsMatch", "(", "wishesMagicWords", ",", "givenMagicWord", ")", "{", "const", "bestMatch", "=", "{", "matchType", ":", "_matchRankMap", ".", "noMatch", ",", "magicWordIndex", ":", "-", "1", ",", "}", "_each", "(", "wishesMagicWords", ",", "(", "wishesMagicWord", ",", "index", ")", "=>", "{", "const", "matchRank", "=", "_stringsMatch", "(", "wishesMagicWord", ",", "givenMagicWord", ")", "if", "(", "matchRank", ">", "bestMatch", ".", "matchType", ")", "{", "bestMatch", ".", "matchType", "=", "matchRank", "bestMatch", ".", "magicWordIndex", "=", "index", "}", "return", "bestMatch", ".", "matchType", "!==", "_matchRankMap", ".", "equals", "}", ")", "return", "bestMatch", "}" ]
Gets the best magic words match of the wish's magic words @param {string|Array.<string>} wishesMagicWords @param {string} givenMagicWord @returns {MatchPriority} @private
[ "Gets", "the", "best", "magic", "words", "match", "of", "the", "wish", "s", "magic", "words" ]
9b868ea9dd41f4ce931abc7e37b3467a356443cf
https://github.com/kentcdodds/genie/blob/9b868ea9dd41f4ce931abc7e37b3467a356443cf/src/index.js#L657-L671
22,137
kentcdodds/genie
src/index.js
_getAcronym
function _getAcronym(string) { let acronym = '' const wordsInString = string.split(' ') _each(wordsInString, wordInString => { const splitByHyphenWords = wordInString.split('-') _each(splitByHyphenWords, splitByHyphenWord => { acronym += splitByHyphenWord.substr(0, 1) }) }) return acronym }
javascript
function _getAcronym(string) { let acronym = '' const wordsInString = string.split(' ') _each(wordsInString, wordInString => { const splitByHyphenWords = wordInString.split('-') _each(splitByHyphenWords, splitByHyphenWord => { acronym += splitByHyphenWord.substr(0, 1) }) }) return acronym }
[ "function", "_getAcronym", "(", "string", ")", "{", "let", "acronym", "=", "''", "const", "wordsInString", "=", "string", ".", "split", "(", "' '", ")", "_each", "(", "wordsInString", ",", "wordInString", "=>", "{", "const", "splitByHyphenWords", "=", "wordInString", ".", "split", "(", "'-'", ")", "_each", "(", "splitByHyphenWords", ",", "splitByHyphenWord", "=>", "{", "acronym", "+=", "splitByHyphenWord", ".", "substr", "(", "0", ",", "1", ")", "}", ")", "}", ")", "return", "acronym", "}" ]
Generates an acronym for a string. @param {string} string @returns {string} @private @examples _getAcronym('i love candy') // => 'ilc' _getAcronym('water-fall in the spring-time') // => 'wfitst'
[ "Generates", "an", "acronym", "for", "a", "string", "." ]
9b868ea9dd41f4ce931abc7e37b3467a356443cf
https://github.com/kentcdodds/genie/blob/9b868ea9dd41f4ce931abc7e37b3467a356443cf/src/index.js#L733-L743
22,138
kentcdodds/genie
src/index.js
_stringsByCharOrder
function _stringsByCharOrder(magicWord, givenMagicWord) { let charNumber = 0 function _findMatchingCharacter(matchChar, string) { let found = false for (let j = charNumber; j < string.length; j++) { const stringChar = string[j] if (stringChar === matchChar) { found = true charNumber = j + 1 break } } return found } for (let i = 0; i < givenMagicWord.length; i++) { const matchChar = givenMagicWord[i] const found = _findMatchingCharacter(matchChar, magicWord) if (!found) { return _matchRankMap.noMatch } } return _matchRankMap.matches }
javascript
function _stringsByCharOrder(magicWord, givenMagicWord) { let charNumber = 0 function _findMatchingCharacter(matchChar, string) { let found = false for (let j = charNumber; j < string.length; j++) { const stringChar = string[j] if (stringChar === matchChar) { found = true charNumber = j + 1 break } } return found } for (let i = 0; i < givenMagicWord.length; i++) { const matchChar = givenMagicWord[i] const found = _findMatchingCharacter(matchChar, magicWord) if (!found) { return _matchRankMap.noMatch } } return _matchRankMap.matches }
[ "function", "_stringsByCharOrder", "(", "magicWord", ",", "givenMagicWord", ")", "{", "let", "charNumber", "=", "0", "function", "_findMatchingCharacter", "(", "matchChar", ",", "string", ")", "{", "let", "found", "=", "false", "for", "(", "let", "j", "=", "charNumber", ";", "j", "<", "string", ".", "length", ";", "j", "++", ")", "{", "const", "stringChar", "=", "string", "[", "j", "]", "if", "(", "stringChar", "===", "matchChar", ")", "{", "found", "=", "true", "charNumber", "=", "j", "+", "1", "break", "}", "}", "return", "found", "}", "for", "(", "let", "i", "=", "0", ";", "i", "<", "givenMagicWord", ".", "length", ";", "i", "++", ")", "{", "const", "matchChar", "=", "givenMagicWord", "[", "i", "]", "const", "found", "=", "_findMatchingCharacter", "(", "matchChar", ",", "magicWord", ")", "if", "(", "!", "found", ")", "{", "return", "_matchRankMap", ".", "noMatch", "}", "}", "return", "_matchRankMap", ".", "matches", "}" ]
Returns a _matchRankMap.matches or noMatch score based on whether the characters in the givenMagicWord are found in order in the magicWord @param {string} magicWord @param {string} givenMagicWord @returns {number} @private
[ "Returns", "a", "_matchRankMap", ".", "matches", "or", "noMatch", "score", "based", "on", "whether", "the", "characters", "in", "the", "givenMagicWord", "are", "found", "in", "order", "in", "the", "magicWord" ]
9b868ea9dd41f4ce931abc7e37b3467a356443cf
https://github.com/kentcdodds/genie/blob/9b868ea9dd41f4ce931abc7e37b3467a356443cf/src/index.js#L754-L778
22,139
kentcdodds/genie
src/index.js
_maybeAddWishToMatchPriorityArray
function _maybeAddWishToMatchPriorityArray( wish, matchPriority, matchPriorityArrays, currentMatchingWishIds, ) { const indexOfWishInCurrent = currentMatchingWishIds.indexOf(wish.id) if (matchPriority.matchType !== _matchRankMap.noMatch) { if (indexOfWishInCurrent === -1) { _getMatchPriorityArray(matchPriorityArrays, matchPriority).push(wish.id) } } else if (indexOfWishInCurrent !== -1) { // remove current matching wishIds if it doesn't match currentMatchingWishIds.splice(indexOfWishInCurrent, 1) } }
javascript
function _maybeAddWishToMatchPriorityArray( wish, matchPriority, matchPriorityArrays, currentMatchingWishIds, ) { const indexOfWishInCurrent = currentMatchingWishIds.indexOf(wish.id) if (matchPriority.matchType !== _matchRankMap.noMatch) { if (indexOfWishInCurrent === -1) { _getMatchPriorityArray(matchPriorityArrays, matchPriority).push(wish.id) } } else if (indexOfWishInCurrent !== -1) { // remove current matching wishIds if it doesn't match currentMatchingWishIds.splice(indexOfWishInCurrent, 1) } }
[ "function", "_maybeAddWishToMatchPriorityArray", "(", "wish", ",", "matchPriority", ",", "matchPriorityArrays", ",", "currentMatchingWishIds", ",", ")", "{", "const", "indexOfWishInCurrent", "=", "currentMatchingWishIds", ".", "indexOf", "(", "wish", ".", "id", ")", "if", "(", "matchPriority", ".", "matchType", "!==", "_matchRankMap", ".", "noMatch", ")", "{", "if", "(", "indexOfWishInCurrent", "===", "-", "1", ")", "{", "_getMatchPriorityArray", "(", "matchPriorityArrays", ",", "matchPriority", ")", ".", "push", "(", "wish", ".", "id", ")", "}", "}", "else", "if", "(", "indexOfWishInCurrent", "!==", "-", "1", ")", "{", "// remove current matching wishIds if it doesn't match", "currentMatchingWishIds", ".", "splice", "(", "indexOfWishInCurrent", ",", "1", ")", "}", "}" ]
If the wish has a matchType which is not equal to the _matchRankMap.noMatch and it is not contained in the currentMatchingWishIds, then it is added to the matchPriorityArrays based on the matchPriority. @param {wish} wish @param {MatchPriority} matchPriority @param {Array.<Array>} matchPriorityArrays @param {wishIds} currentMatchingWishIds @private
[ "If", "the", "wish", "has", "a", "matchType", "which", "is", "not", "equal", "to", "the", "_matchRankMap", ".", "noMatch", "and", "it", "is", "not", "contained", "in", "the", "currentMatchingWishIds", "then", "it", "is", "added", "to", "the", "matchPriorityArrays", "based", "on", "the", "matchPriority", "." ]
9b868ea9dd41f4ce931abc7e37b3467a356443cf
https://github.com/kentcdodds/genie/blob/9b868ea9dd41f4ce931abc7e37b3467a356443cf/src/index.js#L790-L805
22,140
kentcdodds/genie
src/index.js
_getMatchPriorityArray
function _getMatchPriorityArray(arry, matchPriority) { arry[matchPriority.matchType] = arry[matchPriority.matchType] || [] const matchTypeArray = arry[matchPriority.matchType] const matchPriorityArray = (matchTypeArray[matchPriority.magicWordIndex] = matchTypeArray[matchPriority.magicWordIndex] || []) return matchPriorityArray }
javascript
function _getMatchPriorityArray(arry, matchPriority) { arry[matchPriority.matchType] = arry[matchPriority.matchType] || [] const matchTypeArray = arry[matchPriority.matchType] const matchPriorityArray = (matchTypeArray[matchPriority.magicWordIndex] = matchTypeArray[matchPriority.magicWordIndex] || []) return matchPriorityArray }
[ "function", "_getMatchPriorityArray", "(", "arry", ",", "matchPriority", ")", "{", "arry", "[", "matchPriority", ".", "matchType", "]", "=", "arry", "[", "matchPriority", ".", "matchType", "]", "||", "[", "]", "const", "matchTypeArray", "=", "arry", "[", "matchPriority", ".", "matchType", "]", "const", "matchPriorityArray", "=", "(", "matchTypeArray", "[", "matchPriority", ".", "magicWordIndex", "]", "=", "matchTypeArray", "[", "matchPriority", ".", "magicWordIndex", "]", "||", "[", "]", ")", "return", "matchPriorityArray", "}" ]
Creates a spot in the given array for the matchPriority @param {Array.<Array>} arry @param {MatchPriority} matchPriority @returns {Array.<string>} @private
[ "Creates", "a", "spot", "in", "the", "given", "array", "for", "the", "matchPriority" ]
9b868ea9dd41f4ce931abc7e37b3467a356443cf
https://github.com/kentcdodds/genie/blob/9b868ea9dd41f4ce931abc7e37b3467a356443cf/src/index.js#L814-L820
22,141
kentcdodds/genie
src/index.js
_convertToWishObjectFromNullOrId
function _convertToWishObjectFromNullOrId(wish, magicWord) { let wishObject = wish // Check if it may be a wish object if (!_isObject(wishObject)) { wishObject = getWish(wish) } if (_isNullOrUndefined(wishObject)) { const matchingWishes = getMatchingWishes(magicWord) if (matchingWishes.length > 0) { wishObject = matchingWishes[0] } } return wishObject }
javascript
function _convertToWishObjectFromNullOrId(wish, magicWord) { let wishObject = wish // Check if it may be a wish object if (!_isObject(wishObject)) { wishObject = getWish(wish) } if (_isNullOrUndefined(wishObject)) { const matchingWishes = getMatchingWishes(magicWord) if (matchingWishes.length > 0) { wishObject = matchingWishes[0] } } return wishObject }
[ "function", "_convertToWishObjectFromNullOrId", "(", "wish", ",", "magicWord", ")", "{", "let", "wishObject", "=", "wish", "// Check if it may be a wish object", "if", "(", "!", "_isObject", "(", "wishObject", ")", ")", "{", "wishObject", "=", "getWish", "(", "wish", ")", "}", "if", "(", "_isNullOrUndefined", "(", "wishObject", ")", ")", "{", "const", "matchingWishes", "=", "getMatchingWishes", "(", "magicWord", ")", "if", "(", "matchingWishes", ".", "length", ">", "0", ")", "{", "wishObject", "=", "matchingWishes", "[", "0", "]", "}", "}", "return", "wishObject", "}" ]
Convert the given wish argument to a valid wish object. It could be an ID, or null. @param {wish|string} [wish] An id, wish object, or null. @param {string} magicWord Used if wish is null to lookup the nearest matching wish to be used. @returns {wish} The wish object @private
[ "Convert", "the", "given", "wish", "argument", "to", "a", "valid", "wish", "object", ".", "It", "could", "be", "an", "ID", "or", "null", "." ]
9b868ea9dd41f4ce931abc7e37b3467a356443cf
https://github.com/kentcdodds/genie/blob/9b868ea9dd41f4ce931abc7e37b3467a356443cf/src/index.js#L860-L873
22,142
kentcdodds/genie
src/index.js
_executeWish
function _executeWish(wish, magicWord) { wish.action(wish, magicWord) const timesMade = wish.data.timesMade timesMade.total++ timesMade.magicWords[magicWord] = timesMade.magicWords[magicWord] || 0 timesMade.magicWords[magicWord]++ }
javascript
function _executeWish(wish, magicWord) { wish.action(wish, magicWord) const timesMade = wish.data.timesMade timesMade.total++ timesMade.magicWords[magicWord] = timesMade.magicWords[magicWord] || 0 timesMade.magicWords[magicWord]++ }
[ "function", "_executeWish", "(", "wish", ",", "magicWord", ")", "{", "wish", ".", "action", "(", "wish", ",", "magicWord", ")", "const", "timesMade", "=", "wish", ".", "data", ".", "timesMade", "timesMade", ".", "total", "++", "timesMade", ".", "magicWords", "[", "magicWord", "]", "=", "timesMade", ".", "magicWords", "[", "magicWord", "]", "||", "0", "timesMade", ".", "magicWords", "[", "magicWord", "]", "++", "}" ]
Calls the wish's action with the wish and magic word as the parameters and iterates the timesMade properties. @param {wish} wish @param {string} magicWord @private
[ "Calls", "the", "wish", "s", "action", "with", "the", "wish", "and", "magic", "word", "as", "the", "parameters", "and", "iterates", "the", "timesMade", "properties", "." ]
9b868ea9dd41f4ce931abc7e37b3467a356443cf
https://github.com/kentcdodds/genie/blob/9b868ea9dd41f4ce931abc7e37b3467a356443cf/src/index.js#L902-L908
22,143
kentcdodds/genie
src/index.js
_contextIsDefault
function _contextIsDefault(context) { if (!_isObject(context)) { context = _arrayify(context) } if (_isArray(context) && context.length === 1) { return context[0] === _defaultContext[0] } else if (context.any && context.any.length === 1) { return context.any[0] === _defaultContext[0] } else { return false } }
javascript
function _contextIsDefault(context) { if (!_isObject(context)) { context = _arrayify(context) } if (_isArray(context) && context.length === 1) { return context[0] === _defaultContext[0] } else if (context.any && context.any.length === 1) { return context.any[0] === _defaultContext[0] } else { return false } }
[ "function", "_contextIsDefault", "(", "context", ")", "{", "if", "(", "!", "_isObject", "(", "context", ")", ")", "{", "context", "=", "_arrayify", "(", "context", ")", "}", "if", "(", "_isArray", "(", "context", ")", "&&", "context", ".", "length", "===", "1", ")", "{", "return", "context", "[", "0", "]", "===", "_defaultContext", "[", "0", "]", "}", "else", "if", "(", "context", ".", "any", "&&", "context", ".", "any", ".", "length", "===", "1", ")", "{", "return", "context", ".", "any", "[", "0", "]", "===", "_defaultContext", "[", "0", "]", "}", "else", "{", "return", "false", "}", "}" ]
Returns true if the given context is the default context. @param {string|Array.<string>|context} context @returns {boolean} contextIsDefault @private @examples _contextIsDefault(_defaultContext[0]) // => true _contextIsDefault(_defaultContext) // => true _contextIsDefault(_defaultContext.concat(['1', '2', '3'])) // => true _contextIsDefault('something else') // => false
[ "Returns", "true", "if", "the", "given", "context", "is", "the", "default", "context", "." ]
9b868ea9dd41f4ce931abc7e37b3467a356443cf
https://github.com/kentcdodds/genie/blob/9b868ea9dd41f4ce931abc7e37b3467a356443cf/src/index.js#L921-L932
22,144
kentcdodds/genie
src/index.js
_createSpotInEnteredMagicWords
function _createSpotInEnteredMagicWords(spot, chars) { const firstChar = chars.substring(0, 1) const remainingChars = chars.substring(1) const nextSpot = (spot[firstChar] = spot[firstChar] || {}) if (remainingChars) { return _createSpotInEnteredMagicWords(nextSpot, remainingChars) } else { return nextSpot } }
javascript
function _createSpotInEnteredMagicWords(spot, chars) { const firstChar = chars.substring(0, 1) const remainingChars = chars.substring(1) const nextSpot = (spot[firstChar] = spot[firstChar] || {}) if (remainingChars) { return _createSpotInEnteredMagicWords(nextSpot, remainingChars) } else { return nextSpot } }
[ "function", "_createSpotInEnteredMagicWords", "(", "spot", ",", "chars", ")", "{", "const", "firstChar", "=", "chars", ".", "substring", "(", "0", ",", "1", ")", "const", "remainingChars", "=", "chars", ".", "substring", "(", "1", ")", "const", "nextSpot", "=", "(", "spot", "[", "firstChar", "]", "=", "spot", "[", "firstChar", "]", "||", "{", "}", ")", "if", "(", "remainingChars", ")", "{", "return", "_createSpotInEnteredMagicWords", "(", "nextSpot", ",", "remainingChars", ")", "}", "else", "{", "return", "nextSpot", "}", "}" ]
Recursively creates a new object property if one does not exist for each character in the chars string. @param {object} spot @param {string} chars @returns {object} - the final object. @private
[ "Recursively", "creates", "a", "new", "object", "property", "if", "one", "does", "not", "exist", "for", "each", "character", "in", "the", "chars", "string", "." ]
9b868ea9dd41f4ce931abc7e37b3467a356443cf
https://github.com/kentcdodds/genie/blob/9b868ea9dd41f4ce931abc7e37b3467a356443cf/src/index.js#L1026-L1035
22,145
kentcdodds/genie
src/index.js
_getContextsFromPath
function _getContextsFromPath(path) { const allContexts = { add: [], remove: [], } _each(_pathContexts, pathContext => { let contextAdded = false const contexts = pathContext.contexts const regexes = pathContext.regexes const paths = pathContext.paths _each(regexes, regex => { regex.lastIndex = 0 const matches = regex.exec(path) if (matches && matches.length > 0) { const contextsToAdd = [] _each(contexts, context => { const replacedContext = context.replace( _contextRegex, (match, group) => { return matches[group] }, ) contextsToAdd.push(replacedContext) }) allContexts.add = allContexts.add.concat(contextsToAdd) contextAdded = true } return !contextAdded }) if (!contextAdded) { _each(paths, pathToTry => { if (path === pathToTry) { allContexts.add = allContexts.add.concat(contexts) contextAdded = true } return !contextAdded }) if (!contextAdded) { allContexts.remove = allContexts.remove.concat(contexts) } } }) return allContexts }
javascript
function _getContextsFromPath(path) { const allContexts = { add: [], remove: [], } _each(_pathContexts, pathContext => { let contextAdded = false const contexts = pathContext.contexts const regexes = pathContext.regexes const paths = pathContext.paths _each(regexes, regex => { regex.lastIndex = 0 const matches = regex.exec(path) if (matches && matches.length > 0) { const contextsToAdd = [] _each(contexts, context => { const replacedContext = context.replace( _contextRegex, (match, group) => { return matches[group] }, ) contextsToAdd.push(replacedContext) }) allContexts.add = allContexts.add.concat(contextsToAdd) contextAdded = true } return !contextAdded }) if (!contextAdded) { _each(paths, pathToTry => { if (path === pathToTry) { allContexts.add = allContexts.add.concat(contexts) contextAdded = true } return !contextAdded }) if (!contextAdded) { allContexts.remove = allContexts.remove.concat(contexts) } } }) return allContexts }
[ "function", "_getContextsFromPath", "(", "path", ")", "{", "const", "allContexts", "=", "{", "add", ":", "[", "]", ",", "remove", ":", "[", "]", ",", "}", "_each", "(", "_pathContexts", ",", "pathContext", "=>", "{", "let", "contextAdded", "=", "false", "const", "contexts", "=", "pathContext", ".", "contexts", "const", "regexes", "=", "pathContext", ".", "regexes", "const", "paths", "=", "pathContext", ".", "paths", "_each", "(", "regexes", ",", "regex", "=>", "{", "regex", ".", "lastIndex", "=", "0", "const", "matches", "=", "regex", ".", "exec", "(", "path", ")", "if", "(", "matches", "&&", "matches", ".", "length", ">", "0", ")", "{", "const", "contextsToAdd", "=", "[", "]", "_each", "(", "contexts", ",", "context", "=>", "{", "const", "replacedContext", "=", "context", ".", "replace", "(", "_contextRegex", ",", "(", "match", ",", "group", ")", "=>", "{", "return", "matches", "[", "group", "]", "}", ",", ")", "contextsToAdd", ".", "push", "(", "replacedContext", ")", "}", ")", "allContexts", ".", "add", "=", "allContexts", ".", "add", ".", "concat", "(", "contextsToAdd", ")", "contextAdded", "=", "true", "}", "return", "!", "contextAdded", "}", ")", "if", "(", "!", "contextAdded", ")", "{", "_each", "(", "paths", ",", "pathToTry", "=>", "{", "if", "(", "path", "===", "pathToTry", ")", "{", "allContexts", ".", "add", "=", "allContexts", ".", "add", ".", "concat", "(", "contexts", ")", "contextAdded", "=", "true", "}", "return", "!", "contextAdded", "}", ")", "if", "(", "!", "contextAdded", ")", "{", "allContexts", ".", "remove", "=", "allContexts", ".", "remove", ".", "concat", "(", "contexts", ")", "}", "}", "}", ")", "return", "allContexts", "}" ]
Gets the context paths that should be added based on the given path and the context paths that should be removed based ont he given path @param {string} path @returns {{add: Array, remove: Array}} @private
[ "Gets", "the", "context", "paths", "that", "should", "be", "added", "based", "on", "the", "given", "path", "and", "the", "context", "paths", "that", "should", "be", "removed", "based", "ont", "he", "given", "path" ]
9b868ea9dd41f4ce931abc7e37b3467a356443cf
https://github.com/kentcdodds/genie/blob/9b868ea9dd41f4ce931abc7e37b3467a356443cf/src/index.js#L1072-L1117
22,146
kentcdodds/genie
src/index.js
_getContextsMatchingRegexPathContexts
function _getContextsMatchingRegexPathContexts() { const regexContexts = [] _each(_pathContexts, pathContext => { const contexts = pathContext.contexts _each(contexts, context => { if (_contextRegex.test(context)) { // context string is a regex context const replaceContextRegex = context.replace(_contextRegex, '.+?') _each(_context, currentContext => { if (new RegExp(replaceContextRegex).test(currentContext)) { regexContexts.push(currentContext) } }) } }) }) return regexContexts }
javascript
function _getContextsMatchingRegexPathContexts() { const regexContexts = [] _each(_pathContexts, pathContext => { const contexts = pathContext.contexts _each(contexts, context => { if (_contextRegex.test(context)) { // context string is a regex context const replaceContextRegex = context.replace(_contextRegex, '.+?') _each(_context, currentContext => { if (new RegExp(replaceContextRegex).test(currentContext)) { regexContexts.push(currentContext) } }) } }) }) return regexContexts }
[ "function", "_getContextsMatchingRegexPathContexts", "(", ")", "{", "const", "regexContexts", "=", "[", "]", "_each", "(", "_pathContexts", ",", "pathContext", "=>", "{", "const", "contexts", "=", "pathContext", ".", "contexts", "_each", "(", "contexts", ",", "context", "=>", "{", "if", "(", "_contextRegex", ".", "test", "(", "context", ")", ")", "{", "// context string is a regex context", "const", "replaceContextRegex", "=", "context", ".", "replace", "(", "_contextRegex", ",", "'.+?'", ")", "_each", "(", "_context", ",", "currentContext", "=>", "{", "if", "(", "new", "RegExp", "(", "replaceContextRegex", ")", ".", "test", "(", "currentContext", ")", ")", "{", "regexContexts", ".", "push", "(", "currentContext", ")", "}", "}", ")", "}", "}", ")", "}", ")", "return", "regexContexts", "}" ]
Gets all the pathContext.contexts that are regex contexts and matches those to genie's contexts. Returns all the matching contexts. @returns {Array} @private
[ "Gets", "all", "the", "pathContext", ".", "contexts", "that", "are", "regex", "contexts", "and", "matches", "those", "to", "genie", "s", "contexts", ".", "Returns", "all", "the", "matching", "contexts", "." ]
9b868ea9dd41f4ce931abc7e37b3467a356443cf
https://github.com/kentcdodds/genie/blob/9b868ea9dd41f4ce931abc7e37b3467a356443cf/src/index.js#L1125-L1144
22,147
kentcdodds/genie
src/index.js
_addUniqueItems
function _addUniqueItems(arry, obj) { obj = _arrayify(obj) arry = _arrayify(arry) _each(obj, o => { if (arry.indexOf(o) < 0) { arry.push(o) } }) return arry }
javascript
function _addUniqueItems(arry, obj) { obj = _arrayify(obj) arry = _arrayify(arry) _each(obj, o => { if (arry.indexOf(o) < 0) { arry.push(o) } }) return arry }
[ "function", "_addUniqueItems", "(", "arry", ",", "obj", ")", "{", "obj", "=", "_arrayify", "(", "obj", ")", "arry", "=", "_arrayify", "(", "arry", ")", "_each", "(", "obj", ",", "o", "=>", "{", "if", "(", "arry", ".", "indexOf", "(", "o", ")", "<", "0", ")", "{", "arry", ".", "push", "(", "o", ")", "}", "}", ")", "return", "arry", "}" ]
Adds items to the arry from the obj only if it is not in the arry already @param {Array.<*>} arry @param {*|Array.<*>} obj @returns {Array.<*>} arry @private @examples _addUniqueItems(1, 2) // => [1,2] _addUniqueItems(1, [2,3]) // => [1,2,3] _addUniqueItems([1,2], 3) // => [1,2,3] _addUniqueItems([1,2], [3,4]) // => [1,2,3,4] _addUniqueItems([1,2], [3,1]) // => [1,2,3] _addUniqueItems([1,2], [1,2]) // => [1,2] _addUniqueItems([1,2], [1,2]) // => [1,2] _addUniqueItems([1,2,3], [1,2,1,2,3]) // => [1,2,3]
[ "Adds", "items", "to", "the", "arry", "from", "the", "obj", "only", "if", "it", "is", "not", "in", "the", "arry", "already" ]
9b868ea9dd41f4ce931abc7e37b3467a356443cf
https://github.com/kentcdodds/genie/blob/9b868ea9dd41f4ce931abc7e37b3467a356443cf/src/index.js#L1185-L1194
22,148
kentcdodds/genie
src/index.js
_removeItems
function _removeItems(arry, obj) { arry = _arrayify(arry) obj = _arrayify(obj) let i = 0 while (i < arry.length) { if (_contains(obj, arry[i])) { arry.splice(i, 1) } else { i++ } } return arry }
javascript
function _removeItems(arry, obj) { arry = _arrayify(arry) obj = _arrayify(obj) let i = 0 while (i < arry.length) { if (_contains(obj, arry[i])) { arry.splice(i, 1) } else { i++ } } return arry }
[ "function", "_removeItems", "(", "arry", ",", "obj", ")", "{", "arry", "=", "_arrayify", "(", "arry", ")", "obj", "=", "_arrayify", "(", "obj", ")", "let", "i", "=", "0", "while", "(", "i", "<", "arry", ".", "length", ")", "{", "if", "(", "_contains", "(", "obj", ",", "arry", "[", "i", "]", ")", ")", "{", "arry", ".", "splice", "(", "i", ",", "1", ")", "}", "else", "{", "i", "++", "}", "}", "return", "arry", "}" ]
Removes all instances of items in the given obj from the given arry. @param {Array.<*>} arry @param {*|Array.<*>} obj @returns {Array.<*>} arry @private @examples _removeItems(1, 2) // => [1] _removeItems(1, [2,3]) // => [1] _removeItems([1,2], 3) // => [1,2] _removeItems([1,2], [3,4]) // => [1,2] _removeItems([1,2], [3,1]) // => [2] _removeItems([1,2], [1,2]) // => [] _removeItems([1,2,1,2,3], [2,3]) // => [1,1]
[ "Removes", "all", "instances", "of", "items", "in", "the", "given", "obj", "from", "the", "given", "arry", "." ]
9b868ea9dd41f4ce931abc7e37b3467a356443cf
https://github.com/kentcdodds/genie/blob/9b868ea9dd41f4ce931abc7e37b3467a356443cf/src/index.js#L1212-L1225
22,149
kentcdodds/genie
src/index.js
_arrayContainsNone
function _arrayContainsNone(arry1, arry2) { arry1 = _arrayify(arry1) arry2 = _arrayify(arry2) for (let i = 0; i < arry2.length; i++) { if (_contains(arry1, arry2[i])) { return false } } return true }
javascript
function _arrayContainsNone(arry1, arry2) { arry1 = _arrayify(arry1) arry2 = _arrayify(arry2) for (let i = 0; i < arry2.length; i++) { if (_contains(arry1, arry2[i])) { return false } } return true }
[ "function", "_arrayContainsNone", "(", "arry1", ",", "arry2", ")", "{", "arry1", "=", "_arrayify", "(", "arry1", ")", "arry2", "=", "_arrayify", "(", "arry2", ")", "for", "(", "let", "i", "=", "0", ";", "i", "<", "arry2", ".", "length", ";", "i", "++", ")", "{", "if", "(", "_contains", "(", "arry1", ",", "arry2", "[", "i", "]", ")", ")", "{", "return", "false", "}", "}", "return", "true", "}" ]
Returns true if arry1 does not contain any of arry2's elements @param {*|Array.<*>} arry1 @param {*|Array.<*>} arry2 @returns {boolean} @private
[ "Returns", "true", "if", "arry1", "does", "not", "contain", "any", "of", "arry2", "s", "elements" ]
9b868ea9dd41f4ce931abc7e37b3467a356443cf
https://github.com/kentcdodds/genie/blob/9b868ea9dd41f4ce931abc7e37b3467a356443cf/src/index.js#L1258-L1267
22,150
kentcdodds/genie
src/index.js
_isEmpty
function _isEmpty(obj) { if (_isNullOrUndefined(obj)) { return true } else if (_isArray(obj)) { return obj.length === 0 } else if (_isString(obj)) { return obj === '' } else if (_isPrimitive(obj)) { return false } else if (_isObject(obj)) { return Object.keys(obj).length < 1 } else { return false } }
javascript
function _isEmpty(obj) { if (_isNullOrUndefined(obj)) { return true } else if (_isArray(obj)) { return obj.length === 0 } else if (_isString(obj)) { return obj === '' } else if (_isPrimitive(obj)) { return false } else if (_isObject(obj)) { return Object.keys(obj).length < 1 } else { return false } }
[ "function", "_isEmpty", "(", "obj", ")", "{", "if", "(", "_isNullOrUndefined", "(", "obj", ")", ")", "{", "return", "true", "}", "else", "if", "(", "_isArray", "(", "obj", ")", ")", "{", "return", "obj", ".", "length", "===", "0", "}", "else", "if", "(", "_isString", "(", "obj", ")", ")", "{", "return", "obj", "===", "''", "}", "else", "if", "(", "_isPrimitive", "(", "obj", ")", ")", "{", "return", "false", "}", "else", "if", "(", "_isObject", "(", "obj", ")", ")", "{", "return", "Object", ".", "keys", "(", "obj", ")", ".", "length", "<", "1", "}", "else", "{", "return", "false", "}", "}" ]
Whether the given object is empty. @param obj @returns {boolean} @private @examples _isEmpty() // => true _isEmpty(null) // => true _isEmpty(undefined) // => true _isEmpty('') // => true _isEmpty({}) // => true _isEmpty([]) // => true _isEmpty(1) // => false _isEmpty('a') // => false _isEmpty(['a', 'b']) // => false _isEmpty({a: 'b'}) // => false
[ "Whether", "the", "given", "object", "is", "empty", "." ]
9b868ea9dd41f4ce931abc7e37b3467a356443cf
https://github.com/kentcdodds/genie/blob/9b868ea9dd41f4ce931abc7e37b3467a356443cf/src/index.js#L1315-L1329
22,151
kentcdodds/genie
src/index.js
_eachArrayReverse
function _eachArrayReverse(arry, fn) { let ret = true for (let i = arry.length - 1; i >= 0; i--) { ret = fn(arry[i], i, arry) if (ret === false) { break } } return ret }
javascript
function _eachArrayReverse(arry, fn) { let ret = true for (let i = arry.length - 1; i >= 0; i--) { ret = fn(arry[i], i, arry) if (ret === false) { break } } return ret }
[ "function", "_eachArrayReverse", "(", "arry", ",", "fn", ")", "{", "let", "ret", "=", "true", "for", "(", "let", "i", "=", "arry", ".", "length", "-", "1", ";", "i", ">=", "0", ";", "i", "--", ")", "{", "ret", "=", "fn", "(", "arry", "[", "i", "]", ",", "i", ",", "arry", ")", "if", "(", "ret", "===", "false", ")", "{", "break", "}", "}", "return", "ret", "}" ]
Iterates through the array and calls the given function in reverse order. @param {Array.<*>} arry @param {eachCallback} fn @returns {boolean} - whether the loop broke early @private
[ "Iterates", "through", "the", "array", "and", "calls", "the", "given", "function", "in", "reverse", "order", "." ]
9b868ea9dd41f4ce931abc7e37b3467a356443cf
https://github.com/kentcdodds/genie/blob/9b868ea9dd41f4ce931abc7e37b3467a356443cf/src/index.js#L1389-L1398
22,152
kentcdodds/genie
src/index.js
_eachArrayForward
function _eachArrayForward(arry, fn) { let ret = true for (let i = 0; i < arry.length; i++) { ret = fn(arry[i], i, arry) if (ret === false) { break } } return ret }
javascript
function _eachArrayForward(arry, fn) { let ret = true for (let i = 0; i < arry.length; i++) { ret = fn(arry[i], i, arry) if (ret === false) { break } } return ret }
[ "function", "_eachArrayForward", "(", "arry", ",", "fn", ")", "{", "let", "ret", "=", "true", "for", "(", "let", "i", "=", "0", ";", "i", "<", "arry", ".", "length", ";", "i", "++", ")", "{", "ret", "=", "fn", "(", "arry", "[", "i", "]", ",", "i", ",", "arry", ")", "if", "(", "ret", "===", "false", ")", "{", "break", "}", "}", "return", "ret", "}" ]
Iterates through the array and calls the given function @param {Array.<*>} arry @param {Function} fn @returns {boolean} - whether the loop broke early @private
[ "Iterates", "through", "the", "array", "and", "calls", "the", "given", "function" ]
9b868ea9dd41f4ce931abc7e37b3467a356443cf
https://github.com/kentcdodds/genie/blob/9b868ea9dd41f4ce931abc7e37b3467a356443cf/src/index.js#L1407-L1416
22,153
kentcdodds/genie
src/index.js
_eachProperty
function _eachProperty(obj, fn) { let ret = true for (const prop in obj) { if (obj.hasOwnProperty(prop)) { ret = fn(obj[prop], prop, obj) if (ret === false) { break } } } return ret }
javascript
function _eachProperty(obj, fn) { let ret = true for (const prop in obj) { if (obj.hasOwnProperty(prop)) { ret = fn(obj[prop], prop, obj) if (ret === false) { break } } } return ret }
[ "function", "_eachProperty", "(", "obj", ",", "fn", ")", "{", "let", "ret", "=", "true", "for", "(", "const", "prop", "in", "obj", ")", "{", "if", "(", "obj", ".", "hasOwnProperty", "(", "prop", ")", ")", "{", "ret", "=", "fn", "(", "obj", "[", "prop", "]", ",", "prop", ",", "obj", ")", "if", "(", "ret", "===", "false", ")", "{", "break", "}", "}", "}", "return", "ret", "}" ]
Iterates through each property and calls the callback if the object hasOwnProperty. @param {object} obj @param {Function} fn @returns {boolean} @private
[ "Iterates", "through", "each", "property", "and", "calls", "the", "callback", "if", "the", "object", "hasOwnProperty", "." ]
9b868ea9dd41f4ce931abc7e37b3467a356443cf
https://github.com/kentcdodds/genie/blob/9b868ea9dd41f4ce931abc7e37b3467a356443cf/src/index.js#L1426-L1437
22,154
kentcdodds/genie
src/index.js
_updateWishesWithOptions
function _updateWishesWithOptions(opts) { if (opts.wishes) { if (opts.noWishMerge) { _wishes = opts.wishes } else { mergeWishes(opts.wishes) } } }
javascript
function _updateWishesWithOptions(opts) { if (opts.wishes) { if (opts.noWishMerge) { _wishes = opts.wishes } else { mergeWishes(opts.wishes) } } }
[ "function", "_updateWishesWithOptions", "(", "opts", ")", "{", "if", "(", "opts", ".", "wishes", ")", "{", "if", "(", "opts", ".", "noWishMerge", ")", "{", "_wishes", "=", "opts", ".", "wishes", "}", "else", "{", "mergeWishes", "(", "opts", ".", "wishes", ")", "}", "}", "}" ]
If wishes are present, will update them based on options given. @param {object} opts @private
[ "If", "wishes", "are", "present", "will", "update", "them", "based", "on", "options", "given", "." ]
9b868ea9dd41f4ce931abc7e37b3467a356443cf
https://github.com/kentcdodds/genie/blob/9b868ea9dd41f4ce931abc7e37b3467a356443cf/src/index.js#L1658-L1666
22,155
kentcdodds/genie
src/index.js
context
function context(newContext) { if (!_isUndefined(newContext)) { _previousContext = _context if (!_isArray(newContext)) { newContext = [newContext] } _context = newContext } return _context }
javascript
function context(newContext) { if (!_isUndefined(newContext)) { _previousContext = _context if (!_isArray(newContext)) { newContext = [newContext] } _context = newContext } return _context }
[ "function", "context", "(", "newContext", ")", "{", "if", "(", "!", "_isUndefined", "(", "newContext", ")", ")", "{", "_previousContext", "=", "_context", "if", "(", "!", "_isArray", "(", "newContext", ")", ")", "{", "newContext", "=", "[", "newContext", "]", "}", "_context", "=", "newContext", "}", "return", "_context", "}" ]
Set's then returns genie's current context. If no context is provided, simply acts as getter. If a context is provided, genie's previous context is set to the context before it is assigned to the given context. @param {string|Array.<string>} newContext The context to set genie's context to. @returns {Array.<string>} The new context @public
[ "Set", "s", "then", "returns", "genie", "s", "current", "context", ".", "If", "no", "context", "is", "provided", "simply", "acts", "as", "getter", ".", "If", "a", "context", "is", "provided", "genie", "s", "previous", "context", "is", "set", "to", "the", "context", "before", "it", "is", "assigned", "to", "the", "given", "context", "." ]
9b868ea9dd41f4ce931abc7e37b3467a356443cf
https://github.com/kentcdodds/genie/blob/9b868ea9dd41f4ce931abc7e37b3467a356443cf/src/index.js#L1711-L1720
22,156
kentcdodds/genie
src/index.js
addContext
function addContext(newContext) { if (newContext && newContext.length) { _previousContext = _context _addUniqueItems(_context, newContext) } return _context }
javascript
function addContext(newContext) { if (newContext && newContext.length) { _previousContext = _context _addUniqueItems(_context, newContext) } return _context }
[ "function", "addContext", "(", "newContext", ")", "{", "if", "(", "newContext", "&&", "newContext", ".", "length", ")", "{", "_previousContext", "=", "_context", "_addUniqueItems", "(", "_context", ",", "newContext", ")", "}", "return", "_context", "}" ]
Adds the new context to genie's current context. Genie's context will maintain uniqueness, so don't worry about overloading genie's context with duplicates. @param {string|Array.<string>} newContext The context to add @returns {Array} Genie's new context @public
[ "Adds", "the", "new", "context", "to", "genie", "s", "current", "context", ".", "Genie", "s", "context", "will", "maintain", "uniqueness", "so", "don", "t", "worry", "about", "overloading", "genie", "s", "context", "with", "duplicates", "." ]
9b868ea9dd41f4ce931abc7e37b3467a356443cf
https://github.com/kentcdodds/genie/blob/9b868ea9dd41f4ce931abc7e37b3467a356443cf/src/index.js#L1731-L1737
22,157
kentcdodds/genie
src/index.js
removeContext
function removeContext(contextToRemove) { if (contextToRemove && contextToRemove.length) { _previousContext = _context _removeItems(_context, contextToRemove) if (_isEmpty(context)) { _context = _defaultContext } } return _context }
javascript
function removeContext(contextToRemove) { if (contextToRemove && contextToRemove.length) { _previousContext = _context _removeItems(_context, contextToRemove) if (_isEmpty(context)) { _context = _defaultContext } } return _context }
[ "function", "removeContext", "(", "contextToRemove", ")", "{", "if", "(", "contextToRemove", "&&", "contextToRemove", ".", "length", ")", "{", "_previousContext", "=", "_context", "_removeItems", "(", "_context", ",", "contextToRemove", ")", "if", "(", "_isEmpty", "(", "context", ")", ")", "{", "_context", "=", "_defaultContext", "}", "}", "return", "_context", "}" ]
Removes the given context @param {string|Array.<string>} contextToRemove The context to remove @returns {Array.<string>} Genie's new context @public
[ "Removes", "the", "given", "context" ]
9b868ea9dd41f4ce931abc7e37b3467a356443cf
https://github.com/kentcdodds/genie/blob/9b868ea9dd41f4ce931abc7e37b3467a356443cf/src/index.js#L1745-L1754
22,158
kentcdodds/genie
src/index.js
updatePathContext
function updatePathContext(path, noDeregister) { if (path) { const allContexts = _getContextsFromPath(path) const contextsToAdd = allContexts.add let contextsToRemove = _getContextsMatchingRegexPathContexts() contextsToRemove = contextsToRemove.concat(allContexts.remove) removeContext(contextsToRemove) if (!noDeregister) { // There's no way to prevent users of genie from adding wishes that already exist in genie // so we're completely removing them here deregisterWishesWithContext(contextsToRemove) } addContext(contextsToAdd) } return _context }
javascript
function updatePathContext(path, noDeregister) { if (path) { const allContexts = _getContextsFromPath(path) const contextsToAdd = allContexts.add let contextsToRemove = _getContextsMatchingRegexPathContexts() contextsToRemove = contextsToRemove.concat(allContexts.remove) removeContext(contextsToRemove) if (!noDeregister) { // There's no way to prevent users of genie from adding wishes that already exist in genie // so we're completely removing them here deregisterWishesWithContext(contextsToRemove) } addContext(contextsToAdd) } return _context }
[ "function", "updatePathContext", "(", "path", ",", "noDeregister", ")", "{", "if", "(", "path", ")", "{", "const", "allContexts", "=", "_getContextsFromPath", "(", "path", ")", "const", "contextsToAdd", "=", "allContexts", ".", "add", "let", "contextsToRemove", "=", "_getContextsMatchingRegexPathContexts", "(", ")", "contextsToRemove", "=", "contextsToRemove", ".", "concat", "(", "allContexts", ".", "remove", ")", "removeContext", "(", "contextsToRemove", ")", "if", "(", "!", "noDeregister", ")", "{", "// There's no way to prevent users of genie from adding wishes that already exist in genie", "// so we're completely removing them here", "deregisterWishesWithContext", "(", "contextsToRemove", ")", "}", "addContext", "(", "contextsToAdd", ")", "}", "return", "_context", "}" ]
Updates genie's context based on the given path @param {string} path the path to match @param {boolean} [noDeregister] Do not deregister wishes which are no longer in context @returns {Array.<string>} The new context @public
[ "Updates", "genie", "s", "context", "based", "on", "the", "given", "path" ]
9b868ea9dd41f4ce931abc7e37b3467a356443cf
https://github.com/kentcdodds/genie/blob/9b868ea9dd41f4ce931abc7e37b3467a356443cf/src/index.js#L1782-L1800
22,159
kentcdodds/genie
src/index.js
addPathContext
function addPathContext(pathContexts) { _each(pathContexts, pathContext => { if (pathContext.paths) { pathContext.paths = _arrayify(pathContext.paths) } if (pathContext.regexes) { pathContext.regexes = _arrayify(pathContext.regexes) } if (pathContext.contexts) { pathContext.contexts = _arrayify(pathContext.contexts) } }) _addUniqueItems(_pathContexts, pathContexts) return _pathContexts }
javascript
function addPathContext(pathContexts) { _each(pathContexts, pathContext => { if (pathContext.paths) { pathContext.paths = _arrayify(pathContext.paths) } if (pathContext.regexes) { pathContext.regexes = _arrayify(pathContext.regexes) } if (pathContext.contexts) { pathContext.contexts = _arrayify(pathContext.contexts) } }) _addUniqueItems(_pathContexts, pathContexts) return _pathContexts }
[ "function", "addPathContext", "(", "pathContexts", ")", "{", "_each", "(", "pathContexts", ",", "pathContext", "=>", "{", "if", "(", "pathContext", ".", "paths", ")", "{", "pathContext", ".", "paths", "=", "_arrayify", "(", "pathContext", ".", "paths", ")", "}", "if", "(", "pathContext", ".", "regexes", ")", "{", "pathContext", ".", "regexes", "=", "_arrayify", "(", "pathContext", ".", "regexes", ")", "}", "if", "(", "pathContext", ".", "contexts", ")", "{", "pathContext", ".", "contexts", "=", "_arrayify", "(", "pathContext", ".", "contexts", ")", "}", "}", ")", "_addUniqueItems", "(", "_pathContexts", ",", "pathContexts", ")", "return", "_pathContexts", "}" ]
Add a path context to genie's pathContexts @param {Array.<PathContext>} pathContexts The path context to add @returns {Array.<PathContext>} The new path contexts @public
[ "Add", "a", "path", "context", "to", "genie", "s", "pathContexts" ]
9b868ea9dd41f4ce931abc7e37b3467a356443cf
https://github.com/kentcdodds/genie/blob/9b868ea9dd41f4ce931abc7e37b3467a356443cf/src/index.js#L1808-L1824
22,160
apigee-127/swagger-test-templates
index.js
setPathParamsFromArray
function setPathParamsFromArray(data, config, idx) { // only write parameters if they are not already defined in config if (data.requestData === undefined || config.pathParams) { return data; } // if we have requestData, fill the path params accordingly var mockParameters = {}; data.pathParameters.forEach(function(parameter) { // find the mock data for this parameter name mockParameters[parameter.name] = data.requestData.filter(function(mock) { return mock.hasOwnProperty(parameter.name); })[idx][parameter.name]; }); data.pathParams = mockParameters; return data; }
javascript
function setPathParamsFromArray(data, config, idx) { // only write parameters if they are not already defined in config if (data.requestData === undefined || config.pathParams) { return data; } // if we have requestData, fill the path params accordingly var mockParameters = {}; data.pathParameters.forEach(function(parameter) { // find the mock data for this parameter name mockParameters[parameter.name] = data.requestData.filter(function(mock) { return mock.hasOwnProperty(parameter.name); })[idx][parameter.name]; }); data.pathParams = mockParameters; return data; }
[ "function", "setPathParamsFromArray", "(", "data", ",", "config", ",", "idx", ")", "{", "// only write parameters if they are not already defined in config", "if", "(", "data", ".", "requestData", "===", "undefined", "||", "config", ".", "pathParams", ")", "{", "return", "data", ";", "}", "// if we have requestData, fill the path params accordingly", "var", "mockParameters", "=", "{", "}", ";", "data", ".", "pathParameters", ".", "forEach", "(", "function", "(", "parameter", ")", "{", "// find the mock data for this parameter name", "mockParameters", "[", "parameter", ".", "name", "]", "=", "data", ".", "requestData", ".", "filter", "(", "function", "(", "mock", ")", "{", "return", "mock", ".", "hasOwnProperty", "(", "parameter", ".", "name", ")", ";", "}", ")", "[", "idx", "]", "[", "parameter", ".", "name", "]", ";", "}", ")", ";", "data", ".", "pathParams", "=", "mockParameters", ";", "return", "data", ";", "}" ]
Populate path params from request data array @private @param {json} data Generated Data @param {json} config configuration for testGen @param {int} idx Index of request for response @returns {json} return all the properties information
[ "Populate", "path", "params", "from", "request", "data", "array" ]
3851930b9cc3ff946915990271ebcc7b7f29a32a
https://github.com/apigee-127/swagger-test-templates/blob/3851930b9cc3ff946915990271ebcc7b7f29a32a/index.js#L234-L250
22,161
apigee-127/swagger-test-templates
index.js
filterOutOptionalQueryParams
function filterOutOptionalQueryParams(data) { data.queryParameters = data.queryParameters.filter(function(queryParam) { // Let's be conservative and treat params without explicit required field as not-optional var optional = queryParam.required !== undefined && !queryParam.required; var dataProvided = data.requestParameters.hasOwnProperty(queryParam.name); return !optional || dataProvided; }); return data; }
javascript
function filterOutOptionalQueryParams(data) { data.queryParameters = data.queryParameters.filter(function(queryParam) { // Let's be conservative and treat params without explicit required field as not-optional var optional = queryParam.required !== undefined && !queryParam.required; var dataProvided = data.requestParameters.hasOwnProperty(queryParam.name); return !optional || dataProvided; }); return data; }
[ "function", "filterOutOptionalQueryParams", "(", "data", ")", "{", "data", ".", "queryParameters", "=", "data", ".", "queryParameters", ".", "filter", "(", "function", "(", "queryParam", ")", "{", "// Let's be conservative and treat params without explicit required field as not-optional", "var", "optional", "=", "queryParam", ".", "required", "!==", "undefined", "&&", "!", "queryParam", ".", "required", ";", "var", "dataProvided", "=", "data", ".", "requestParameters", ".", "hasOwnProperty", "(", "queryParam", ".", "name", ")", ";", "return", "!", "optional", "||", "dataProvided", ";", "}", ")", ";", "return", "data", ";", "}" ]
Filter out optional query parameters with no value provided in request data @private @param {json} data Generated Data @returns {json} return all the properties information
[ "Filter", "out", "optional", "query", "parameters", "with", "no", "value", "provided", "in", "request", "data" ]
3851930b9cc3ff946915990271ebcc7b7f29a32a
https://github.com/apigee-127/swagger-test-templates/blob/3851930b9cc3ff946915990271ebcc7b7f29a32a/index.js#L258-L267
22,162
apigee-127/swagger-test-templates
lib/helpers.js
validateResponse
function validateResponse(type, noSchema, options) { if (arguments.length < 3) { throw new Error('Handlebars Helper \'validateResponse\'' + 'needs 2 parameters'); } if (!noSchema && mediaTypeContainsJson(type)) { return options.fn(this); } else { return options.inverse(this); } }
javascript
function validateResponse(type, noSchema, options) { if (arguments.length < 3) { throw new Error('Handlebars Helper \'validateResponse\'' + 'needs 2 parameters'); } if (!noSchema && mediaTypeContainsJson(type)) { return options.fn(this); } else { return options.inverse(this); } }
[ "function", "validateResponse", "(", "type", ",", "noSchema", ",", "options", ")", "{", "if", "(", "arguments", ".", "length", "<", "3", ")", "{", "throw", "new", "Error", "(", "'Handlebars Helper \\'validateResponse\\''", "+", "'needs 2 parameters'", ")", ";", "}", "if", "(", "!", "noSchema", "&&", "mediaTypeContainsJson", "(", "type", ")", ")", "{", "return", "options", ".", "fn", "(", "this", ")", ";", "}", "else", "{", "return", "options", ".", "inverse", "(", "this", ")", ";", "}", "}" ]
determines if content types are able to be validated @param {string} type content type to be evaluated @param {boolean} noSchema whether or not there is a defined schema @param {Object} options handlebars built-in options @returns {boolean} whether or not the content can be validated
[ "determines", "if", "content", "types", "are", "able", "to", "be", "validated" ]
3851930b9cc3ff946915990271ebcc7b7f29a32a
https://github.com/apigee-127/swagger-test-templates/blob/3851930b9cc3ff946915990271ebcc7b7f29a32a/lib/helpers.js#L62-L74
22,163
apigee-127/swagger-test-templates
lib/helpers.js
length
function length(description) { if (arguments.length < 2) { throw new Error('Handlebar Helper \'length\'' + ' needs 1 parameter'); } if ((typeof description) !== 'string') { throw new TypeError('Handlebars Helper \'length\'' + 'requires path to be a string'); } var desc = description; if (len !== -1) { description = strObj(description).truncate(len - 50).s; } return jsStringEscape(description); }
javascript
function length(description) { if (arguments.length < 2) { throw new Error('Handlebar Helper \'length\'' + ' needs 1 parameter'); } if ((typeof description) !== 'string') { throw new TypeError('Handlebars Helper \'length\'' + 'requires path to be a string'); } var desc = description; if (len !== -1) { description = strObj(description).truncate(len - 50).s; } return jsStringEscape(description); }
[ "function", "length", "(", "description", ")", "{", "if", "(", "arguments", ".", "length", "<", "2", ")", "{", "throw", "new", "Error", "(", "'Handlebar Helper \\'length\\''", "+", "' needs 1 parameter'", ")", ";", "}", "if", "(", "(", "typeof", "description", ")", "!==", "'string'", ")", "{", "throw", "new", "TypeError", "(", "'Handlebars Helper \\'length\\''", "+", "'requires path to be a string'", ")", ";", "}", "var", "desc", "=", "description", ";", "if", "(", "len", "!==", "-", "1", ")", "{", "description", "=", "strObj", "(", "description", ")", ".", "truncate", "(", "len", "-", "50", ")", ".", "s", ";", "}", "return", "jsStringEscape", "(", "description", ")", ";", "}" ]
split the long description into multiple lines @param {string} description request description to be splitted @returns {string} multiple lines
[ "split", "the", "long", "description", "into", "multiple", "lines" ]
3851930b9cc3ff946915990271ebcc7b7f29a32a
https://github.com/apigee-127/swagger-test-templates/blob/3851930b9cc3ff946915990271ebcc7b7f29a32a/lib/helpers.js#L177-L194
22,164
covenanttechnologysolutions/connectwise-rest
src/utils/Callback.js
verifyMessage
function verifyMessage(callbackBody, contentSignature, signingKey) { const hash = crypto.createHash('sha256').update(signingKey).digest(); const hmac = crypto.createHmac('sha256', hash); return contentSignature === hmac.update(JSON.stringify(callbackBody)).digest('base64'); }
javascript
function verifyMessage(callbackBody, contentSignature, signingKey) { const hash = crypto.createHash('sha256').update(signingKey).digest(); const hmac = crypto.createHmac('sha256', hash); return contentSignature === hmac.update(JSON.stringify(callbackBody)).digest('base64'); }
[ "function", "verifyMessage", "(", "callbackBody", ",", "contentSignature", ",", "signingKey", ")", "{", "const", "hash", "=", "crypto", ".", "createHash", "(", "'sha256'", ")", ".", "update", "(", "signingKey", ")", ".", "digest", "(", ")", ";", "const", "hmac", "=", "crypto", ".", "createHmac", "(", "'sha256'", ",", "hash", ")", ";", "return", "contentSignature", "===", "hmac", ".", "update", "(", "JSON", ".", "stringify", "(", "callbackBody", ")", ")", ".", "digest", "(", "'base64'", ")", ";", "}" ]
Validate a callback body against signed key @param {CallbackPayload} callbackBody @param {string} contentSignature @param {string} signingKey @returns {boolean}
[ "Validate", "a", "callback", "body", "against", "signed", "key" ]
311e4c78014643f325386f5f596f0ee744c36a3b
https://github.com/covenanttechnologysolutions/connectwise-rest/blob/311e4c78014643f325386f5f596f0ee744c36a3b/src/utils/Callback.js#L64-L69
22,165
freedomjs/freedom
demo/datachannels/chat.js
function (dispatchEvents, name) { this.dispatchEvent = dispatchEvents; this.name = name; this.connection = freedom['core.rtcpeerconnection'](); this.connection.on(function (type, msg) { if (type === 'onsignalingstatechange' || type === 'onnegotiationneeded' || type === 'oniceconnectionstatechange') { this.dispatchEvent('message', '<small style="color:gray">' + type + '</small>'); } else if (type === 'onicecandidate') { if (msg) { this.dispatchEvent('ice', JSON.stringify(msg)); } this.dispatchEvent('message', '<small style="color:lightgray">Ice Candidate Produced</small>'); } else if (type === 'ondatachannel') { this.dispatchEvent('message', '<small style="color:blue">Data Channel Ready [Recipient]</small>'); this.channel = freedom['core.rtcdatachannel'](msg.channel); this.channel.on(this.onDataChannelMsg.bind(this)); } else { this.dispatchEvent('message', JSON.stringify({type: type, msg: msg})); } }.bind(this)); }
javascript
function (dispatchEvents, name) { this.dispatchEvent = dispatchEvents; this.name = name; this.connection = freedom['core.rtcpeerconnection'](); this.connection.on(function (type, msg) { if (type === 'onsignalingstatechange' || type === 'onnegotiationneeded' || type === 'oniceconnectionstatechange') { this.dispatchEvent('message', '<small style="color:gray">' + type + '</small>'); } else if (type === 'onicecandidate') { if (msg) { this.dispatchEvent('ice', JSON.stringify(msg)); } this.dispatchEvent('message', '<small style="color:lightgray">Ice Candidate Produced</small>'); } else if (type === 'ondatachannel') { this.dispatchEvent('message', '<small style="color:blue">Data Channel Ready [Recipient]</small>'); this.channel = freedom['core.rtcdatachannel'](msg.channel); this.channel.on(this.onDataChannelMsg.bind(this)); } else { this.dispatchEvent('message', JSON.stringify({type: type, msg: msg})); } }.bind(this)); }
[ "function", "(", "dispatchEvents", ",", "name", ")", "{", "this", ".", "dispatchEvent", "=", "dispatchEvents", ";", "this", ".", "name", "=", "name", ";", "this", ".", "connection", "=", "freedom", "[", "'core.rtcpeerconnection'", "]", "(", ")", ";", "this", ".", "connection", ".", "on", "(", "function", "(", "type", ",", "msg", ")", "{", "if", "(", "type", "===", "'onsignalingstatechange'", "||", "type", "===", "'onnegotiationneeded'", "||", "type", "===", "'oniceconnectionstatechange'", ")", "{", "this", ".", "dispatchEvent", "(", "'message'", ",", "'<small style=\"color:gray\">'", "+", "type", "+", "'</small>'", ")", ";", "}", "else", "if", "(", "type", "===", "'onicecandidate'", ")", "{", "if", "(", "msg", ")", "{", "this", ".", "dispatchEvent", "(", "'ice'", ",", "JSON", ".", "stringify", "(", "msg", ")", ")", ";", "}", "this", ".", "dispatchEvent", "(", "'message'", ",", "'<small style=\"color:lightgray\">Ice Candidate Produced</small>'", ")", ";", "}", "else", "if", "(", "type", "===", "'ondatachannel'", ")", "{", "this", ".", "dispatchEvent", "(", "'message'", ",", "'<small style=\"color:blue\">Data Channel Ready [Recipient]</small>'", ")", ";", "this", ".", "channel", "=", "freedom", "[", "'core.rtcdatachannel'", "]", "(", "msg", ".", "channel", ")", ";", "this", ".", "channel", ".", "on", "(", "this", ".", "onDataChannelMsg", ".", "bind", "(", "this", ")", ")", ";", "}", "else", "{", "this", ".", "dispatchEvent", "(", "'message'", ",", "JSON", ".", "stringify", "(", "{", "type", ":", "type", ",", "msg", ":", "msg", "}", ")", ")", ";", "}", "}", ".", "bind", "(", "this", ")", ")", ";", "}" ]
This is the root module of the datachannel freedom.js demo. It runs in an isolated thread with its own namespace, peerconnection and datachannel objects are provided through freedom.
[ "This", "is", "the", "root", "module", "of", "the", "datachannel", "freedom", ".", "js", "demo", ".", "It", "runs", "in", "an", "isolated", "thread", "with", "its", "own", "namespace", "peerconnection", "and", "datachannel", "objects", "are", "provided", "through", "freedom", "." ]
9638e840aec9598c4d60383ed22444c525aefbf5
https://github.com/freedomjs/freedom/blob/9638e840aec9598c4d60383ed22444c525aefbf5/demo/datachannels/chat.js#L11-L33
22,166
freedomjs/freedom
providers/core/core.peerconnection.js
PeerConnection
function PeerConnection(portModule, dispatchEvent, RTCPeerConnection, RTCSessionDescription, RTCIceCandidate) { // Channel for emitting events to consumer. this.dispatchEvent = dispatchEvent; // a (hopefully unique) ID for debugging. this.peerName = "p" + Math.random(); // This is the portApp (defined in freedom/src/port-app.js). A way to speak // to freedom. this.freedomModule = portModule.module; // For tests we may mock out the PeerConnection and // SessionDescription implementations this.RTCPeerConnection = RTCPeerConnection; this.RTCSessionDescription = RTCSessionDescription; this.RTCIceCandidate = RTCIceCandidate; // This is the a channel to send signalling messages. this.signallingChannel = null; // The DataPeer object for talking to the peer. this.peer = null; // The Core object for managing channels. this.freedomModule.once('core', function (Core) { this.core = new Core(); }.bind(this)); this.freedomModule.emit(this.freedomModule.controlChannel, { type: 'core request delegated to peerconnection', request: 'core' }); }
javascript
function PeerConnection(portModule, dispatchEvent, RTCPeerConnection, RTCSessionDescription, RTCIceCandidate) { // Channel for emitting events to consumer. this.dispatchEvent = dispatchEvent; // a (hopefully unique) ID for debugging. this.peerName = "p" + Math.random(); // This is the portApp (defined in freedom/src/port-app.js). A way to speak // to freedom. this.freedomModule = portModule.module; // For tests we may mock out the PeerConnection and // SessionDescription implementations this.RTCPeerConnection = RTCPeerConnection; this.RTCSessionDescription = RTCSessionDescription; this.RTCIceCandidate = RTCIceCandidate; // This is the a channel to send signalling messages. this.signallingChannel = null; // The DataPeer object for talking to the peer. this.peer = null; // The Core object for managing channels. this.freedomModule.once('core', function (Core) { this.core = new Core(); }.bind(this)); this.freedomModule.emit(this.freedomModule.controlChannel, { type: 'core request delegated to peerconnection', request: 'core' }); }
[ "function", "PeerConnection", "(", "portModule", ",", "dispatchEvent", ",", "RTCPeerConnection", ",", "RTCSessionDescription", ",", "RTCIceCandidate", ")", "{", "// Channel for emitting events to consumer.", "this", ".", "dispatchEvent", "=", "dispatchEvent", ";", "// a (hopefully unique) ID for debugging.", "this", ".", "peerName", "=", "\"p\"", "+", "Math", ".", "random", "(", ")", ";", "// This is the portApp (defined in freedom/src/port-app.js). A way to speak", "// to freedom.", "this", ".", "freedomModule", "=", "portModule", ".", "module", ";", "// For tests we may mock out the PeerConnection and", "// SessionDescription implementations", "this", ".", "RTCPeerConnection", "=", "RTCPeerConnection", ";", "this", ".", "RTCSessionDescription", "=", "RTCSessionDescription", ";", "this", ".", "RTCIceCandidate", "=", "RTCIceCandidate", ";", "// This is the a channel to send signalling messages.", "this", ".", "signallingChannel", "=", "null", ";", "// The DataPeer object for talking to the peer.", "this", ".", "peer", "=", "null", ";", "// The Core object for managing channels.", "this", ".", "freedomModule", ".", "once", "(", "'core'", ",", "function", "(", "Core", ")", "{", "this", ".", "core", "=", "new", "Core", "(", ")", ";", "}", ".", "bind", "(", "this", ")", ")", ";", "this", ".", "freedomModule", ".", "emit", "(", "this", ".", "freedomModule", ".", "controlChannel", ",", "{", "type", ":", "'core request delegated to peerconnection'", ",", "request", ":", "'core'", "}", ")", ";", "}" ]
_signallingChannel is a channel for emitting events back to the freedom Hub.
[ "_signallingChannel", "is", "a", "channel", "for", "emitting", "events", "back", "to", "the", "freedom", "Hub", "." ]
9638e840aec9598c4d60383ed22444c525aefbf5
https://github.com/freedomjs/freedom/blob/9638e840aec9598c4d60383ed22444c525aefbf5/providers/core/core.peerconnection.js#L336-L369
22,167
freedomjs/freedom
providers/core/core.peerconnection.js
function (dataChannel, info, event) { if (event.data instanceof ArrayBuffer) { self.dispatchEvent('onReceived', { 'channelLabel': info.label, 'buffer': event.data }); } else if (event.data instanceof Blob) { self.dispatchEvent('onReceived', { 'channelLabel': info.label, 'binary': event.data }); } else if (typeof (event.data) === 'string') { self.dispatchEvent('onReceived', { 'channelLabel': info.label, 'text': event.data }); } }
javascript
function (dataChannel, info, event) { if (event.data instanceof ArrayBuffer) { self.dispatchEvent('onReceived', { 'channelLabel': info.label, 'buffer': event.data }); } else if (event.data instanceof Blob) { self.dispatchEvent('onReceived', { 'channelLabel': info.label, 'binary': event.data }); } else if (typeof (event.data) === 'string') { self.dispatchEvent('onReceived', { 'channelLabel': info.label, 'text': event.data }); } }
[ "function", "(", "dataChannel", ",", "info", ",", "event", ")", "{", "if", "(", "event", ".", "data", "instanceof", "ArrayBuffer", ")", "{", "self", ".", "dispatchEvent", "(", "'onReceived'", ",", "{", "'channelLabel'", ":", "info", ".", "label", ",", "'buffer'", ":", "event", ".", "data", "}", ")", ";", "}", "else", "if", "(", "event", ".", "data", "instanceof", "Blob", ")", "{", "self", ".", "dispatchEvent", "(", "'onReceived'", ",", "{", "'channelLabel'", ":", "info", ".", "label", ",", "'binary'", ":", "event", ".", "data", "}", ")", ";", "}", "else", "if", "(", "typeof", "(", "event", ".", "data", ")", "===", "'string'", ")", "{", "self", ".", "dispatchEvent", "(", "'onReceived'", ",", "{", "'channelLabel'", ":", "info", ".", "label", ",", "'text'", ":", "event", ".", "data", "}", ")", ";", "}", "}" ]
Default on real message prints it to console.
[ "Default", "on", "real", "message", "prints", "it", "to", "console", "." ]
9638e840aec9598c4d60383ed22444c525aefbf5
https://github.com/freedomjs/freedom/blob/9638e840aec9598c4d60383ed22444c525aefbf5/providers/core/core.peerconnection.js#L399-L416
22,168
freedomjs/freedom
providers/core/core.peerconnection.js
function (dataChannel, info, err) { console.error(dataChannel.peerName + ": dataChannel(" + dataChannel.dataChannel.label + "): error: ", err); }
javascript
function (dataChannel, info, err) { console.error(dataChannel.peerName + ": dataChannel(" + dataChannel.dataChannel.label + "): error: ", err); }
[ "function", "(", "dataChannel", ",", "info", ",", "err", ")", "{", "console", ".", "error", "(", "dataChannel", ".", "peerName", "+", "\": dataChannel(\"", "+", "dataChannel", ".", "dataChannel", ".", "label", "+", "\"): error: \"", ",", "err", ")", ";", "}" ]
Default on error, prints it.
[ "Default", "on", "error", "prints", "it", "." ]
9638e840aec9598c4d60383ed22444c525aefbf5
https://github.com/freedomjs/freedom/blob/9638e840aec9598c4d60383ed22444c525aefbf5/providers/core/core.peerconnection.js#L418-L421
22,169
freedomjs/freedom
providers/core/core.echo.js
function(cap, dispatchEvent) { this.mod = cap.module; this.dispatchEvent = dispatchEvent; util.handleEvents(this); // The Core object for managing channels. this.mod.once('core', function(Core) { this.core = new Core(); }.bind(this)); this.mod.emit(this.mod.controlChannel, { type: 'core request delegated to echo', request: 'core' }); }
javascript
function(cap, dispatchEvent) { this.mod = cap.module; this.dispatchEvent = dispatchEvent; util.handleEvents(this); // The Core object for managing channels. this.mod.once('core', function(Core) { this.core = new Core(); }.bind(this)); this.mod.emit(this.mod.controlChannel, { type: 'core request delegated to echo', request: 'core' }); }
[ "function", "(", "cap", ",", "dispatchEvent", ")", "{", "this", ".", "mod", "=", "cap", ".", "module", ";", "this", ".", "dispatchEvent", "=", "dispatchEvent", ";", "util", ".", "handleEvents", "(", "this", ")", ";", "// The Core object for managing channels.", "this", ".", "mod", ".", "once", "(", "'core'", ",", "function", "(", "Core", ")", "{", "this", ".", "core", "=", "new", "Core", "(", ")", ";", "}", ".", "bind", "(", "this", ")", ")", ";", "this", ".", "mod", ".", "emit", "(", "this", ".", "mod", ".", "controlChannel", ",", "{", "type", ":", "'core request delegated to echo'", ",", "request", ":", "'core'", "}", ")", ";", "}" ]
A minimal provider implementing the core.echo interface for interaction with custom channels. Primarily used for testing the robustness of the custom channel implementation. @Class Echo_unprivileged @constructor @param {module:Module} cap The module creating this provider.
[ "A", "minimal", "provider", "implementing", "the", "core", ".", "echo", "interface", "for", "interaction", "with", "custom", "channels", ".", "Primarily", "used", "for", "testing", "the", "robustness", "of", "the", "custom", "channel", "implementation", "." ]
9638e840aec9598c4d60383ed22444c525aefbf5
https://github.com/freedomjs/freedom/blob/9638e840aec9598c4d60383ed22444c525aefbf5/providers/core/core.echo.js#L13-L26
22,170
freedomjs/freedom
providers/core/core.console.js
function (cap) { this.level = (cap.config && cap.config.debug) || 'log'; this.console = (cap.config && cap.config.global.console); util.handleEvents(this); }
javascript
function (cap) { this.level = (cap.config && cap.config.debug) || 'log'; this.console = (cap.config && cap.config.global.console); util.handleEvents(this); }
[ "function", "(", "cap", ")", "{", "this", ".", "level", "=", "(", "cap", ".", "config", "&&", "cap", ".", "config", ".", "debug", ")", "||", "'log'", ";", "this", ".", "console", "=", "(", "cap", ".", "config", "&&", "cap", ".", "config", ".", "global", ".", "console", ")", ";", "util", ".", "handleEvents", "(", "this", ")", ";", "}" ]
A freedom.js logging provider that logs to chrome, firefox, and node consoles. @Class Logger_console @constructor @private @param {config: Object} cap Capabilities - console requires global config.
[ "A", "freedom", ".", "js", "logging", "provider", "that", "logs", "to", "chrome", "firefox", "and", "node", "consoles", "." ]
9638e840aec9598c4d60383ed22444c525aefbf5
https://github.com/freedomjs/freedom/blob/9638e840aec9598c4d60383ed22444c525aefbf5/providers/core/core.console.js#L12-L16
22,171
freedomjs/freedom
src/module.js
function (manifestURL, manifest, creator, policy) { this.api = policy.api; this.policy = policy; this.resource = policy.resource; this.debug = policy.debug; this.config = {}; this.id = manifestURL + Math.random(); this.manifestId = manifestURL; this.manifest = manifest; this.lineage = [this.manifestId].concat(creator); this.quiet = this.manifest.quiet || false; this.externalPortMap = {}; this.internalPortMap = {}; this.dependantChannels = []; // Map from dependency names to target URLs, from this module's manifest. this.dependencyUrls = {}; // Map from depenency names to arrays of pending messages. Once a // dependency is fully started, the pending messages will be drained and its // entry in this map will be deleted. this.pendingMessages = {}; this.started = false; this.failed = false; util.handleEvents(this); }
javascript
function (manifestURL, manifest, creator, policy) { this.api = policy.api; this.policy = policy; this.resource = policy.resource; this.debug = policy.debug; this.config = {}; this.id = manifestURL + Math.random(); this.manifestId = manifestURL; this.manifest = manifest; this.lineage = [this.manifestId].concat(creator); this.quiet = this.manifest.quiet || false; this.externalPortMap = {}; this.internalPortMap = {}; this.dependantChannels = []; // Map from dependency names to target URLs, from this module's manifest. this.dependencyUrls = {}; // Map from depenency names to arrays of pending messages. Once a // dependency is fully started, the pending messages will be drained and its // entry in this map will be deleted. this.pendingMessages = {}; this.started = false; this.failed = false; util.handleEvents(this); }
[ "function", "(", "manifestURL", ",", "manifest", ",", "creator", ",", "policy", ")", "{", "this", ".", "api", "=", "policy", ".", "api", ";", "this", ".", "policy", "=", "policy", ";", "this", ".", "resource", "=", "policy", ".", "resource", ";", "this", ".", "debug", "=", "policy", ".", "debug", ";", "this", ".", "config", "=", "{", "}", ";", "this", ".", "id", "=", "manifestURL", "+", "Math", ".", "random", "(", ")", ";", "this", ".", "manifestId", "=", "manifestURL", ";", "this", ".", "manifest", "=", "manifest", ";", "this", ".", "lineage", "=", "[", "this", ".", "manifestId", "]", ".", "concat", "(", "creator", ")", ";", "this", ".", "quiet", "=", "this", ".", "manifest", ".", "quiet", "||", "false", ";", "this", ".", "externalPortMap", "=", "{", "}", ";", "this", ".", "internalPortMap", "=", "{", "}", ";", "this", ".", "dependantChannels", "=", "[", "]", ";", "// Map from dependency names to target URLs, from this module's manifest.", "this", ".", "dependencyUrls", "=", "{", "}", ";", "// Map from depenency names to arrays of pending messages. Once a", "// dependency is fully started, the pending messages will be drained and its", "// entry in this map will be deleted.", "this", ".", "pendingMessages", "=", "{", "}", ";", "this", ".", "started", "=", "false", ";", "this", ".", "failed", "=", "false", ";", "util", ".", "handleEvents", "(", "this", ")", ";", "}" ]
The external Port face of a module on a hub. @class Module @extends Port @param {String} manifestURL The manifest this module loads. @param {String[]} creator The lineage of creation for this module. @param {Policy} Policy The policy loader for dependencies. @constructor
[ "The", "external", "Port", "face", "of", "a", "module", "on", "a", "hub", "." ]
9638e840aec9598c4d60383ed22444c525aefbf5
https://github.com/freedomjs/freedom/blob/9638e840aec9598c4d60383ed22444c525aefbf5/src/module.js#L14-L42
22,172
freedomjs/freedom
src/moduleinternal.js
function (manager) { this.config = {}; this.manager = manager; this.debug = manager.debug; this.binder = new ProxyBinder(this.manager); this.api = this.manager.api; this.manifests = {}; this.providers = {}; this.id = 'ModuleInternal'; this.pendingPorts = 0; this.requests = {}; this.unboundPorts = {}; util.handleEvents(this); }
javascript
function (manager) { this.config = {}; this.manager = manager; this.debug = manager.debug; this.binder = new ProxyBinder(this.manager); this.api = this.manager.api; this.manifests = {}; this.providers = {}; this.id = 'ModuleInternal'; this.pendingPorts = 0; this.requests = {}; this.unboundPorts = {}; util.handleEvents(this); }
[ "function", "(", "manager", ")", "{", "this", ".", "config", "=", "{", "}", ";", "this", ".", "manager", "=", "manager", ";", "this", ".", "debug", "=", "manager", ".", "debug", ";", "this", ".", "binder", "=", "new", "ProxyBinder", "(", "this", ".", "manager", ")", ";", "this", ".", "api", "=", "this", ".", "manager", ".", "api", ";", "this", ".", "manifests", "=", "{", "}", ";", "this", ".", "providers", "=", "{", "}", ";", "this", ".", "id", "=", "'ModuleInternal'", ";", "this", ".", "pendingPorts", "=", "0", ";", "this", ".", "requests", "=", "{", "}", ";", "this", ".", "unboundPorts", "=", "{", "}", ";", "util", ".", "handleEvents", "(", "this", ")", ";", "}" ]
The internal logic for module setup, which makes sure the public facing exports have appropriate properties, and load user scripts. @class ModuleInternal @extends Port @param {Port} manager The manager in this module to use for routing setup. @constructor
[ "The", "internal", "logic", "for", "module", "setup", "which", "makes", "sure", "the", "public", "facing", "exports", "have", "appropriate", "properties", "and", "load", "user", "scripts", "." ]
9638e840aec9598c4d60383ed22444c525aefbf5
https://github.com/freedomjs/freedom/blob/9638e840aec9598c4d60383ed22444c525aefbf5/src/moduleinternal.js#L17-L32
22,173
freedomjs/freedom
src/resource.js
function (debug) { this.debug = debug; this.files = {}; this.resolvers = [this.httpResolver, this.nullResolver]; this.contentRetrievers = { 'http': this.xhrRetriever, 'https': this.xhrRetriever, 'chrome-extension': this.xhrRetriever, 'resource': this.xhrRetriever, 'chrome': this.xhrRetriever, 'app': this.xhrRetriever, 'gopher': this.xhrRetriever, // For Cordova; see http://crbug.com/513352 . 'manifest': this.manifestRetriever }; }
javascript
function (debug) { this.debug = debug; this.files = {}; this.resolvers = [this.httpResolver, this.nullResolver]; this.contentRetrievers = { 'http': this.xhrRetriever, 'https': this.xhrRetriever, 'chrome-extension': this.xhrRetriever, 'resource': this.xhrRetriever, 'chrome': this.xhrRetriever, 'app': this.xhrRetriever, 'gopher': this.xhrRetriever, // For Cordova; see http://crbug.com/513352 . 'manifest': this.manifestRetriever }; }
[ "function", "(", "debug", ")", "{", "this", ".", "debug", "=", "debug", ";", "this", ".", "files", "=", "{", "}", ";", "this", ".", "resolvers", "=", "[", "this", ".", "httpResolver", ",", "this", ".", "nullResolver", "]", ";", "this", ".", "contentRetrievers", "=", "{", "'http'", ":", "this", ".", "xhrRetriever", ",", "'https'", ":", "this", ".", "xhrRetriever", ",", "'chrome-extension'", ":", "this", ".", "xhrRetriever", ",", "'resource'", ":", "this", ".", "xhrRetriever", ",", "'chrome'", ":", "this", ".", "xhrRetriever", ",", "'app'", ":", "this", ".", "xhrRetriever", ",", "'gopher'", ":", "this", ".", "xhrRetriever", ",", "// For Cordova; see http://crbug.com/513352 .", "'manifest'", ":", "this", ".", "manifestRetriever", "}", ";", "}" ]
The Resource registry for FreeDOM. Used to look up requested Resources, and provide lookup and migration of resources. @Class Resource @param {Debug} debug The logger to use for debugging. @constructor
[ "The", "Resource", "registry", "for", "FreeDOM", ".", "Used", "to", "look", "up", "requested", "Resources", "and", "provide", "lookup", "and", "migration", "of", "resources", "." ]
9638e840aec9598c4d60383ed22444c525aefbf5
https://github.com/freedomjs/freedom/blob/9638e840aec9598c4d60383ed22444c525aefbf5/src/resource.js#L14-L28
22,174
freedomjs/freedom
demo/connections/third-party/qr/qr.js
download
function download(cvs, data, callback) { var mime = data.mime || DEFAULT_MIME; root.location.href = cvs.toDataURL(mime).replace(mime, DOWNLOAD_MIME); if (typeof callback === 'function') callback(); }
javascript
function download(cvs, data, callback) { var mime = data.mime || DEFAULT_MIME; root.location.href = cvs.toDataURL(mime).replace(mime, DOWNLOAD_MIME); if (typeof callback === 'function') callback(); }
[ "function", "download", "(", "cvs", ",", "data", ",", "callback", ")", "{", "var", "mime", "=", "data", ".", "mime", "||", "DEFAULT_MIME", ";", "root", ".", "location", ".", "href", "=", "cvs", ".", "toDataURL", "(", "mime", ")", ".", "replace", "(", "mime", ",", "DOWNLOAD_MIME", ")", ";", "if", "(", "typeof", "callback", "===", "'function'", ")", "callback", "(", ")", ";", "}" ]
Force the canvas image to be downloaded in the browser. Optionally, a `callback` function can be specified which will be called upon completed. Since this is not an asynchronous operation, this is merely convenient and helps simplify the calling code.
[ "Force", "the", "canvas", "image", "to", "be", "downloaded", "in", "the", "browser", ".", "Optionally", "a", "callback", "function", "can", "be", "specified", "which", "will", "be", "called", "upon", "completed", ".", "Since", "this", "is", "not", "an", "asynchronous", "operation", "this", "is", "merely", "convenient", "and", "helps", "simplify", "the", "calling", "code", "." ]
9638e840aec9598c4d60383ed22444c525aefbf5
https://github.com/freedomjs/freedom/blob/9638e840aec9598c4d60383ed22444c525aefbf5/demo/connections/third-party/qr/qr.js#L192-L198
22,175
freedomjs/freedom
demo/connections/third-party/qr/qr.js
overrideAPI
function overrideAPI(qr) { var methods = [ 'canvas', 'image', 'save', 'saveSync', 'toDataURL' ]; var i; function overrideMethod(name) { qr[name] = function () { throw new Error(name + ' requires HTML5 canvas element support'); }; } for (i = 0; i < methods.length; i++) { overrideMethod(methods[i]); } }
javascript
function overrideAPI(qr) { var methods = [ 'canvas', 'image', 'save', 'saveSync', 'toDataURL' ]; var i; function overrideMethod(name) { qr[name] = function () { throw new Error(name + ' requires HTML5 canvas element support'); }; } for (i = 0; i < methods.length; i++) { overrideMethod(methods[i]); } }
[ "function", "overrideAPI", "(", "qr", ")", "{", "var", "methods", "=", "[", "'canvas'", ",", "'image'", ",", "'save'", ",", "'saveSync'", ",", "'toDataURL'", "]", ";", "var", "i", ";", "function", "overrideMethod", "(", "name", ")", "{", "qr", "[", "name", "]", "=", "function", "(", ")", "{", "throw", "new", "Error", "(", "name", "+", "' requires HTML5 canvas element support'", ")", ";", "}", ";", "}", "for", "(", "i", "=", "0", ";", "i", "<", "methods", ".", "length", ";", "i", "++", ")", "{", "overrideMethod", "(", "methods", "[", "i", "]", ")", ";", "}", "}" ]
Override the `qr` API methods that require HTML5 canvas support to throw a relevant error.
[ "Override", "the", "qr", "API", "methods", "that", "require", "HTML5", "canvas", "support", "to", "throw", "a", "relevant", "error", "." ]
9638e840aec9598c4d60383ed22444c525aefbf5
https://github.com/freedomjs/freedom/blob/9638e840aec9598c4d60383ed22444c525aefbf5/demo/connections/third-party/qr/qr.js#L207-L220
22,176
freedomjs/freedom
demo/connections/third-party/qr/qr.js
writeFile
function writeFile(cvs, data, callback) { if (typeof data.path !== 'string') { return callback(new TypeError('Invalid path type: ' + typeof data.path)); } var fd, buff; // Write the buffer to the open file stream once both prerequisites are met. function writeBuffer() { fs.write(fd, buff, 0, buff.length, 0, function (error) { fs.close(fd); callback(error); }); } // Create a buffer of the canvas' data. cvs.toBuffer(function (error, _buff) { if (error) return callback(error); buff = _buff; if (fd) { writeBuffer(); } }); // Open a stream for the file to be written. fs.open(data.path, 'w', WRITE_MODE, function (error, _fd) { if (error) return callback(error); fd = _fd; if (buff) { writeBuffer(); } }); }
javascript
function writeFile(cvs, data, callback) { if (typeof data.path !== 'string') { return callback(new TypeError('Invalid path type: ' + typeof data.path)); } var fd, buff; // Write the buffer to the open file stream once both prerequisites are met. function writeBuffer() { fs.write(fd, buff, 0, buff.length, 0, function (error) { fs.close(fd); callback(error); }); } // Create a buffer of the canvas' data. cvs.toBuffer(function (error, _buff) { if (error) return callback(error); buff = _buff; if (fd) { writeBuffer(); } }); // Open a stream for the file to be written. fs.open(data.path, 'w', WRITE_MODE, function (error, _fd) { if (error) return callback(error); fd = _fd; if (buff) { writeBuffer(); } }); }
[ "function", "writeFile", "(", "cvs", ",", "data", ",", "callback", ")", "{", "if", "(", "typeof", "data", ".", "path", "!==", "'string'", ")", "{", "return", "callback", "(", "new", "TypeError", "(", "'Invalid path type: '", "+", "typeof", "data", ".", "path", ")", ")", ";", "}", "var", "fd", ",", "buff", ";", "// Write the buffer to the open file stream once both prerequisites are met.", "function", "writeBuffer", "(", ")", "{", "fs", ".", "write", "(", "fd", ",", "buff", ",", "0", ",", "buff", ".", "length", ",", "0", ",", "function", "(", "error", ")", "{", "fs", ".", "close", "(", "fd", ")", ";", "callback", "(", "error", ")", ";", "}", ")", ";", "}", "// Create a buffer of the canvas' data.", "cvs", ".", "toBuffer", "(", "function", "(", "error", ",", "_buff", ")", "{", "if", "(", "error", ")", "return", "callback", "(", "error", ")", ";", "buff", "=", "_buff", ";", "if", "(", "fd", ")", "{", "writeBuffer", "(", ")", ";", "}", "}", ")", ";", "// Open a stream for the file to be written.", "fs", ".", "open", "(", "data", ".", "path", ",", "'w'", ",", "WRITE_MODE", ",", "function", "(", "error", ",", "_fd", ")", "{", "if", "(", "error", ")", "return", "callback", "(", "error", ")", ";", "fd", "=", "_fd", ";", "if", "(", "buff", ")", "{", "writeBuffer", "(", ")", ";", "}", "}", ")", ";", "}" ]
Asynchronously write the data of the rendered canvas to a given file path.
[ "Asynchronously", "write", "the", "data", "of", "the", "rendered", "canvas", "to", "a", "given", "file", "path", "." ]
9638e840aec9598c4d60383ed22444c525aefbf5
https://github.com/freedomjs/freedom/blob/9638e840aec9598c4d60383ed22444c525aefbf5/demo/connections/third-party/qr/qr.js#L223-L258
22,177
freedomjs/freedom
demo/connections/third-party/qr/qr.js
writeBuffer
function writeBuffer() { fs.write(fd, buff, 0, buff.length, 0, function (error) { fs.close(fd); callback(error); }); }
javascript
function writeBuffer() { fs.write(fd, buff, 0, buff.length, 0, function (error) { fs.close(fd); callback(error); }); }
[ "function", "writeBuffer", "(", ")", "{", "fs", ".", "write", "(", "fd", ",", "buff", ",", "0", ",", "buff", ".", "length", ",", "0", ",", "function", "(", "error", ")", "{", "fs", ".", "close", "(", "fd", ")", ";", "callback", "(", "error", ")", ";", "}", ")", ";", "}" ]
Write the buffer to the open file stream once both prerequisites are met.
[ "Write", "the", "buffer", "to", "the", "open", "file", "stream", "once", "both", "prerequisites", "are", "met", "." ]
9638e840aec9598c4d60383ed22444c525aefbf5
https://github.com/freedomjs/freedom/blob/9638e840aec9598c4d60383ed22444c525aefbf5/demo/connections/third-party/qr/qr.js#L231-L237
22,178
freedomjs/freedom
demo/connections/third-party/qr/qr.js
writeFileSync
function writeFileSync(cvs, data) { if (typeof data.path !== 'string') { throw new TypeError('Invalid path type: ' + typeof data.path); } var buff = cvs.toBuffer(); var fd = fs.openSync(data.path, 'w', WRITE_MODE); try { fs.writeSync(fd, buff, 0, buff.length, 0); } catch (error) { fs.closeSync(fd); } }
javascript
function writeFileSync(cvs, data) { if (typeof data.path !== 'string') { throw new TypeError('Invalid path type: ' + typeof data.path); } var buff = cvs.toBuffer(); var fd = fs.openSync(data.path, 'w', WRITE_MODE); try { fs.writeSync(fd, buff, 0, buff.length, 0); } catch (error) { fs.closeSync(fd); } }
[ "function", "writeFileSync", "(", "cvs", ",", "data", ")", "{", "if", "(", "typeof", "data", ".", "path", "!==", "'string'", ")", "{", "throw", "new", "TypeError", "(", "'Invalid path type: '", "+", "typeof", "data", ".", "path", ")", ";", "}", "var", "buff", "=", "cvs", ".", "toBuffer", "(", ")", ";", "var", "fd", "=", "fs", ".", "openSync", "(", "data", ".", "path", ",", "'w'", ",", "WRITE_MODE", ")", ";", "try", "{", "fs", ".", "writeSync", "(", "fd", ",", "buff", ",", "0", ",", "buff", ".", "length", ",", "0", ")", ";", "}", "catch", "(", "error", ")", "{", "fs", ".", "closeSync", "(", "fd", ")", ";", "}", "}" ]
Write the data of the rendered canvas to a given file path.
[ "Write", "the", "data", "of", "the", "rendered", "canvas", "to", "a", "given", "file", "path", "." ]
9638e840aec9598c4d60383ed22444c525aefbf5
https://github.com/freedomjs/freedom/blob/9638e840aec9598c4d60383ed22444c525aefbf5/demo/connections/third-party/qr/qr.js#L261-L274
22,179
freedomjs/freedom
demo/connections/third-party/qr/qr.js
addAlignment
function addAlignment(x, y) { var i; frameBuffer[x + width * y] = 1; for (i = -2; i < 2; i++) { frameBuffer[(x + i) + width * (y - 2)] = 1; frameBuffer[(x - 2) + width * (y + i + 1)] = 1; frameBuffer[(x + 2) + width * (y + i)] = 1; frameBuffer[(x + i + 1) + width * (y + 2)] = 1; } for (i = 0; i < 2; i++) { setMask(x - 1, y + i); setMask(x + 1, y - i); setMask(x - i, y - 1); setMask(x + i, y + 1); } }
javascript
function addAlignment(x, y) { var i; frameBuffer[x + width * y] = 1; for (i = -2; i < 2; i++) { frameBuffer[(x + i) + width * (y - 2)] = 1; frameBuffer[(x - 2) + width * (y + i + 1)] = 1; frameBuffer[(x + 2) + width * (y + i)] = 1; frameBuffer[(x + i + 1) + width * (y + 2)] = 1; } for (i = 0; i < 2; i++) { setMask(x - 1, y + i); setMask(x + 1, y - i); setMask(x - i, y - 1); setMask(x + i, y + 1); } }
[ "function", "addAlignment", "(", "x", ",", "y", ")", "{", "var", "i", ";", "frameBuffer", "[", "x", "+", "width", "*", "y", "]", "=", "1", ";", "for", "(", "i", "=", "-", "2", ";", "i", "<", "2", ";", "i", "++", ")", "{", "frameBuffer", "[", "(", "x", "+", "i", ")", "+", "width", "*", "(", "y", "-", "2", ")", "]", "=", "1", ";", "frameBuffer", "[", "(", "x", "-", "2", ")", "+", "width", "*", "(", "y", "+", "i", "+", "1", ")", "]", "=", "1", ";", "frameBuffer", "[", "(", "x", "+", "2", ")", "+", "width", "*", "(", "y", "+", "i", ")", "]", "=", "1", ";", "frameBuffer", "[", "(", "x", "+", "i", "+", "1", ")", "+", "width", "*", "(", "y", "+", "2", ")", "]", "=", "1", ";", "}", "for", "(", "i", "=", "0", ";", "i", "<", "2", ";", "i", "++", ")", "{", "setMask", "(", "x", "-", "1", ",", "y", "+", "i", ")", ";", "setMask", "(", "x", "+", "1", ",", "y", "-", "i", ")", ";", "setMask", "(", "x", "-", "i", ",", "y", "-", "1", ")", ";", "setMask", "(", "x", "+", "i", ",", "y", "+", "1", ")", ";", "}", "}" ]
Enter alignment pattern. Foreground colour to frame, background to mask. Frame will be merged with mask later.
[ "Enter", "alignment", "pattern", ".", "Foreground", "colour", "to", "frame", "background", "to", "mask", ".", "Frame", "will", "be", "merged", "with", "mask", "later", "." ]
9638e840aec9598c4d60383ed22444c525aefbf5
https://github.com/freedomjs/freedom/blob/9638e840aec9598c4d60383ed22444c525aefbf5/demo/connections/third-party/qr/qr.js#L297-L315
22,180
freedomjs/freedom
demo/connections/third-party/qr/qr.js
appendData
function appendData(data, dataLength, ecc, eccLength) { var bit, i, j; for (i = 0; i < eccLength; i++) { stringBuffer[ecc + i] = 0; } for (i = 0; i < dataLength; i++) { bit = GALOIS_LOG[stringBuffer[data + i] ^ stringBuffer[ecc]]; if (bit !== 255) { for (j = 1; j < eccLength; j++) { stringBuffer[ecc + j - 1] = stringBuffer[ecc + j] ^ GALOIS_EXPONENT[modN(bit + polynomial[eccLength - j])]; } } else { for (j = ecc; j < ecc + eccLength; j++) { stringBuffer[j] = stringBuffer[j + 1]; } } stringBuffer[ecc + eccLength - 1] = bit === 255 ? 0 : GALOIS_EXPONENT[modN(bit + polynomial[0])]; } }
javascript
function appendData(data, dataLength, ecc, eccLength) { var bit, i, j; for (i = 0; i < eccLength; i++) { stringBuffer[ecc + i] = 0; } for (i = 0; i < dataLength; i++) { bit = GALOIS_LOG[stringBuffer[data + i] ^ stringBuffer[ecc]]; if (bit !== 255) { for (j = 1; j < eccLength; j++) { stringBuffer[ecc + j - 1] = stringBuffer[ecc + j] ^ GALOIS_EXPONENT[modN(bit + polynomial[eccLength - j])]; } } else { for (j = ecc; j < ecc + eccLength; j++) { stringBuffer[j] = stringBuffer[j + 1]; } } stringBuffer[ecc + eccLength - 1] = bit === 255 ? 0 : GALOIS_EXPONENT[modN(bit + polynomial[0])]; } }
[ "function", "appendData", "(", "data", ",", "dataLength", ",", "ecc", ",", "eccLength", ")", "{", "var", "bit", ",", "i", ",", "j", ";", "for", "(", "i", "=", "0", ";", "i", "<", "eccLength", ";", "i", "++", ")", "{", "stringBuffer", "[", "ecc", "+", "i", "]", "=", "0", ";", "}", "for", "(", "i", "=", "0", ";", "i", "<", "dataLength", ";", "i", "++", ")", "{", "bit", "=", "GALOIS_LOG", "[", "stringBuffer", "[", "data", "+", "i", "]", "^", "stringBuffer", "[", "ecc", "]", "]", ";", "if", "(", "bit", "!==", "255", ")", "{", "for", "(", "j", "=", "1", ";", "j", "<", "eccLength", ";", "j", "++", ")", "{", "stringBuffer", "[", "ecc", "+", "j", "-", "1", "]", "=", "stringBuffer", "[", "ecc", "+", "j", "]", "^", "GALOIS_EXPONENT", "[", "modN", "(", "bit", "+", "polynomial", "[", "eccLength", "-", "j", "]", ")", "]", ";", "}", "}", "else", "{", "for", "(", "j", "=", "ecc", ";", "j", "<", "ecc", "+", "eccLength", ";", "j", "++", ")", "{", "stringBuffer", "[", "j", "]", "=", "stringBuffer", "[", "j", "+", "1", "]", ";", "}", "}", "stringBuffer", "[", "ecc", "+", "eccLength", "-", "1", "]", "=", "bit", "===", "255", "?", "0", ":", "GALOIS_EXPONENT", "[", "modN", "(", "bit", "+", "polynomial", "[", "0", "]", ")", "]", ";", "}", "}" ]
Calculate and append `ecc` data to the `data` block. If block is in the string buffer the indices to buffers are used.
[ "Calculate", "and", "append", "ecc", "data", "to", "the", "data", "block", ".", "If", "block", "is", "in", "the", "string", "buffer", "the", "indices", "to", "buffers", "are", "used", "." ]
9638e840aec9598c4d60383ed22444c525aefbf5
https://github.com/freedomjs/freedom/blob/9638e840aec9598c4d60383ed22444c525aefbf5/demo/connections/third-party/qr/qr.js#L329-L353
22,181
freedomjs/freedom
demo/connections/third-party/qr/qr.js
isMasked
function isMasked(x, y) { var bit; if (x > y) { bit = x; x = y; y = bit; } bit = y; bit += y * y; bit >>= 1; bit += x; return frameMask[bit] === 1; }
javascript
function isMasked(x, y) { var bit; if (x > y) { bit = x; x = y; y = bit; } bit = y; bit += y * y; bit >>= 1; bit += x; return frameMask[bit] === 1; }
[ "function", "isMasked", "(", "x", ",", "y", ")", "{", "var", "bit", ";", "if", "(", "x", ">", "y", ")", "{", "bit", "=", "x", ";", "x", "=", "y", ";", "y", "=", "bit", ";", "}", "bit", "=", "y", ";", "bit", "+=", "y", "*", "y", ";", "bit", ">>=", "1", ";", "bit", "+=", "x", ";", "return", "frameMask", "[", "bit", "]", "===", "1", ";", "}" ]
Check mask since symmetricals use half.
[ "Check", "mask", "since", "symmetricals", "use", "half", "." ]
9638e840aec9598c4d60383ed22444c525aefbf5
https://github.com/freedomjs/freedom/blob/9638e840aec9598c4d60383ed22444c525aefbf5/demo/connections/third-party/qr/qr.js#L356-L371
22,182
freedomjs/freedom
demo/connections/third-party/qr/qr.js
getBadRuns
function getBadRuns(length) { var badRuns = 0; var i; for (i = 0; i <= length; i++) { if (badBuffer[i] >= 5) { badRuns += N1 + badBuffer[i] - 5; } } // FBFFFBF as in finder. for (i = 3; i < length - 1; i += 2) { if (badBuffer[i - 2] === badBuffer[i + 2] && badBuffer[i + 2] === badBuffer[i - 1] && badBuffer[i - 1] === badBuffer[i + 1] && badBuffer[i - 1] * 3 === badBuffer[i] && // Background around the foreground pattern? Not part of the specs. (badBuffer[i - 3] === 0 || i + 3 > length || badBuffer[i - 3] * 3 >= badBuffer[i] * 4 || badBuffer[i + 3] * 3 >= badBuffer[i] * 4)) { badRuns += N3; } } return badRuns; }
javascript
function getBadRuns(length) { var badRuns = 0; var i; for (i = 0; i <= length; i++) { if (badBuffer[i] >= 5) { badRuns += N1 + badBuffer[i] - 5; } } // FBFFFBF as in finder. for (i = 3; i < length - 1; i += 2) { if (badBuffer[i - 2] === badBuffer[i + 2] && badBuffer[i + 2] === badBuffer[i - 1] && badBuffer[i - 1] === badBuffer[i + 1] && badBuffer[i - 1] * 3 === badBuffer[i] && // Background around the foreground pattern? Not part of the specs. (badBuffer[i - 3] === 0 || i + 3 > length || badBuffer[i - 3] * 3 >= badBuffer[i] * 4 || badBuffer[i + 3] * 3 >= badBuffer[i] * 4)) { badRuns += N3; } } return badRuns; }
[ "function", "getBadRuns", "(", "length", ")", "{", "var", "badRuns", "=", "0", ";", "var", "i", ";", "for", "(", "i", "=", "0", ";", "i", "<=", "length", ";", "i", "++", ")", "{", "if", "(", "badBuffer", "[", "i", "]", ">=", "5", ")", "{", "badRuns", "+=", "N1", "+", "badBuffer", "[", "i", "]", "-", "5", ";", "}", "}", "// FBFFFBF as in finder.", "for", "(", "i", "=", "3", ";", "i", "<", "length", "-", "1", ";", "i", "+=", "2", ")", "{", "if", "(", "badBuffer", "[", "i", "-", "2", "]", "===", "badBuffer", "[", "i", "+", "2", "]", "&&", "badBuffer", "[", "i", "+", "2", "]", "===", "badBuffer", "[", "i", "-", "1", "]", "&&", "badBuffer", "[", "i", "-", "1", "]", "===", "badBuffer", "[", "i", "+", "1", "]", "&&", "badBuffer", "[", "i", "-", "1", "]", "*", "3", "===", "badBuffer", "[", "i", "]", "&&", "// Background around the foreground pattern? Not part of the specs.", "(", "badBuffer", "[", "i", "-", "3", "]", "===", "0", "||", "i", "+", "3", ">", "length", "||", "badBuffer", "[", "i", "-", "3", "]", "*", "3", ">=", "badBuffer", "[", "i", "]", "*", "4", "||", "badBuffer", "[", "i", "+", "3", "]", "*", "3", ">=", "badBuffer", "[", "i", "]", "*", "4", ")", ")", "{", "badRuns", "+=", "N3", ";", "}", "}", "return", "badRuns", ";", "}" ]
Using the table for the length of each run, calculate the amount of bad image. Long runs or those that look like finders are called twice; once for X and Y.
[ "Using", "the", "table", "for", "the", "length", "of", "each", "run", "calculate", "the", "amount", "of", "bad", "image", ".", "Long", "runs", "or", "those", "that", "look", "like", "finders", "are", "called", "twice", ";", "once", "for", "X", "and", "Y", "." ]
9638e840aec9598c4d60383ed22444c525aefbf5
https://github.com/freedomjs/freedom/blob/9638e840aec9598c4d60383ed22444c525aefbf5/demo/connections/third-party/qr/qr.js#L486-L511
22,183
freedomjs/freedom
providers/core/core.websocket.js
function (cap, dispatchEvent, url, protocols, socket) { var WSImplementation = null, error; this.isNode = nodeStyle; if (typeof socket !== 'undefined') { WSImplementation = socket; } else if (WSHandle !== null) { WSImplementation = WSHandle; } else if (typeof WebSocket !== 'undefined') { WSImplementation = WebSocket; } else { console.error('Platform does not support WebSocket'); } this.dispatchEvent = dispatchEvent; try { if (protocols) { this.websocket = new WSImplementation(url, protocols); } else { this.websocket = new WSImplementation(url); } this.websocket.binaryType = 'arraybuffer'; } catch (e) { error = {}; if (e instanceof SyntaxError) { error.errcode = 'SYNTAX'; } else { error.errcode = e.name; } error.message = e.message; dispatchEvent('onError', error); return; } if (this.isNode) { this.websocket.on('message', this.onMessage.bind(this)); this.websocket.on('open', this.onOpen.bind(this)); // node.js websocket implementation not compliant this.websocket.on('close', this.onClose.bind(this, { code: 0, reason: 'UNKNOWN', wasClean: true })); this.websocket.on('error', this.onError.bind(this)); } else { this.websocket.onopen = this.onOpen.bind(this); this.websocket.onclose = this.onClose.bind(this); this.websocket.onmessage = this.onMessage.bind(this); this.websocket.onerror = this.onError.bind(this); } }
javascript
function (cap, dispatchEvent, url, protocols, socket) { var WSImplementation = null, error; this.isNode = nodeStyle; if (typeof socket !== 'undefined') { WSImplementation = socket; } else if (WSHandle !== null) { WSImplementation = WSHandle; } else if (typeof WebSocket !== 'undefined') { WSImplementation = WebSocket; } else { console.error('Platform does not support WebSocket'); } this.dispatchEvent = dispatchEvent; try { if (protocols) { this.websocket = new WSImplementation(url, protocols); } else { this.websocket = new WSImplementation(url); } this.websocket.binaryType = 'arraybuffer'; } catch (e) { error = {}; if (e instanceof SyntaxError) { error.errcode = 'SYNTAX'; } else { error.errcode = e.name; } error.message = e.message; dispatchEvent('onError', error); return; } if (this.isNode) { this.websocket.on('message', this.onMessage.bind(this)); this.websocket.on('open', this.onOpen.bind(this)); // node.js websocket implementation not compliant this.websocket.on('close', this.onClose.bind(this, { code: 0, reason: 'UNKNOWN', wasClean: true })); this.websocket.on('error', this.onError.bind(this)); } else { this.websocket.onopen = this.onOpen.bind(this); this.websocket.onclose = this.onClose.bind(this); this.websocket.onmessage = this.onMessage.bind(this); this.websocket.onerror = this.onError.bind(this); } }
[ "function", "(", "cap", ",", "dispatchEvent", ",", "url", ",", "protocols", ",", "socket", ")", "{", "var", "WSImplementation", "=", "null", ",", "error", ";", "this", ".", "isNode", "=", "nodeStyle", ";", "if", "(", "typeof", "socket", "!==", "'undefined'", ")", "{", "WSImplementation", "=", "socket", ";", "}", "else", "if", "(", "WSHandle", "!==", "null", ")", "{", "WSImplementation", "=", "WSHandle", ";", "}", "else", "if", "(", "typeof", "WebSocket", "!==", "'undefined'", ")", "{", "WSImplementation", "=", "WebSocket", ";", "}", "else", "{", "console", ".", "error", "(", "'Platform does not support WebSocket'", ")", ";", "}", "this", ".", "dispatchEvent", "=", "dispatchEvent", ";", "try", "{", "if", "(", "protocols", ")", "{", "this", ".", "websocket", "=", "new", "WSImplementation", "(", "url", ",", "protocols", ")", ";", "}", "else", "{", "this", ".", "websocket", "=", "new", "WSImplementation", "(", "url", ")", ";", "}", "this", ".", "websocket", ".", "binaryType", "=", "'arraybuffer'", ";", "}", "catch", "(", "e", ")", "{", "error", "=", "{", "}", ";", "if", "(", "e", "instanceof", "SyntaxError", ")", "{", "error", ".", "errcode", "=", "'SYNTAX'", ";", "}", "else", "{", "error", ".", "errcode", "=", "e", ".", "name", ";", "}", "error", ".", "message", "=", "e", ".", "message", ";", "dispatchEvent", "(", "'onError'", ",", "error", ")", ";", "return", ";", "}", "if", "(", "this", ".", "isNode", ")", "{", "this", ".", "websocket", ".", "on", "(", "'message'", ",", "this", ".", "onMessage", ".", "bind", "(", "this", ")", ")", ";", "this", ".", "websocket", ".", "on", "(", "'open'", ",", "this", ".", "onOpen", ".", "bind", "(", "this", ")", ")", ";", "// node.js websocket implementation not compliant", "this", ".", "websocket", ".", "on", "(", "'close'", ",", "this", ".", "onClose", ".", "bind", "(", "this", ",", "{", "code", ":", "0", ",", "reason", ":", "'UNKNOWN'", ",", "wasClean", ":", "true", "}", ")", ")", ";", "this", ".", "websocket", ".", "on", "(", "'error'", ",", "this", ".", "onError", ".", "bind", "(", "this", ")", ")", ";", "}", "else", "{", "this", ".", "websocket", ".", "onopen", "=", "this", ".", "onOpen", ".", "bind", "(", "this", ")", ";", "this", ".", "websocket", ".", "onclose", "=", "this", ".", "onClose", ".", "bind", "(", "this", ")", ";", "this", ".", "websocket", ".", "onmessage", "=", "this", ".", "onMessage", ".", "bind", "(", "this", ")", ";", "this", ".", "websocket", ".", "onerror", "=", "this", ".", "onError", ".", "bind", "(", "this", ")", ";", "}", "}" ]
A WebSocket core provider @param {Object} cap Capabilities for the provider @param {Function} dispatchEvent Function to dispatch events. @param {String} url The Remote URL to connect with. @param {String[]} protocols SubProtocols to open. @param {WebSocket?} socket An alternative socket class to use.
[ "A", "WebSocket", "core", "provider" ]
9638e840aec9598c4d60383ed22444c525aefbf5
https://github.com/freedomjs/freedom/blob/9638e840aec9598c4d60383ed22444c525aefbf5/providers/core/core.websocket.js#L16-L66
22,184
freedomjs/freedom
src/provider.js
function (def, debug) { this.id = Consumer.nextId(); util.handleEvents(this); this.debug = debug; this.definition = def; this.mode = Provider.mode.synchronous; this.channels = {}; this.iface = null; this.closeHandlers = {}; this.providerCls = null; this.ifaces = {}; this.emits = {}; }
javascript
function (def, debug) { this.id = Consumer.nextId(); util.handleEvents(this); this.debug = debug; this.definition = def; this.mode = Provider.mode.synchronous; this.channels = {}; this.iface = null; this.closeHandlers = {}; this.providerCls = null; this.ifaces = {}; this.emits = {}; }
[ "function", "(", "def", ",", "debug", ")", "{", "this", ".", "id", "=", "Consumer", ".", "nextId", "(", ")", ";", "util", ".", "handleEvents", "(", "this", ")", ";", "this", ".", "debug", "=", "debug", ";", "this", ".", "definition", "=", "def", ";", "this", ".", "mode", "=", "Provider", ".", "mode", ".", "synchronous", ";", "this", ".", "channels", "=", "{", "}", ";", "this", ".", "iface", "=", "null", ";", "this", ".", "closeHandlers", "=", "{", "}", ";", "this", ".", "providerCls", "=", "null", ";", "this", ".", "ifaces", "=", "{", "}", ";", "this", ".", "emits", "=", "{", "}", ";", "}" ]
A freedom port for a user-accessable provider. @class Provider @implements Port @uses handleEvents @param {Object} def The interface of the provider. @param {Debug} debug The debugger to use for logging. @contructor
[ "A", "freedom", "port", "for", "a", "user", "-", "accessable", "provider", "." ]
9638e840aec9598c4d60383ed22444c525aefbf5
https://github.com/freedomjs/freedom/blob/9638e840aec9598c4d60383ed22444c525aefbf5/src/provider.js#L14-L28
22,185
freedomjs/freedom
spec/providers/social/social.double.integration.src.js
function(evts, key) { var saw1 = false, saw2 = false; for (var i = 0; i < evts.length; i++) { if (typeof c1State !== "undefined" && evts[i][key] == c1State[key]) { saw1 = true; } if (typeof c2State !== "undefined" && evts[i][key] == c2State[key]) { saw2 = true; } } return saw1 && saw2; }
javascript
function(evts, key) { var saw1 = false, saw2 = false; for (var i = 0; i < evts.length; i++) { if (typeof c1State !== "undefined" && evts[i][key] == c1State[key]) { saw1 = true; } if (typeof c2State !== "undefined" && evts[i][key] == c2State[key]) { saw2 = true; } } return saw1 && saw2; }
[ "function", "(", "evts", ",", "key", ")", "{", "var", "saw1", "=", "false", ",", "saw2", "=", "false", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "evts", ".", "length", ";", "i", "++", ")", "{", "if", "(", "typeof", "c1State", "!==", "\"undefined\"", "&&", "evts", "[", "i", "]", "[", "key", "]", "==", "c1State", "[", "key", "]", ")", "{", "saw1", "=", "true", ";", "}", "if", "(", "typeof", "c2State", "!==", "\"undefined\"", "&&", "evts", "[", "i", "]", "[", "key", "]", "==", "c2State", "[", "key", "]", ")", "{", "saw2", "=", "true", ";", "}", "}", "return", "saw1", "&&", "saw2", ";", "}" ]
Checks if we see both users for a set of events
[ "Checks", "if", "we", "see", "both", "users", "for", "a", "set", "of", "events" ]
9638e840aec9598c4d60383ed22444c525aefbf5
https://github.com/freedomjs/freedom/blob/9638e840aec9598c4d60383ed22444c525aefbf5/spec/providers/social/social.double.integration.src.js#L144-L155
22,186
freedomjs/freedom
spec/providers/social/social.double.integration.src.js
function(arr, info) { if (typeof arr !== "undefined") { arr.push(info); } if (!triggered && seeBoth(c1ProfileEvts, "userId") && seeBoth(c2ProfileEvts, "userId") && seeBoth(c1StateEvts, "clientId") && seeBoth(c2StateEvts, "clientId")) { triggered = true; Promise.all([ c1.getUsers(), c2.getUsers(), c1.getClients(), c2.getClients() ]).then(function(ret) { expect(ret[0][c1State.userId]).toEqual(Helper.makeUserProfile(c1State.userId)); expect(ret[0][c2State.userId]).toEqual(Helper.makeUserProfile(c2State.userId)); expect(ret[1][c1State.userId]).toEqual(Helper.makeUserProfile(c1State.userId)); expect(ret[1][c2State.userId]).toEqual(Helper.makeUserProfile(c2State.userId)); expect(ret[2][c1State.clientId]).toEqual(Helper.makeClientState(c1State.userId, c1State.clientId, "ONLINE")); expect(ret[2][c2State.clientId]).toEqual(Helper.makeClientState(c2State.userId, c2State.clientId, "ONLINE")); expect(ret[3][c1State.clientId]).toEqual(Helper.makeClientState(c1State.userId, c1State.clientId, "ONLINE")); expect(ret[3][c2State.clientId]).toEqual(Helper.makeClientState(c2State.userId, c2State.clientId, "ONLINE")); return Promise.all([ c1.logout(), c2.logout() ]); }).then(done).catch(Helper.errHandler); } }
javascript
function(arr, info) { if (typeof arr !== "undefined") { arr.push(info); } if (!triggered && seeBoth(c1ProfileEvts, "userId") && seeBoth(c2ProfileEvts, "userId") && seeBoth(c1StateEvts, "clientId") && seeBoth(c2StateEvts, "clientId")) { triggered = true; Promise.all([ c1.getUsers(), c2.getUsers(), c1.getClients(), c2.getClients() ]).then(function(ret) { expect(ret[0][c1State.userId]).toEqual(Helper.makeUserProfile(c1State.userId)); expect(ret[0][c2State.userId]).toEqual(Helper.makeUserProfile(c2State.userId)); expect(ret[1][c1State.userId]).toEqual(Helper.makeUserProfile(c1State.userId)); expect(ret[1][c2State.userId]).toEqual(Helper.makeUserProfile(c2State.userId)); expect(ret[2][c1State.clientId]).toEqual(Helper.makeClientState(c1State.userId, c1State.clientId, "ONLINE")); expect(ret[2][c2State.clientId]).toEqual(Helper.makeClientState(c2State.userId, c2State.clientId, "ONLINE")); expect(ret[3][c1State.clientId]).toEqual(Helper.makeClientState(c1State.userId, c1State.clientId, "ONLINE")); expect(ret[3][c2State.clientId]).toEqual(Helper.makeClientState(c2State.userId, c2State.clientId, "ONLINE")); return Promise.all([ c1.logout(), c2.logout() ]); }).then(done).catch(Helper.errHandler); } }
[ "function", "(", "arr", ",", "info", ")", "{", "if", "(", "typeof", "arr", "!==", "\"undefined\"", ")", "{", "arr", ".", "push", "(", "info", ")", ";", "}", "if", "(", "!", "triggered", "&&", "seeBoth", "(", "c1ProfileEvts", ",", "\"userId\"", ")", "&&", "seeBoth", "(", "c2ProfileEvts", ",", "\"userId\"", ")", "&&", "seeBoth", "(", "c1StateEvts", ",", "\"clientId\"", ")", "&&", "seeBoth", "(", "c2StateEvts", ",", "\"clientId\"", ")", ")", "{", "triggered", "=", "true", ";", "Promise", ".", "all", "(", "[", "c1", ".", "getUsers", "(", ")", ",", "c2", ".", "getUsers", "(", ")", ",", "c1", ".", "getClients", "(", ")", ",", "c2", ".", "getClients", "(", ")", "]", ")", ".", "then", "(", "function", "(", "ret", ")", "{", "expect", "(", "ret", "[", "0", "]", "[", "c1State", ".", "userId", "]", ")", ".", "toEqual", "(", "Helper", ".", "makeUserProfile", "(", "c1State", ".", "userId", ")", ")", ";", "expect", "(", "ret", "[", "0", "]", "[", "c2State", ".", "userId", "]", ")", ".", "toEqual", "(", "Helper", ".", "makeUserProfile", "(", "c2State", ".", "userId", ")", ")", ";", "expect", "(", "ret", "[", "1", "]", "[", "c1State", ".", "userId", "]", ")", ".", "toEqual", "(", "Helper", ".", "makeUserProfile", "(", "c1State", ".", "userId", ")", ")", ";", "expect", "(", "ret", "[", "1", "]", "[", "c2State", ".", "userId", "]", ")", ".", "toEqual", "(", "Helper", ".", "makeUserProfile", "(", "c2State", ".", "userId", ")", ")", ";", "expect", "(", "ret", "[", "2", "]", "[", "c1State", ".", "clientId", "]", ")", ".", "toEqual", "(", "Helper", ".", "makeClientState", "(", "c1State", ".", "userId", ",", "c1State", ".", "clientId", ",", "\"ONLINE\"", ")", ")", ";", "expect", "(", "ret", "[", "2", "]", "[", "c2State", ".", "clientId", "]", ")", ".", "toEqual", "(", "Helper", ".", "makeClientState", "(", "c2State", ".", "userId", ",", "c2State", ".", "clientId", ",", "\"ONLINE\"", ")", ")", ";", "expect", "(", "ret", "[", "3", "]", "[", "c1State", ".", "clientId", "]", ")", ".", "toEqual", "(", "Helper", ".", "makeClientState", "(", "c1State", ".", "userId", ",", "c1State", ".", "clientId", ",", "\"ONLINE\"", ")", ")", ";", "expect", "(", "ret", "[", "3", "]", "[", "c2State", ".", "clientId", "]", ")", ".", "toEqual", "(", "Helper", ".", "makeClientState", "(", "c2State", ".", "userId", ",", "c2State", ".", "clientId", ",", "\"ONLINE\"", ")", ")", ";", "return", "Promise", ".", "all", "(", "[", "c1", ".", "logout", "(", ")", ",", "c2", ".", "logout", "(", ")", "]", ")", ";", "}", ")", ".", "then", "(", "done", ")", ".", "catch", "(", "Helper", ".", "errHandler", ")", ";", "}", "}" ]
Triggered on every event, waiting until all necessary events are collected
[ "Triggered", "on", "every", "event", "waiting", "until", "all", "necessary", "events", "are", "collected" ]
9638e840aec9598c4d60383ed22444c525aefbf5
https://github.com/freedomjs/freedom/blob/9638e840aec9598c4d60383ed22444c525aefbf5/spec/providers/social/social.double.integration.src.js#L158-L178
22,187
freedomjs/freedom
src/link.js
function (name, resource) { this.id = 'Link' + Math.random(); this.name = name; this.resource = resource; this.config = {}; this.src = null; util.handleEvents(this); util.mixin(this, Link.prototype); }
javascript
function (name, resource) { this.id = 'Link' + Math.random(); this.name = name; this.resource = resource; this.config = {}; this.src = null; util.handleEvents(this); util.mixin(this, Link.prototype); }
[ "function", "(", "name", ",", "resource", ")", "{", "this", ".", "id", "=", "'Link'", "+", "Math", ".", "random", "(", ")", ";", "this", ".", "name", "=", "name", ";", "this", ".", "resource", "=", "resource", ";", "this", ".", "config", "=", "{", "}", ";", "this", ".", "src", "=", "null", ";", "util", ".", "handleEvents", "(", "this", ")", ";", "util", ".", "mixin", "(", "this", ",", "Link", ".", "prototype", ")", ";", "}" ]
A link connects two freedom hubs. This is an abstract class providing common functionality of translating control channels, and integrating config information. @class Link @implements Port @constructor
[ "A", "link", "connects", "two", "freedom", "hubs", ".", "This", "is", "an", "abstract", "class", "providing", "common", "functionality", "of", "translating", "control", "channels", "and", "integrating", "config", "information", "." ]
9638e840aec9598c4d60383ed22444c525aefbf5
https://github.com/freedomjs/freedom/blob/9638e840aec9598c4d60383ed22444c525aefbf5/src/link.js#L12-L21
22,188
freedomjs/freedom
src/policy.js
function(manager, resource, config) { this.api = manager.api; this.debug = manager.debug; this.location = config.location; this.resource = resource; this.config = config; this.runtimes = []; this.policies = []; this.pending = {}; util.handleEvents(this); this.add(manager, config.policy); this.runtimes[0].local = true; }
javascript
function(manager, resource, config) { this.api = manager.api; this.debug = manager.debug; this.location = config.location; this.resource = resource; this.config = config; this.runtimes = []; this.policies = []; this.pending = {}; util.handleEvents(this); this.add(manager, config.policy); this.runtimes[0].local = true; }
[ "function", "(", "manager", ",", "resource", ",", "config", ")", "{", "this", ".", "api", "=", "manager", ".", "api", ";", "this", ".", "debug", "=", "manager", ".", "debug", ";", "this", ".", "location", "=", "config", ".", "location", ";", "this", ".", "resource", "=", "resource", ";", "this", ".", "config", "=", "config", ";", "this", ".", "runtimes", "=", "[", "]", ";", "this", ".", "policies", "=", "[", "]", ";", "this", ".", "pending", "=", "{", "}", ";", "util", ".", "handleEvents", "(", "this", ")", ";", "this", ".", "add", "(", "manager", ",", "config", ".", "policy", ")", ";", "this", ".", "runtimes", "[", "0", "]", ".", "local", "=", "true", ";", "}" ]
The Policy registry for freedom.js. Used to look up modules and provide migration and coallesing of execution. @Class Policy @param {Manager} manager The manager of the active runtime. @param {Resource} resource The resource loader of the active runtime. @param {Object} config The local config. @constructor
[ "The", "Policy", "registry", "for", "freedom", ".", "js", ".", "Used", "to", "look", "up", "modules", "and", "provide", "migration", "and", "coallesing", "of", "execution", "." ]
9638e840aec9598c4d60383ed22444c525aefbf5
https://github.com/freedomjs/freedom/blob/9638e840aec9598c4d60383ed22444c525aefbf5/src/policy.js#L16-L30
22,189
freedomjs/freedom
src/manager.js
function (hub, resource, api) { this.id = 'control'; this.config = {}; this.controlFlows = {}; this.dataFlows = {}; this.dataFlows[this.id] = []; this.reverseFlowMap = {}; this.debug = hub.debug; this.hub = hub; this.resource = resource; this.api = api; this.delegate = null; this.toDelegate = {}; this.hub.on('config', function (config) { util.mixin(this.config, config); this.emit('config'); }.bind(this)); util.handleEvents(this); this.hub.register(this); }
javascript
function (hub, resource, api) { this.id = 'control'; this.config = {}; this.controlFlows = {}; this.dataFlows = {}; this.dataFlows[this.id] = []; this.reverseFlowMap = {}; this.debug = hub.debug; this.hub = hub; this.resource = resource; this.api = api; this.delegate = null; this.toDelegate = {}; this.hub.on('config', function (config) { util.mixin(this.config, config); this.emit('config'); }.bind(this)); util.handleEvents(this); this.hub.register(this); }
[ "function", "(", "hub", ",", "resource", ",", "api", ")", "{", "this", ".", "id", "=", "'control'", ";", "this", ".", "config", "=", "{", "}", ";", "this", ".", "controlFlows", "=", "{", "}", ";", "this", ".", "dataFlows", "=", "{", "}", ";", "this", ".", "dataFlows", "[", "this", ".", "id", "]", "=", "[", "]", ";", "this", ".", "reverseFlowMap", "=", "{", "}", ";", "this", ".", "debug", "=", "hub", ".", "debug", ";", "this", ".", "hub", "=", "hub", ";", "this", ".", "resource", "=", "resource", ";", "this", ".", "api", "=", "api", ";", "this", ".", "delegate", "=", "null", ";", "this", ".", "toDelegate", "=", "{", "}", ";", "this", ".", "hub", ".", "on", "(", "'config'", ",", "function", "(", "config", ")", "{", "util", ".", "mixin", "(", "this", ".", "config", ",", "config", ")", ";", "this", ".", "emit", "(", "'config'", ")", ";", "}", ".", "bind", "(", "this", ")", ")", ";", "util", ".", "handleEvents", "(", "this", ")", ";", "this", ".", "hub", ".", "register", "(", "this", ")", ";", "}" ]
A freedom port which manages the control plane of of changing hub routes. @class Manager @implements Port @param {Hub} hub The routing hub to control. @param {Resource} resource The resource manager for the runtime. @param {Api} api The API manager for the runtime. @constructor
[ "A", "freedom", "port", "which", "manages", "the", "control", "plane", "of", "of", "changing", "hub", "routes", "." ]
9638e840aec9598c4d60383ed22444c525aefbf5
https://github.com/freedomjs/freedom/blob/9638e840aec9598c4d60383ed22444c525aefbf5/src/manager.js#L14-L37
22,190
freedomjs/freedom
demo/connections/main.js
onState
function onState(data) { if (data.status === social.STATUS.OFFLINE) { if (users.hasOwnProperty(data.userId)) { delete users[data.userId]; } } else { //Only track non-offline clients users[data.userId] = data; } sendUsers(); // Handle my state separately if (myClientState !== null && data.clientId === myClientState.clientId) { view.postMessage({ event: 'status', online: data.status === social.STATUS.ONLINE }); view.postMessage({'height': data.status === social.STATUS.ONLINE ? 384 : 109}); if (data.status !== social.STATUS.ONLINE) { logger.error('got status ' + data.status + ' from social'); doLogin(); } } }
javascript
function onState(data) { if (data.status === social.STATUS.OFFLINE) { if (users.hasOwnProperty(data.userId)) { delete users[data.userId]; } } else { //Only track non-offline clients users[data.userId] = data; } sendUsers(); // Handle my state separately if (myClientState !== null && data.clientId === myClientState.clientId) { view.postMessage({ event: 'status', online: data.status === social.STATUS.ONLINE }); view.postMessage({'height': data.status === social.STATUS.ONLINE ? 384 : 109}); if (data.status !== social.STATUS.ONLINE) { logger.error('got status ' + data.status + ' from social'); doLogin(); } } }
[ "function", "onState", "(", "data", ")", "{", "if", "(", "data", ".", "status", "===", "social", ".", "STATUS", ".", "OFFLINE", ")", "{", "if", "(", "users", ".", "hasOwnProperty", "(", "data", ".", "userId", ")", ")", "{", "delete", "users", "[", "data", ".", "userId", "]", ";", "}", "}", "else", "{", "//Only track non-offline clients", "users", "[", "data", ".", "userId", "]", "=", "data", ";", "}", "sendUsers", "(", ")", ";", "// Handle my state separately", "if", "(", "myClientState", "!==", "null", "&&", "data", ".", "clientId", "===", "myClientState", ".", "clientId", ")", "{", "view", ".", "postMessage", "(", "{", "event", ":", "'status'", ",", "online", ":", "data", ".", "status", "===", "social", ".", "STATUS", ".", "ONLINE", "}", ")", ";", "view", ".", "postMessage", "(", "{", "'height'", ":", "data", ".", "status", "===", "social", ".", "STATUS", ".", "ONLINE", "?", "384", ":", "109", "}", ")", ";", "if", "(", "data", ".", "status", "!==", "social", ".", "STATUS", ".", "ONLINE", ")", "{", "logger", ".", "error", "(", "'got status '", "+", "data", ".", "status", "+", "' from social'", ")", ";", "doLogin", "(", ")", ";", "}", "}", "}" ]
On newly online or offline clients, let's update the roster
[ "On", "newly", "online", "or", "offline", "clients", "let", "s", "update", "the", "roster" ]
9638e840aec9598c4d60383ed22444c525aefbf5
https://github.com/freedomjs/freedom/blob/9638e840aec9598c4d60383ed22444c525aefbf5/demo/connections/main.js#L49-L71
22,191
freedomjs/freedom
demo/aboutme/aboutme.js
function(resp) { if (resp.name) { resp.details = "Speaks: " + resp.locale + ", Gender: " + resp.gender; } page.emit('profile', resp); }
javascript
function(resp) { if (resp.name) { resp.details = "Speaks: " + resp.locale + ", Gender: " + resp.gender; } page.emit('profile', resp); }
[ "function", "(", "resp", ")", "{", "if", "(", "resp", ".", "name", ")", "{", "resp", ".", "details", "=", "\"Speaks: \"", "+", "resp", ".", "locale", "+", "\", Gender: \"", "+", "resp", ".", "gender", ";", "}", "page", ".", "emit", "(", "'profile'", ",", "resp", ")", ";", "}" ]
onProfile is called by the script included by importScripts above.
[ "onProfile", "is", "called", "by", "the", "script", "included", "by", "importScripts", "above", "." ]
9638e840aec9598c4d60383ed22444c525aefbf5
https://github.com/freedomjs/freedom/blob/9638e840aec9598c4d60383ed22444c525aefbf5/demo/aboutme/aboutme.js#L56-L61
22,192
freedomjs/freedom
spec/providers/coreIntegration/rtcpeerconnection.integration.src.js
function(payload, callback) { var alice, bob, aliceChannel, bobChannel, aliceCandidates = [], aliceOffer; alice = peercon(); bob = peercon(); bob.on('ondatachannel', function (msg) { bobChannel = datachan(msg.channel); bobChannel.setBinaryType('arraybuffer', function () {}); bobChannel.on('onmessage', function (msg) { alice.close(); bob.close(); callback(msg); }); }); bob.on('onicecandidate', function (msg) { msg.candidate && alice.addIceCandidate(msg.candidate); }); alice.on('onicecandidate', function (msg) { // firefox needs ice candidates all sent before asking for an answer. if (!msg.candidate) { bob.setRemoteDescription(aliceOffer).then(function () { var last; while (aliceCandidates.length) { last = bob.addIceCandidate(aliceCandidates.shift()); } return last; }).then(function () { return bob.createAnswer(); }).then(function (answer) { return bob.setLocalDescription(answer).then(function () {return answer; }); }).then(function (answer) { return alice.setRemoteDescription(answer); }, function (err) { console.error('RTC failed: ', err); }); } else { aliceCandidates.push(msg.candidate); } }); alice.createDataChannel('channel').then(function (id) { aliceChannel = datachan(id); aliceChannel.on('onopen', function () { if (payload instanceof ArrayBuffer) { aliceChannel.sendBuffer(payload); } else { aliceChannel.send(payload); } }); aliceChannel.setBinaryType('arraybuffer').then(function () { return alice.createOffer(); }).then(function (offer) { alice.setLocalDescription(offer); aliceOffer = offer; }); }, function (err) { console.error('RTC failed: ', err); }); }
javascript
function(payload, callback) { var alice, bob, aliceChannel, bobChannel, aliceCandidates = [], aliceOffer; alice = peercon(); bob = peercon(); bob.on('ondatachannel', function (msg) { bobChannel = datachan(msg.channel); bobChannel.setBinaryType('arraybuffer', function () {}); bobChannel.on('onmessage', function (msg) { alice.close(); bob.close(); callback(msg); }); }); bob.on('onicecandidate', function (msg) { msg.candidate && alice.addIceCandidate(msg.candidate); }); alice.on('onicecandidate', function (msg) { // firefox needs ice candidates all sent before asking for an answer. if (!msg.candidate) { bob.setRemoteDescription(aliceOffer).then(function () { var last; while (aliceCandidates.length) { last = bob.addIceCandidate(aliceCandidates.shift()); } return last; }).then(function () { return bob.createAnswer(); }).then(function (answer) { return bob.setLocalDescription(answer).then(function () {return answer; }); }).then(function (answer) { return alice.setRemoteDescription(answer); }, function (err) { console.error('RTC failed: ', err); }); } else { aliceCandidates.push(msg.candidate); } }); alice.createDataChannel('channel').then(function (id) { aliceChannel = datachan(id); aliceChannel.on('onopen', function () { if (payload instanceof ArrayBuffer) { aliceChannel.sendBuffer(payload); } else { aliceChannel.send(payload); } }); aliceChannel.setBinaryType('arraybuffer').then(function () { return alice.createOffer(); }).then(function (offer) { alice.setLocalDescription(offer); aliceOffer = offer; }); }, function (err) { console.error('RTC failed: ', err); }); }
[ "function", "(", "payload", ",", "callback", ")", "{", "var", "alice", ",", "bob", ",", "aliceChannel", ",", "bobChannel", ",", "aliceCandidates", "=", "[", "]", ",", "aliceOffer", ";", "alice", "=", "peercon", "(", ")", ";", "bob", "=", "peercon", "(", ")", ";", "bob", ".", "on", "(", "'ondatachannel'", ",", "function", "(", "msg", ")", "{", "bobChannel", "=", "datachan", "(", "msg", ".", "channel", ")", ";", "bobChannel", ".", "setBinaryType", "(", "'arraybuffer'", ",", "function", "(", ")", "{", "}", ")", ";", "bobChannel", ".", "on", "(", "'onmessage'", ",", "function", "(", "msg", ")", "{", "alice", ".", "close", "(", ")", ";", "bob", ".", "close", "(", ")", ";", "callback", "(", "msg", ")", ";", "}", ")", ";", "}", ")", ";", "bob", ".", "on", "(", "'onicecandidate'", ",", "function", "(", "msg", ")", "{", "msg", ".", "candidate", "&&", "alice", ".", "addIceCandidate", "(", "msg", ".", "candidate", ")", ";", "}", ")", ";", "alice", ".", "on", "(", "'onicecandidate'", ",", "function", "(", "msg", ")", "{", "// firefox needs ice candidates all sent before asking for an answer.", "if", "(", "!", "msg", ".", "candidate", ")", "{", "bob", ".", "setRemoteDescription", "(", "aliceOffer", ")", ".", "then", "(", "function", "(", ")", "{", "var", "last", ";", "while", "(", "aliceCandidates", ".", "length", ")", "{", "last", "=", "bob", ".", "addIceCandidate", "(", "aliceCandidates", ".", "shift", "(", ")", ")", ";", "}", "return", "last", ";", "}", ")", ".", "then", "(", "function", "(", ")", "{", "return", "bob", ".", "createAnswer", "(", ")", ";", "}", ")", ".", "then", "(", "function", "(", "answer", ")", "{", "return", "bob", ".", "setLocalDescription", "(", "answer", ")", ".", "then", "(", "function", "(", ")", "{", "return", "answer", ";", "}", ")", ";", "}", ")", ".", "then", "(", "function", "(", "answer", ")", "{", "return", "alice", ".", "setRemoteDescription", "(", "answer", ")", ";", "}", ",", "function", "(", "err", ")", "{", "console", ".", "error", "(", "'RTC failed: '", ",", "err", ")", ";", "}", ")", ";", "}", "else", "{", "aliceCandidates", ".", "push", "(", "msg", ".", "candidate", ")", ";", "}", "}", ")", ";", "alice", ".", "createDataChannel", "(", "'channel'", ")", ".", "then", "(", "function", "(", "id", ")", "{", "aliceChannel", "=", "datachan", "(", "id", ")", ";", "aliceChannel", ".", "on", "(", "'onopen'", ",", "function", "(", ")", "{", "if", "(", "payload", "instanceof", "ArrayBuffer", ")", "{", "aliceChannel", ".", "sendBuffer", "(", "payload", ")", ";", "}", "else", "{", "aliceChannel", ".", "send", "(", "payload", ")", ";", "}", "}", ")", ";", "aliceChannel", ".", "setBinaryType", "(", "'arraybuffer'", ")", ".", "then", "(", "function", "(", ")", "{", "return", "alice", ".", "createOffer", "(", ")", ";", "}", ")", ".", "then", "(", "function", "(", "offer", ")", "{", "alice", ".", "setLocalDescription", "(", "offer", ")", ";", "aliceOffer", "=", "offer", ";", "}", ")", ";", "}", ",", "function", "(", "err", ")", "{", "console", ".", "error", "(", "'RTC failed: '", ",", "err", ")", ";", "}", ")", ";", "}" ]
Establishes a peerconnection with one datachannel, sends a message on the datachannel and calls back with the message received by the other peer.
[ "Establishes", "a", "peerconnection", "with", "one", "datachannel", "sends", "a", "message", "on", "the", "datachannel", "and", "calls", "back", "with", "the", "message", "received", "by", "the", "other", "peer", "." ]
9638e840aec9598c4d60383ed22444c525aefbf5
https://github.com/freedomjs/freedom/blob/9638e840aec9598c4d60383ed22444c525aefbf5/spec/providers/coreIntegration/rtcpeerconnection.integration.src.js#L19-L77
22,193
freedomjs/freedom
spec/providers/transport/transport.webrtc.unit.spec.js
makeEventTarget
function makeEventTarget(target) { var listeners = {}; target.on = function(event, func) { if (listeners[event]) { listeners[event].push(func); } else { listeners[event] = [func]; } }; target.fireEvent = function(event, data) { expect(target.on).toHaveBeenCalledWith(event, jasmine.any(Function)); listeners[event].forEach(function(listener) { listener(data); }); }; target.removeListeners = function() { listeners = {}; }; spyOn(target, "on").and.callThrough(); }
javascript
function makeEventTarget(target) { var listeners = {}; target.on = function(event, func) { if (listeners[event]) { listeners[event].push(func); } else { listeners[event] = [func]; } }; target.fireEvent = function(event, data) { expect(target.on).toHaveBeenCalledWith(event, jasmine.any(Function)); listeners[event].forEach(function(listener) { listener(data); }); }; target.removeListeners = function() { listeners = {}; }; spyOn(target, "on").and.callThrough(); }
[ "function", "makeEventTarget", "(", "target", ")", "{", "var", "listeners", "=", "{", "}", ";", "target", ".", "on", "=", "function", "(", "event", ",", "func", ")", "{", "if", "(", "listeners", "[", "event", "]", ")", "{", "listeners", "[", "event", "]", ".", "push", "(", "func", ")", ";", "}", "else", "{", "listeners", "[", "event", "]", "=", "[", "func", "]", ";", "}", "}", ";", "target", ".", "fireEvent", "=", "function", "(", "event", ",", "data", ")", "{", "expect", "(", "target", ".", "on", ")", ".", "toHaveBeenCalledWith", "(", "event", ",", "jasmine", ".", "any", "(", "Function", ")", ")", ";", "listeners", "[", "event", "]", ".", "forEach", "(", "function", "(", "listener", ")", "{", "listener", "(", "data", ")", ";", "}", ")", ";", "}", ";", "target", ".", "removeListeners", "=", "function", "(", ")", "{", "listeners", "=", "{", "}", ";", "}", ";", "spyOn", "(", "target", ",", "\"on\"", ")", ".", "and", ".", "callThrough", "(", ")", ";", "}" ]
Adds "on" listener that can register event listeners, which can later be fired through "fireEvent". It is expected that listeners will be regstered before events are fired.
[ "Adds", "on", "listener", "that", "can", "register", "event", "listeners", "which", "can", "later", "be", "fired", "through", "fireEvent", ".", "It", "is", "expected", "that", "listeners", "will", "be", "regstered", "before", "events", "are", "fired", "." ]
9638e840aec9598c4d60383ed22444c525aefbf5
https://github.com/freedomjs/freedom/blob/9638e840aec9598c4d60383ed22444c525aefbf5/spec/providers/transport/transport.webrtc.unit.spec.js#L35-L54
22,194
freedomjs/freedom
spec/providers/transport/transport.webrtc.unit.spec.js
function() { var iface = testUtil.mockIface([ ["setup", undefined], ["send", undefined], ["openDataChannel", undefined], ["close", undefined], ["getBufferedAmount", 0] ]); peerconnection = iface(); makeEventTarget(peerconnection); return peerconnection; }
javascript
function() { var iface = testUtil.mockIface([ ["setup", undefined], ["send", undefined], ["openDataChannel", undefined], ["close", undefined], ["getBufferedAmount", 0] ]); peerconnection = iface(); makeEventTarget(peerconnection); return peerconnection; }
[ "function", "(", ")", "{", "var", "iface", "=", "testUtil", ".", "mockIface", "(", "[", "[", "\"setup\"", ",", "undefined", "]", ",", "[", "\"send\"", ",", "undefined", "]", ",", "[", "\"openDataChannel\"", ",", "undefined", "]", ",", "[", "\"close\"", ",", "undefined", "]", ",", "[", "\"getBufferedAmount\"", ",", "0", "]", "]", ")", ";", "peerconnection", "=", "iface", "(", ")", ";", "makeEventTarget", "(", "peerconnection", ")", ";", "return", "peerconnection", ";", "}" ]
We can't use mockIface alone, we need to make peerconnection an event target.
[ "We", "can", "t", "use", "mockIface", "alone", "we", "need", "to", "make", "peerconnection", "an", "event", "target", "." ]
9638e840aec9598c4d60383ed22444c525aefbf5
https://github.com/freedomjs/freedom/blob/9638e840aec9598c4d60383ed22444c525aefbf5/spec/providers/transport/transport.webrtc.unit.spec.js#L62-L73
22,195
freedomjs/freedom
src/consumer.js
function (interfaceCls, debug) { this.id = Consumer.nextId(); this.interfaceCls = interfaceCls; this.debug = debug; util.handleEvents(this); this.ifaces = {}; this.closeHandlers = {}; this.errorHandlers = {}; this.emits = {}; }
javascript
function (interfaceCls, debug) { this.id = Consumer.nextId(); this.interfaceCls = interfaceCls; this.debug = debug; util.handleEvents(this); this.ifaces = {}; this.closeHandlers = {}; this.errorHandlers = {}; this.emits = {}; }
[ "function", "(", "interfaceCls", ",", "debug", ")", "{", "this", ".", "id", "=", "Consumer", ".", "nextId", "(", ")", ";", "this", ".", "interfaceCls", "=", "interfaceCls", ";", "this", ".", "debug", "=", "debug", ";", "util", ".", "handleEvents", "(", "this", ")", ";", "this", ".", "ifaces", "=", "{", "}", ";", "this", ".", "closeHandlers", "=", "{", "}", ";", "this", ".", "errorHandlers", "=", "{", "}", ";", "this", ".", "emits", "=", "{", "}", ";", "}" ]
A freedom port for a user-accessable api. @class Consumer @implements Port @uses handleEvents @param {Object} interfaceCls The api interface exposed by this consumer. @param {Debug} debug The debugger to use for logging. @constructor
[ "A", "freedom", "port", "for", "a", "user", "-", "accessable", "api", "." ]
9638e840aec9598c4d60383ed22444c525aefbf5
https://github.com/freedomjs/freedom/blob/9638e840aec9598c4d60383ed22444c525aefbf5/src/consumer.js#L14-L24
22,196
jarradseers/consign
lib/consign.js
Consign
function Consign(options) { options = options || {}; this._options = { cwd: process.cwd(), locale: 'en-us', logger: console, verbose: true, extensions: [], loggingType: 'info' }; this._files = []; this._object = {}; this._extensions = this._options.extensions.concat(['.js', '.json', '.node']); this._lastOperation = 'include'; if (options.extensions) { this._extensions.concat(options.extensions); } for (var o in options) { this._options[o] = options[o]; } this._ = require(path.join(__dirname, '..', 'locale', this._options.locale)); this._log([pack.name, 'v' + pack.version, this._['Initialized in'], this._options.cwd]); return this; }
javascript
function Consign(options) { options = options || {}; this._options = { cwd: process.cwd(), locale: 'en-us', logger: console, verbose: true, extensions: [], loggingType: 'info' }; this._files = []; this._object = {}; this._extensions = this._options.extensions.concat(['.js', '.json', '.node']); this._lastOperation = 'include'; if (options.extensions) { this._extensions.concat(options.extensions); } for (var o in options) { this._options[o] = options[o]; } this._ = require(path.join(__dirname, '..', 'locale', this._options.locale)); this._log([pack.name, 'v' + pack.version, this._['Initialized in'], this._options.cwd]); return this; }
[ "function", "Consign", "(", "options", ")", "{", "options", "=", "options", "||", "{", "}", ";", "this", ".", "_options", "=", "{", "cwd", ":", "process", ".", "cwd", "(", ")", ",", "locale", ":", "'en-us'", ",", "logger", ":", "console", ",", "verbose", ":", "true", ",", "extensions", ":", "[", "]", ",", "loggingType", ":", "'info'", "}", ";", "this", ".", "_files", "=", "[", "]", ";", "this", ".", "_object", "=", "{", "}", ";", "this", ".", "_extensions", "=", "this", ".", "_options", ".", "extensions", ".", "concat", "(", "[", "'.js'", ",", "'.json'", ",", "'.node'", "]", ")", ";", "this", ".", "_lastOperation", "=", "'include'", ";", "if", "(", "options", ".", "extensions", ")", "{", "this", ".", "_extensions", ".", "concat", "(", "options", ".", "extensions", ")", ";", "}", "for", "(", "var", "o", "in", "options", ")", "{", "this", ".", "_options", "[", "o", "]", "=", "options", "[", "o", "]", ";", "}", "this", ".", "_", "=", "require", "(", "path", ".", "join", "(", "__dirname", ",", "'..'", ",", "'locale'", ",", "this", ".", "_options", ".", "locale", ")", ")", ";", "this", ".", "_log", "(", "[", "pack", ".", "name", ",", "'v'", "+", "pack", ".", "version", ",", "this", ".", "_", "[", "'Initialized in'", "]", ",", "this", ".", "_options", ".", "cwd", "]", ")", ";", "return", "this", ";", "}" ]
Consign constructor. @param options @returns
[ "Consign", "constructor", "." ]
45c69476c421fde6f45e18221ade5d1755523483
https://github.com/jarradseers/consign/blob/45c69476c421fde6f45e18221ade5d1755523483/lib/consign.js#L24-L54
22,197
vissense/vissense
lib/vissense.js
extend
function extend(dest, source, callback) { var index = -1, props = Object.keys(source), length = props.length, ask = isFunction(callback); while (++index < length) { var key = props[index]; dest[key] = ask ? callback(dest[key], source[key], key, dest, source) : source[key]; } return dest; }
javascript
function extend(dest, source, callback) { var index = -1, props = Object.keys(source), length = props.length, ask = isFunction(callback); while (++index < length) { var key = props[index]; dest[key] = ask ? callback(dest[key], source[key], key, dest, source) : source[key]; } return dest; }
[ "function", "extend", "(", "dest", ",", "source", ",", "callback", ")", "{", "var", "index", "=", "-", "1", ",", "props", "=", "Object", ".", "keys", "(", "source", ")", ",", "length", "=", "props", ".", "length", ",", "ask", "=", "isFunction", "(", "callback", ")", ";", "while", "(", "++", "index", "<", "length", ")", "{", "var", "key", "=", "props", "[", "index", "]", ";", "dest", "[", "key", "]", "=", "ask", "?", "callback", "(", "dest", "[", "key", "]", ",", "source", "[", "key", "]", ",", "key", ",", "dest", ",", "source", ")", ":", "source", "[", "key", "]", ";", "}", "return", "dest", ";", "}" ]
This callback lets you intercept the assignment of individual properties. The return value will be assigned to the `destKey` property of the `dest` object. If this callback is not provided `sourceValue` will be assigned. @callback extendCallback @memberof VisSense.Utils @param {*} destValue The destination value that will be replaced. @param {*} sourceValue The source value than will replace the destination value. @param {*} destKey The destination key. @param {*} sourceKey The source key. @param {*} dest The given destination. @param {*} source The given source. @function @name extend @memberof VisSense.Utils @param {Object} dest The destination object. @param {Object} source The source object. @param {VisSense.Utils.extendCallback} [callback] The function to customize assigning values. @returns {Object} @description Overwrites all properties of the destination object with the source object's properties. You can provide an optional callback function to modify the behaviour and/or to manipulate the return value. @example VisSense.Utils.extend({ name: 'Max', age: 31 }, { name: 'Bradley', gender: 'male' }); // => { name: 'Bradley', age: 31, gender: 'male' } VisSense.Utils.extend({ name: 'Max', age: 31 }, { name: 'Bradley', gender: 'male' }, function(destValue, srcValue, key) { if(key === 'age') return destValue + 42; return srcValue; }); // => { name: 'Bradley', age: 73, gender: 'male' }
[ "This", "callback", "lets", "you", "intercept", "the", "assignment", "of", "individual", "properties", ".", "The", "return", "value", "will", "be", "assigned", "to", "the", "destKey", "property", "of", "the", "dest", "object", ".", "If", "this", "callback", "is", "not", "provided", "sourceValue", "will", "be", "assigned", "." ]
f169c9347dc98d3895de65fbb6bcd725351d6248
https://github.com/vissense/vissense/blob/f169c9347dc98d3895de65fbb6bcd725351d6248/lib/vissense.js#L245-L258
22,198
wtfaremyinitials/osa-imessage
index.js
fromAppleTime
function fromAppleTime(ts) { if (ts == 0) { return null } // unpackTime returns 0 if the timestamp wasn't packed // TODO: see `packTimeConditionally`'s comment if (unpackTime(ts) != 0) { ts = unpackTime(ts) } return new Date((ts + DATE_OFFSET) * 1000) }
javascript
function fromAppleTime(ts) { if (ts == 0) { return null } // unpackTime returns 0 if the timestamp wasn't packed // TODO: see `packTimeConditionally`'s comment if (unpackTime(ts) != 0) { ts = unpackTime(ts) } return new Date((ts + DATE_OFFSET) * 1000) }
[ "function", "fromAppleTime", "(", "ts", ")", "{", "if", "(", "ts", "==", "0", ")", "{", "return", "null", "}", "// unpackTime returns 0 if the timestamp wasn't packed", "// TODO: see `packTimeConditionally`'s comment", "if", "(", "unpackTime", "(", "ts", ")", "!=", "0", ")", "{", "ts", "=", "unpackTime", "(", "ts", ")", "}", "return", "new", "Date", "(", "(", "ts", "+", "DATE_OFFSET", ")", "*", "1000", ")", "}" ]
Transforms an Apple-style timestamp to a proper unix timestamp
[ "Transforms", "an", "Apple", "-", "style", "timestamp", "to", "a", "proper", "unix", "timestamp" ]
6532d837524d86d6cabdb7d1ce75fc1fab462044
https://github.com/wtfaremyinitials/osa-imessage/blob/6532d837524d86d6cabdb7d1ce75fc1fab462044/index.js#L44-L56
22,199
wtfaremyinitials/osa-imessage
index.js
handleForName
function handleForName(name) { assert(typeof name == 'string', 'name must be a string') return osa(name => { const Messages = Application('Messages') return Messages.buddies.whose({ name: name })[0].handle() })(name) }
javascript
function handleForName(name) { assert(typeof name == 'string', 'name must be a string') return osa(name => { const Messages = Application('Messages') return Messages.buddies.whose({ name: name })[0].handle() })(name) }
[ "function", "handleForName", "(", "name", ")", "{", "assert", "(", "typeof", "name", "==", "'string'", ",", "'name must be a string'", ")", "return", "osa", "(", "name", "=>", "{", "const", "Messages", "=", "Application", "(", "'Messages'", ")", "return", "Messages", ".", "buddies", ".", "whose", "(", "{", "name", ":", "name", "}", ")", "[", "0", "]", ".", "handle", "(", ")", "}", ")", "(", "name", ")", "}" ]
Gets the proper handle string for a contact with the given name
[ "Gets", "the", "proper", "handle", "string", "for", "a", "contact", "with", "the", "given", "name" ]
6532d837524d86d6cabdb7d1ce75fc1fab462044
https://github.com/wtfaremyinitials/osa-imessage/blob/6532d837524d86d6cabdb7d1ce75fc1fab462044/index.js#L76-L82