repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
sequence
docstring
stringlengths
4
11.8k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
86
226
partition
stringclasses
1 value
unbalanced/grunt-simple-watch
tasks/simple_watch.js
fileChanged
function fileChanged(status, filepath) { // If file was deleted and then re-added, consider it changed. if (changedFiles[filepath] === 'deleted' && status === 'added') { status = 'changed'; } // Keep track of changed status for later. changedFiles[filepath] = status; // Emit watch events if anyone is listening if (grunt.event.listeners('watch').length > 0) { var matchingTargets = []; targets.forEach(function(target) { if (grunt.file.match(target.files, filepath).length > 0) { matchingTargets.push(target.name); } }); matchingTargets.forEach(function(matchingTarget) { grunt.event.emit('watch', status, filepath, matchingTarget); }); } // Keep track of changed status for later. changedFiles[filepath] = status; // Execute debounced done function. done(); }
javascript
function fileChanged(status, filepath) { // If file was deleted and then re-added, consider it changed. if (changedFiles[filepath] === 'deleted' && status === 'added') { status = 'changed'; } // Keep track of changed status for later. changedFiles[filepath] = status; // Emit watch events if anyone is listening if (grunt.event.listeners('watch').length > 0) { var matchingTargets = []; targets.forEach(function(target) { if (grunt.file.match(target.files, filepath).length > 0) { matchingTargets.push(target.name); } }); matchingTargets.forEach(function(matchingTarget) { grunt.event.emit('watch', status, filepath, matchingTarget); }); } // Keep track of changed status for later. changedFiles[filepath] = status; // Execute debounced done function. done(); }
[ "function", "fileChanged", "(", "status", ",", "filepath", ")", "{", "if", "(", "changedFiles", "[", "filepath", "]", "===", "'deleted'", "&&", "status", "===", "'added'", ")", "{", "status", "=", "'changed'", ";", "}", "changedFiles", "[", "filepath", "]", "=", "status", ";", "if", "(", "grunt", ".", "event", ".", "listeners", "(", "'watch'", ")", ".", "length", ">", "0", ")", "{", "var", "matchingTargets", "=", "[", "]", ";", "targets", ".", "forEach", "(", "function", "(", "target", ")", "{", "if", "(", "grunt", ".", "file", ".", "match", "(", "target", ".", "files", ",", "filepath", ")", ".", "length", ">", "0", ")", "{", "matchingTargets", ".", "push", "(", "target", ".", "name", ")", ";", "}", "}", ")", ";", "matchingTargets", ".", "forEach", "(", "function", "(", "matchingTarget", ")", "{", "grunt", ".", "event", ".", "emit", "(", "'watch'", ",", "status", ",", "filepath", ",", "matchingTarget", ")", ";", "}", ")", ";", "}", "changedFiles", "[", "filepath", "]", "=", "status", ";", "done", "(", ")", ";", "}" ]
Handle file changes.
[ "Handle", "file", "changes", "." ]
893ef26b3cb4955d338723196315e6b6be55d7d1
https://github.com/unbalanced/grunt-simple-watch/blob/893ef26b3cb4955d338723196315e6b6be55d7d1/tasks/simple_watch.js#L112-L135
train
unbalanced/grunt-simple-watch
tasks/simple_watch.js
watchFile
function watchFile(filepath) { if (!watchedFiles[filepath]) { // add a new file to watched files var statStructure = null; try { statStructure = fs.statSync(filepath); } catch (e) { // StatSync can throw an error if the file has dissapeared in between return; } watchedFiles[filepath] = statStructure; mtimes[filepath] = +watchedFiles[filepath].mtime; } }
javascript
function watchFile(filepath) { if (!watchedFiles[filepath]) { // add a new file to watched files var statStructure = null; try { statStructure = fs.statSync(filepath); } catch (e) { // StatSync can throw an error if the file has dissapeared in between return; } watchedFiles[filepath] = statStructure; mtimes[filepath] = +watchedFiles[filepath].mtime; } }
[ "function", "watchFile", "(", "filepath", ")", "{", "if", "(", "!", "watchedFiles", "[", "filepath", "]", ")", "{", "var", "statStructure", "=", "null", ";", "try", "{", "statStructure", "=", "fs", ".", "statSync", "(", "filepath", ")", ";", "}", "catch", "(", "e", ")", "{", "return", ";", "}", "watchedFiles", "[", "filepath", "]", "=", "statStructure", ";", "mtimes", "[", "filepath", "]", "=", "+", "watchedFiles", "[", "filepath", "]", ".", "mtime", ";", "}", "}" ]
Watch a file.
[ "Watch", "a", "file", "." ]
893ef26b3cb4955d338723196315e6b6be55d7d1
https://github.com/unbalanced/grunt-simple-watch/blob/893ef26b3cb4955d338723196315e6b6be55d7d1/tasks/simple_watch.js#L138-L151
train
grasshopper-cms/grasshopper-core-nodejs
docs/js/vendor/imagesloaded.js
makeArray
function makeArray( obj ) { var ary = []; if ( isArray( obj ) ) { // use object if already an array ary = obj; } else if ( typeof obj.length === 'number' ) { // convert nodeList to array for ( var i=0, len = obj.length; i < len; i++ ) { ary.push( obj[i] ); } } else { // array of single index ary.push( obj ); } return ary; }
javascript
function makeArray( obj ) { var ary = []; if ( isArray( obj ) ) { // use object if already an array ary = obj; } else if ( typeof obj.length === 'number' ) { // convert nodeList to array for ( var i=0, len = obj.length; i < len; i++ ) { ary.push( obj[i] ); } } else { // array of single index ary.push( obj ); } return ary; }
[ "function", "makeArray", "(", "obj", ")", "{", "var", "ary", "=", "[", "]", ";", "if", "(", "isArray", "(", "obj", ")", ")", "{", "ary", "=", "obj", ";", "}", "else", "if", "(", "typeof", "obj", ".", "length", "===", "'number'", ")", "{", "for", "(", "var", "i", "=", "0", ",", "len", "=", "obj", ".", "length", ";", "i", "<", "len", ";", "i", "++", ")", "{", "ary", ".", "push", "(", "obj", "[", "i", "]", ")", ";", "}", "}", "else", "{", "ary", ".", "push", "(", "obj", ")", ";", "}", "return", "ary", ";", "}" ]
turn element or nodeList into an array
[ "turn", "element", "or", "nodeList", "into", "an", "array" ]
8fabc3bfc5b18855ead443db0644608a277d0ea0
https://github.com/grasshopper-cms/grasshopper-core-nodejs/blob/8fabc3bfc5b18855ead443db0644608a277d0ea0/docs/js/vendor/imagesloaded.js#L589-L604
train
stealjs/steal-npm
npm-crawl.js
function(context, pkg, source) { source = source || "{}"; var packageJSON = JSON.parse(source); utils.extend(pkg, packageJSON); context.packages.push(pkg); return pkg; }
javascript
function(context, pkg, source) { source = source || "{}"; var packageJSON = JSON.parse(source); utils.extend(pkg, packageJSON); context.packages.push(pkg); return pkg; }
[ "function", "(", "context", ",", "pkg", ",", "source", ")", "{", "source", "=", "source", "||", "\"{}\"", ";", "var", "packageJSON", "=", "JSON", ".", "parse", "(", "source", ")", ";", "utils", ".", "extend", "(", "pkg", ",", "packageJSON", ")", ";", "context", ".", "packages", ".", "push", "(", "pkg", ")", ";", "return", "pkg", ";", "}" ]
Adds the properties read from a package's source to the `pkg` object. @param {Object} context @param {NpmPackage} pkg - @param {String} source @return {NpmPackage}
[ "Adds", "the", "properties", "read", "from", "a", "package", "s", "source", "to", "the", "pkg", "object", "." ]
216463c552cabe7d9dad86d754da784b5dea3d78
https://github.com/stealjs/steal-npm/blob/216463c552cabe7d9dad86d754da784b5dea3d78/npm-crawl.js#L17-L23
train
stealjs/steal-npm
npm-crawl.js
function(context, pkg){ var deps = crawl.getDependencyMap(context.loader, pkg, true); var pluginsPromise = crawl.loadPlugins(context, pkg, true, deps, true); var stealPromise = crawl.loadSteal(context, pkg, true, deps); return Promise.all([pluginsPromise, stealPromise]); }
javascript
function(context, pkg){ var deps = crawl.getDependencyMap(context.loader, pkg, true); var pluginsPromise = crawl.loadPlugins(context, pkg, true, deps, true); var stealPromise = crawl.loadSteal(context, pkg, true, deps); return Promise.all([pluginsPromise, stealPromise]); }
[ "function", "(", "context", ",", "pkg", ")", "{", "var", "deps", "=", "crawl", ".", "getDependencyMap", "(", "context", ".", "loader", ",", "pkg", ",", "true", ")", ";", "var", "pluginsPromise", "=", "crawl", ".", "loadPlugins", "(", "context", ",", "pkg", ",", "true", ",", "deps", ",", "true", ")", ";", "var", "stealPromise", "=", "crawl", ".", "loadSteal", "(", "context", ",", "pkg", ",", "true", ",", "deps", ")", ";", "return", "Promise", ".", "all", "(", "[", "pluginsPromise", ",", "stealPromise", "]", ")", ";", "}" ]
Crawl from the root, only fetching Steal and its dependencies so that Node built-ins are autoconfigured.
[ "Crawl", "from", "the", "root", "only", "fetching", "Steal", "and", "its", "dependencies", "so", "that", "Node", "built", "-", "ins", "are", "autoconfigured", "." ]
216463c552cabe7d9dad86d754da784b5dea3d78
https://github.com/stealjs/steal-npm/blob/216463c552cabe7d9dad86d754da784b5dea3d78/npm-crawl.js#L28-L35
train
stealjs/steal-npm
npm-crawl.js
function(context, pkg, isRoot) { var deps = crawl.getDependencies(context.loader, pkg, isRoot); return Promise.all(utils.filter(utils.map(deps, function(childPkg){ return crawl.fetchDep(context, pkg, childPkg, isRoot); }), truthy)).then(function(packages){ // at this point all dependencies of pkg have been loaded, it's ok to get their children return Promise.all(utils.map(packages, function(childPkg){ // Also load 'steal' so that the builtins will be configured if(childPkg && childPkg.name === 'steal') { return crawl.deps(context, childPkg); } })).then(function(){ return packages; }); }); }
javascript
function(context, pkg, isRoot) { var deps = crawl.getDependencies(context.loader, pkg, isRoot); return Promise.all(utils.filter(utils.map(deps, function(childPkg){ return crawl.fetchDep(context, pkg, childPkg, isRoot); }), truthy)).then(function(packages){ // at this point all dependencies of pkg have been loaded, it's ok to get their children return Promise.all(utils.map(packages, function(childPkg){ // Also load 'steal' so that the builtins will be configured if(childPkg && childPkg.name === 'steal') { return crawl.deps(context, childPkg); } })).then(function(){ return packages; }); }); }
[ "function", "(", "context", ",", "pkg", ",", "isRoot", ")", "{", "var", "deps", "=", "crawl", ".", "getDependencies", "(", "context", ".", "loader", ",", "pkg", ",", "isRoot", ")", ";", "return", "Promise", ".", "all", "(", "utils", ".", "filter", "(", "utils", ".", "map", "(", "deps", ",", "function", "(", "childPkg", ")", "{", "return", "crawl", ".", "fetchDep", "(", "context", ",", "pkg", ",", "childPkg", ",", "isRoot", ")", ";", "}", ")", ",", "truthy", ")", ")", ".", "then", "(", "function", "(", "packages", ")", "{", "return", "Promise", ".", "all", "(", "utils", ".", "map", "(", "packages", ",", "function", "(", "childPkg", ")", "{", "if", "(", "childPkg", "&&", "childPkg", ".", "name", "===", "'steal'", ")", "{", "return", "crawl", ".", "deps", "(", "context", ",", "childPkg", ")", ";", "}", "}", ")", ")", ".", "then", "(", "function", "(", ")", "{", "return", "packages", ";", "}", ")", ";", "}", ")", ";", "}" ]
Crawls the packages dependencies @param {Object} context @param {NpmPackage} pkg @param {Boolean} [isRoot] If the root module's dependencies should be crawled. @return {Promise} A promise when all packages have been loaded
[ "Crawls", "the", "packages", "dependencies" ]
216463c552cabe7d9dad86d754da784b5dea3d78
https://github.com/stealjs/steal-npm/blob/216463c552cabe7d9dad86d754da784b5dea3d78/npm-crawl.js#L43-L60
train
stealjs/steal-npm
npm-crawl.js
function(context, parentPkg, childPkg, isRoot){ var pkg = parentPkg; var isFlat = context.isFlatFileStructure; // if a peer dependency, and not isRoot if(childPkg._isPeerDependency && !isRoot ) { // check one node_module level higher childPkg.origFileUrl = nodeModuleAddress(pkg.fileUrl)+"/"+childPkg.name+"/package.json"; } else if(isRoot) { childPkg.origFileUrl = utils.path.depPackage(pkg.fileUrl, childPkg.name); } else { // npm 2 childPkg.origFileUrl = childPkg.nestedFileUrl = utils.path.depPackage(pkg.fileUrl, childPkg.name); if(isFlat) { // npm 3 childPkg.origFileUrl = crawl.parentMostAddress(context, childPkg); } } // check if childPkg matches a parent's version ... if it // does ... do nothing if(crawl.hasParentPackageThatMatches(context, childPkg)) { return; } if(crawl.isSameRequestedVersionFound(context, childPkg)) { return; } var requestedVersion = childPkg.version; return npmLoad(context, childPkg, requestedVersion) .then(function(pkg){ crawl.setVersionsConfig(context, pkg, requestedVersion); return pkg; }); }
javascript
function(context, parentPkg, childPkg, isRoot){ var pkg = parentPkg; var isFlat = context.isFlatFileStructure; // if a peer dependency, and not isRoot if(childPkg._isPeerDependency && !isRoot ) { // check one node_module level higher childPkg.origFileUrl = nodeModuleAddress(pkg.fileUrl)+"/"+childPkg.name+"/package.json"; } else if(isRoot) { childPkg.origFileUrl = utils.path.depPackage(pkg.fileUrl, childPkg.name); } else { // npm 2 childPkg.origFileUrl = childPkg.nestedFileUrl = utils.path.depPackage(pkg.fileUrl, childPkg.name); if(isFlat) { // npm 3 childPkg.origFileUrl = crawl.parentMostAddress(context, childPkg); } } // check if childPkg matches a parent's version ... if it // does ... do nothing if(crawl.hasParentPackageThatMatches(context, childPkg)) { return; } if(crawl.isSameRequestedVersionFound(context, childPkg)) { return; } var requestedVersion = childPkg.version; return npmLoad(context, childPkg, requestedVersion) .then(function(pkg){ crawl.setVersionsConfig(context, pkg, requestedVersion); return pkg; }); }
[ "function", "(", "context", ",", "parentPkg", ",", "childPkg", ",", "isRoot", ")", "{", "var", "pkg", "=", "parentPkg", ";", "var", "isFlat", "=", "context", ".", "isFlatFileStructure", ";", "if", "(", "childPkg", ".", "_isPeerDependency", "&&", "!", "isRoot", ")", "{", "childPkg", ".", "origFileUrl", "=", "nodeModuleAddress", "(", "pkg", ".", "fileUrl", ")", "+", "\"/\"", "+", "childPkg", ".", "name", "+", "\"/package.json\"", ";", "}", "else", "if", "(", "isRoot", ")", "{", "childPkg", ".", "origFileUrl", "=", "utils", ".", "path", ".", "depPackage", "(", "pkg", ".", "fileUrl", ",", "childPkg", ".", "name", ")", ";", "}", "else", "{", "childPkg", ".", "origFileUrl", "=", "childPkg", ".", "nestedFileUrl", "=", "utils", ".", "path", ".", "depPackage", "(", "pkg", ".", "fileUrl", ",", "childPkg", ".", "name", ")", ";", "if", "(", "isFlat", ")", "{", "childPkg", ".", "origFileUrl", "=", "crawl", ".", "parentMostAddress", "(", "context", ",", "childPkg", ")", ";", "}", "}", "if", "(", "crawl", ".", "hasParentPackageThatMatches", "(", "context", ",", "childPkg", ")", ")", "{", "return", ";", "}", "if", "(", "crawl", ".", "isSameRequestedVersionFound", "(", "context", ",", "childPkg", ")", ")", "{", "return", ";", "}", "var", "requestedVersion", "=", "childPkg", ".", "version", ";", "return", "npmLoad", "(", "context", ",", "childPkg", ",", "requestedVersion", ")", ".", "then", "(", "function", "(", "pkg", ")", "{", "crawl", ".", "setVersionsConfig", "(", "context", ",", "pkg", ",", "requestedVersion", ")", ";", "return", "pkg", ";", "}", ")", ";", "}" ]
Fetch a particular package.json dependency @param {Object} context @param {NpmPackage} parentPkg @param {NpmPackage} childPkg @param {Boolean} [isRoot] If the root module's dependencies shoudl be crawled. @return {Promise} A promise when the package has loaded
[ "Fetch", "a", "particular", "package", ".", "json", "dependency" ]
216463c552cabe7d9dad86d754da784b5dea3d78
https://github.com/stealjs/steal-npm/blob/216463c552cabe7d9dad86d754da784b5dea3d78/npm-crawl.js#L129-L167
train
stealjs/steal-npm
npm-crawl.js
function(context, pkg, isRoot, deps){ var stealPkg = utils.filter(deps, function(dep){ return dep && dep.name === "steal"; })[0]; if(stealPkg) { return crawl.fetchDep(context, pkg, stealPkg, isRoot) .then(function(childPkg){ if(childPkg) { return crawl.deps(context, childPkg); } }); } else { return Promise.resolve(); } }
javascript
function(context, pkg, isRoot, deps){ var stealPkg = utils.filter(deps, function(dep){ return dep && dep.name === "steal"; })[0]; if(stealPkg) { return crawl.fetchDep(context, pkg, stealPkg, isRoot) .then(function(childPkg){ if(childPkg) { return crawl.deps(context, childPkg); } }); } else { return Promise.resolve(); } }
[ "function", "(", "context", ",", "pkg", ",", "isRoot", ",", "deps", ")", "{", "var", "stealPkg", "=", "utils", ".", "filter", "(", "deps", ",", "function", "(", "dep", ")", "{", "return", "dep", "&&", "dep", ".", "name", "===", "\"steal\"", ";", "}", ")", "[", "0", "]", ";", "if", "(", "stealPkg", ")", "{", "return", "crawl", ".", "fetchDep", "(", "context", ",", "pkg", ",", "stealPkg", ",", "isRoot", ")", ".", "then", "(", "function", "(", "childPkg", ")", "{", "if", "(", "childPkg", ")", "{", "return", "crawl", ".", "deps", "(", "context", ",", "childPkg", ")", ";", "}", "}", ")", ";", "}", "else", "{", "return", "Promise", ".", "resolve", "(", ")", ";", "}", "}" ]
Load steal and its dependencies, if needed
[ "Load", "steal", "and", "its", "dependencies", "if", "needed" ]
216463c552cabe7d9dad86d754da784b5dea3d78
https://github.com/stealjs/steal-npm/blob/216463c552cabe7d9dad86d754da784b5dea3d78/npm-crawl.js#L183-L198
train
stealjs/steal-npm
npm-crawl.js
function(loader, packageJSON, isRoot){ var deps = crawl.getDependencyMap(loader, packageJSON, isRoot); var dependencies = []; for(var name in deps) { dependencies.push(deps[name]); } return dependencies; }
javascript
function(loader, packageJSON, isRoot){ var deps = crawl.getDependencyMap(loader, packageJSON, isRoot); var dependencies = []; for(var name in deps) { dependencies.push(deps[name]); } return dependencies; }
[ "function", "(", "loader", ",", "packageJSON", ",", "isRoot", ")", "{", "var", "deps", "=", "crawl", ".", "getDependencyMap", "(", "loader", ",", "packageJSON", ",", "isRoot", ")", ";", "var", "dependencies", "=", "[", "]", ";", "for", "(", "var", "name", "in", "deps", ")", "{", "dependencies", ".", "push", "(", "deps", "[", "name", "]", ")", ";", "}", "return", "dependencies", ";", "}" ]
Returns an array of the dependency names that should be crawled. @param {Object} loader @param {NpmPackage} packageJSON @param {Boolean} [isRoot] @return {Array<String>}
[ "Returns", "an", "array", "of", "the", "dependency", "names", "that", "should", "be", "crawled", "." ]
216463c552cabe7d9dad86d754da784b5dea3d78
https://github.com/stealjs/steal-npm/blob/216463c552cabe7d9dad86d754da784b5dea3d78/npm-crawl.js#L206-L215
train
stealjs/steal-npm
npm-crawl.js
function(loader, packageJSON, isRoot){ var config = utils.pkg.config(packageJSON); var hasConfig = !!config; // convert npmIgnore var npmIgnore = hasConfig && config.npmIgnore; function convertToMap(arr) { var npmMap = {}; for(var i = 0; i < arr.length; i++) { npmMap[arr[i]] = true; } return npmMap; } if(npmIgnore && typeof npmIgnore.length === 'number') { npmIgnore = config.npmIgnore = convertToMap(npmIgnore); } // convert npmDependencies var npmDependencies = hasConfig && config.npmDependencies; if(npmDependencies && typeof npmDependencies.length === "number") { config.npmDependencies = convertToMap(npmDependencies); } npmIgnore = npmIgnore || {}; var deps = {}; addDeps(packageJSON, packageJSON.peerDependencies || {}, deps, "peerDependencies", {_isPeerDependency: true}); addDeps(packageJSON, packageJSON.dependencies || {}, deps, "dependencies"); if(isRoot) { addDeps(packageJSON, packageJSON.devDependencies || {}, deps, "devDependencies"); } return deps; }
javascript
function(loader, packageJSON, isRoot){ var config = utils.pkg.config(packageJSON); var hasConfig = !!config; // convert npmIgnore var npmIgnore = hasConfig && config.npmIgnore; function convertToMap(arr) { var npmMap = {}; for(var i = 0; i < arr.length; i++) { npmMap[arr[i]] = true; } return npmMap; } if(npmIgnore && typeof npmIgnore.length === 'number') { npmIgnore = config.npmIgnore = convertToMap(npmIgnore); } // convert npmDependencies var npmDependencies = hasConfig && config.npmDependencies; if(npmDependencies && typeof npmDependencies.length === "number") { config.npmDependencies = convertToMap(npmDependencies); } npmIgnore = npmIgnore || {}; var deps = {}; addDeps(packageJSON, packageJSON.peerDependencies || {}, deps, "peerDependencies", {_isPeerDependency: true}); addDeps(packageJSON, packageJSON.dependencies || {}, deps, "dependencies"); if(isRoot) { addDeps(packageJSON, packageJSON.devDependencies || {}, deps, "devDependencies"); } return deps; }
[ "function", "(", "loader", ",", "packageJSON", ",", "isRoot", ")", "{", "var", "config", "=", "utils", ".", "pkg", ".", "config", "(", "packageJSON", ")", ";", "var", "hasConfig", "=", "!", "!", "config", ";", "var", "npmIgnore", "=", "hasConfig", "&&", "config", ".", "npmIgnore", ";", "function", "convertToMap", "(", "arr", ")", "{", "var", "npmMap", "=", "{", "}", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "arr", ".", "length", ";", "i", "++", ")", "{", "npmMap", "[", "arr", "[", "i", "]", "]", "=", "true", ";", "}", "return", "npmMap", ";", "}", "if", "(", "npmIgnore", "&&", "typeof", "npmIgnore", ".", "length", "===", "'number'", ")", "{", "npmIgnore", "=", "config", ".", "npmIgnore", "=", "convertToMap", "(", "npmIgnore", ")", ";", "}", "var", "npmDependencies", "=", "hasConfig", "&&", "config", ".", "npmDependencies", ";", "if", "(", "npmDependencies", "&&", "typeof", "npmDependencies", ".", "length", "===", "\"number\"", ")", "{", "config", ".", "npmDependencies", "=", "convertToMap", "(", "npmDependencies", ")", ";", "}", "npmIgnore", "=", "npmIgnore", "||", "{", "}", ";", "var", "deps", "=", "{", "}", ";", "addDeps", "(", "packageJSON", ",", "packageJSON", ".", "peerDependencies", "||", "{", "}", ",", "deps", ",", "\"peerDependencies\"", ",", "{", "_isPeerDependency", ":", "true", "}", ")", ";", "addDeps", "(", "packageJSON", ",", "packageJSON", ".", "dependencies", "||", "{", "}", ",", "deps", ",", "\"dependencies\"", ")", ";", "if", "(", "isRoot", ")", "{", "addDeps", "(", "packageJSON", ",", "packageJSON", ".", "devDependencies", "||", "{", "}", ",", "deps", ",", "\"devDependencies\"", ")", ";", "}", "return", "deps", ";", "}" ]
Returns a map of the dependencies and their ranges. @param {Object} loader @param {Object} packageJSON @param {Boolean} isRoot @return {Object<String,Range>} A map of dependency names and requested version ranges.
[ "Returns", "a", "map", "of", "the", "dependencies", "and", "their", "ranges", "." ]
216463c552cabe7d9dad86d754da784b5dea3d78
https://github.com/stealjs/steal-npm/blob/216463c552cabe7d9dad86d754da784b5dea3d78/npm-crawl.js#L223-L259
train
stealjs/steal-npm
npm-crawl.js
function(context, childPkg){ var curAddress = childPkg.origFileUrl; var parentAddress = utils.path.parentNodeModuleAddress(childPkg.origFileUrl); while(parentAddress) { var packageAddress = parentAddress+"/"+childPkg.name+"/package.json"; var parentPkg = context.paths[packageAddress]; if(parentPkg && SemVer.valid(parentPkg.version)) { if(SemVer.satisfies(parentPkg.version, childPkg.version)) { return parentPkg.fileUrl; } else { return curAddress; } } parentAddress = utils.path.parentNodeModuleAddress(packageAddress); curAddress = packageAddress; } return curAddress; }
javascript
function(context, childPkg){ var curAddress = childPkg.origFileUrl; var parentAddress = utils.path.parentNodeModuleAddress(childPkg.origFileUrl); while(parentAddress) { var packageAddress = parentAddress+"/"+childPkg.name+"/package.json"; var parentPkg = context.paths[packageAddress]; if(parentPkg && SemVer.valid(parentPkg.version)) { if(SemVer.satisfies(parentPkg.version, childPkg.version)) { return parentPkg.fileUrl; } else { return curAddress; } } parentAddress = utils.path.parentNodeModuleAddress(packageAddress); curAddress = packageAddress; } return curAddress; }
[ "function", "(", "context", ",", "childPkg", ")", "{", "var", "curAddress", "=", "childPkg", ".", "origFileUrl", ";", "var", "parentAddress", "=", "utils", ".", "path", ".", "parentNodeModuleAddress", "(", "childPkg", ".", "origFileUrl", ")", ";", "while", "(", "parentAddress", ")", "{", "var", "packageAddress", "=", "parentAddress", "+", "\"/\"", "+", "childPkg", ".", "name", "+", "\"/package.json\"", ";", "var", "parentPkg", "=", "context", ".", "paths", "[", "packageAddress", "]", ";", "if", "(", "parentPkg", "&&", "SemVer", ".", "valid", "(", "parentPkg", ".", "version", ")", ")", "{", "if", "(", "SemVer", ".", "satisfies", "(", "parentPkg", ".", "version", ",", "childPkg", ".", "version", ")", ")", "{", "return", "parentPkg", ".", "fileUrl", ";", "}", "else", "{", "return", "curAddress", ";", "}", "}", "parentAddress", "=", "utils", ".", "path", ".", "parentNodeModuleAddress", "(", "packageAddress", ")", ";", "curAddress", "=", "packageAddress", ";", "}", "return", "curAddress", ";", "}" ]
Walk up the parent addresses until you run into the root or a conflicting package and return that as the address.
[ "Walk", "up", "the", "parent", "addresses", "until", "you", "run", "into", "the", "root", "or", "a", "conflicting", "package", "and", "return", "that", "as", "the", "address", "." ]
216463c552cabe7d9dad86d754da784b5dea3d78
https://github.com/stealjs/steal-npm/blob/216463c552cabe7d9dad86d754da784b5dea3d78/npm-crawl.js#L327-L344
train
stealjs/steal-npm
npm-crawl.js
function(pkg){ var pkg = pkg || this.getPackage(); var requestedVersion = this.requestedVersion; return SemVer.validRange(requestedVersion) && SemVer.valid(pkg.version) ? SemVer.satisfies(pkg.version, requestedVersion) : true; }
javascript
function(pkg){ var pkg = pkg || this.getPackage(); var requestedVersion = this.requestedVersion; return SemVer.validRange(requestedVersion) && SemVer.valid(pkg.version) ? SemVer.satisfies(pkg.version, requestedVersion) : true; }
[ "function", "(", "pkg", ")", "{", "var", "pkg", "=", "pkg", "||", "this", ".", "getPackage", "(", ")", ";", "var", "requestedVersion", "=", "this", ".", "requestedVersion", ";", "return", "SemVer", ".", "validRange", "(", "requestedVersion", ")", "&&", "SemVer", ".", "valid", "(", "pkg", ".", "version", ")", "?", "SemVer", ".", "satisfies", "(", "pkg", ".", "version", ",", "requestedVersion", ")", ":", "true", ";", "}" ]
Is the package fetched from this task a compatible version?
[ "Is", "the", "package", "fetched", "from", "this", "task", "a", "compatible", "version?" ]
216463c552cabe7d9dad86d754da784b5dea3d78
https://github.com/stealjs/steal-npm/blob/216463c552cabe7d9dad86d754da784b5dea3d78/npm-crawl.js#L523-L530
train
stealjs/steal-npm
npm-crawl.js
function(){ // If a task is currently loading this fileUrl, // wait for it to complete var loadingTask = this.context.loadingPaths[this.fileUrl]; if (!loadingTask) return; var task = this; return loadingTask.promise.then(function() { task._fetchedPackage = loadingTask.getPackage(); var firstTaskFailed = loadingTask.hadErrorLoading(); var currentTaskIsCompatible = task.isCompatibleVersion(); var firstTaskIsNotCompatible = !loadingTask.isCompatibleVersion(); // Do not flag the current task as failed if: // // - Current task fetches a version in rage and // - First task had no error loading at all or // - First task fetched an incompatible version // // otherwise, assume current task will fail for the same reason as // the first did if (currentTaskIsCompatible && (!firstTaskFailed || firstTaskIsNotCompatible)) { task.failed = false; task.error = null; } else if (!currentTaskIsCompatible) { task.failed = true; task.error = new Error("Incompatible package version requested"); } else if (firstTaskFailed) { task.failed = true; task.error = loadingTask.error; } }); }
javascript
function(){ // If a task is currently loading this fileUrl, // wait for it to complete var loadingTask = this.context.loadingPaths[this.fileUrl]; if (!loadingTask) return; var task = this; return loadingTask.promise.then(function() { task._fetchedPackage = loadingTask.getPackage(); var firstTaskFailed = loadingTask.hadErrorLoading(); var currentTaskIsCompatible = task.isCompatibleVersion(); var firstTaskIsNotCompatible = !loadingTask.isCompatibleVersion(); // Do not flag the current task as failed if: // // - Current task fetches a version in rage and // - First task had no error loading at all or // - First task fetched an incompatible version // // otherwise, assume current task will fail for the same reason as // the first did if (currentTaskIsCompatible && (!firstTaskFailed || firstTaskIsNotCompatible)) { task.failed = false; task.error = null; } else if (!currentTaskIsCompatible) { task.failed = true; task.error = new Error("Incompatible package version requested"); } else if (firstTaskFailed) { task.failed = true; task.error = loadingTask.error; } }); }
[ "function", "(", ")", "{", "var", "loadingTask", "=", "this", ".", "context", ".", "loadingPaths", "[", "this", ".", "fileUrl", "]", ";", "if", "(", "!", "loadingTask", ")", "return", ";", "var", "task", "=", "this", ";", "return", "loadingTask", ".", "promise", ".", "then", "(", "function", "(", ")", "{", "task", ".", "_fetchedPackage", "=", "loadingTask", ".", "getPackage", "(", ")", ";", "var", "firstTaskFailed", "=", "loadingTask", ".", "hadErrorLoading", "(", ")", ";", "var", "currentTaskIsCompatible", "=", "task", ".", "isCompatibleVersion", "(", ")", ";", "var", "firstTaskIsNotCompatible", "=", "!", "loadingTask", ".", "isCompatibleVersion", "(", ")", ";", "if", "(", "currentTaskIsCompatible", "&&", "(", "!", "firstTaskFailed", "||", "firstTaskIsNotCompatible", ")", ")", "{", "task", ".", "failed", "=", "false", ";", "task", ".", "error", "=", "null", ";", "}", "else", "if", "(", "!", "currentTaskIsCompatible", ")", "{", "task", ".", "failed", "=", "true", ";", "task", ".", "error", "=", "new", "Error", "(", "\"Incompatible package version requested\"", ")", ";", "}", "else", "if", "(", "firstTaskFailed", ")", "{", "task", ".", "failed", "=", "true", ";", "task", ".", "error", "=", "loadingTask", ".", "error", ";", "}", "}", ")", ";", "}" ]
Handle the case where this fileUrl is already loading
[ "Handle", "the", "case", "where", "this", "fileUrl", "is", "already", "loading" ]
216463c552cabe7d9dad86d754da784b5dea3d78
https://github.com/stealjs/steal-npm/blob/216463c552cabe7d9dad86d754da784b5dea3d78/npm-crawl.js#L555-L590
train
stealjs/steal-npm
npm-crawl.js
function(){ // If it is already loaded check to see if it's semver compatible // and if so use it. Otherwise reject. var loadedPkg = this.context.paths[this.fileUrl]; if(loadedPkg) { this._fetchedPackage = loadedPkg; if(!this.isCompatibleVersion()) { this.failed = true; } return Promise.resolve(); } }
javascript
function(){ // If it is already loaded check to see if it's semver compatible // and if so use it. Otherwise reject. var loadedPkg = this.context.paths[this.fileUrl]; if(loadedPkg) { this._fetchedPackage = loadedPkg; if(!this.isCompatibleVersion()) { this.failed = true; } return Promise.resolve(); } }
[ "function", "(", ")", "{", "var", "loadedPkg", "=", "this", ".", "context", ".", "paths", "[", "this", ".", "fileUrl", "]", ";", "if", "(", "loadedPkg", ")", "{", "this", ".", "_fetchedPackage", "=", "loadedPkg", ";", "if", "(", "!", "this", ".", "isCompatibleVersion", "(", ")", ")", "{", "this", ".", "failed", "=", "true", ";", "}", "return", "Promise", ".", "resolve", "(", ")", ";", "}", "}" ]
Handle the case where this fileUrl has already loaded.
[ "Handle", "the", "case", "where", "this", "fileUrl", "has", "already", "loaded", "." ]
216463c552cabe7d9dad86d754da784b5dea3d78
https://github.com/stealjs/steal-npm/blob/216463c552cabe7d9dad86d754da784b5dea3d78/npm-crawl.js#L595-L606
train
stealjs/steal-npm
npm-crawl.js
function(){ var pkg = utils.extend({}, this.orig); var isFlat = this.context.isFlatFileStructure; var fileUrl = this.pkg.fileUrl; var context = this.context; if(isFlat && !pkg.__crawledNestedPosition) { pkg.__crawledNestedPosition = true; pkg.nextFileUrl = pkg.nestedFileUrl; } else { // make sure we aren't loading something we've already loaded var parentAddress = utils.path.parentNodeModuleAddress(fileUrl); if(!parentAddress) { throw new Error('Did not find ' + pkg.origFileUrl); } var nodeModuleAddress = parentAddress + "/" + pkg.name + "/package.json"; pkg.nextFileUrl = nodeModuleAddress; } return pkg; }
javascript
function(){ var pkg = utils.extend({}, this.orig); var isFlat = this.context.isFlatFileStructure; var fileUrl = this.pkg.fileUrl; var context = this.context; if(isFlat && !pkg.__crawledNestedPosition) { pkg.__crawledNestedPosition = true; pkg.nextFileUrl = pkg.nestedFileUrl; } else { // make sure we aren't loading something we've already loaded var parentAddress = utils.path.parentNodeModuleAddress(fileUrl); if(!parentAddress) { throw new Error('Did not find ' + pkg.origFileUrl); } var nodeModuleAddress = parentAddress + "/" + pkg.name + "/package.json"; pkg.nextFileUrl = nodeModuleAddress; } return pkg; }
[ "function", "(", ")", "{", "var", "pkg", "=", "utils", ".", "extend", "(", "{", "}", ",", "this", ".", "orig", ")", ";", "var", "isFlat", "=", "this", ".", "context", ".", "isFlatFileStructure", ";", "var", "fileUrl", "=", "this", ".", "pkg", ".", "fileUrl", ";", "var", "context", "=", "this", ".", "context", ";", "if", "(", "isFlat", "&&", "!", "pkg", ".", "__crawledNestedPosition", ")", "{", "pkg", ".", "__crawledNestedPosition", "=", "true", ";", "pkg", ".", "nextFileUrl", "=", "pkg", ".", "nestedFileUrl", ";", "}", "else", "{", "var", "parentAddress", "=", "utils", ".", "path", ".", "parentNodeModuleAddress", "(", "fileUrl", ")", ";", "if", "(", "!", "parentAddress", ")", "{", "throw", "new", "Error", "(", "'Did not find '", "+", "pkg", ".", "origFileUrl", ")", ";", "}", "var", "nodeModuleAddress", "=", "parentAddress", "+", "\"/\"", "+", "pkg", ".", "name", "+", "\"/package.json\"", ";", "pkg", ".", "nextFileUrl", "=", "nodeModuleAddress", ";", "}", "return", "pkg", ";", "}" ]
Get the next package to look up by traversing up the node_modules. Create a new pkg by extending the existing one
[ "Get", "the", "next", "package", "to", "look", "up", "by", "traversing", "up", "the", "node_modules", ".", "Create", "a", "new", "pkg", "by", "extending", "the", "existing", "one" ]
216463c552cabe7d9dad86d754da784b5dea3d78
https://github.com/stealjs/steal-npm/blob/216463c552cabe7d9dad86d754da784b5dea3d78/npm-crawl.js#L612-L636
train
stealjs/steal-npm
npm-crawl.js
npmLoad
function npmLoad(context, pkg){ var task = new FetchTask(context, pkg); return task.load().then(function(){ if(task.failed) { // Recurse. Calling task.next gives us a new pkg object // with the fileUrl being the parent node_modules folder. return npmLoad(context, task.next()); } return task.getPackage(); }); }
javascript
function npmLoad(context, pkg){ var task = new FetchTask(context, pkg); return task.load().then(function(){ if(task.failed) { // Recurse. Calling task.next gives us a new pkg object // with the fileUrl being the parent node_modules folder. return npmLoad(context, task.next()); } return task.getPackage(); }); }
[ "function", "npmLoad", "(", "context", ",", "pkg", ")", "{", "var", "task", "=", "new", "FetchTask", "(", "context", ",", "pkg", ")", ";", "return", "task", ".", "load", "(", ")", ".", "then", "(", "function", "(", ")", "{", "if", "(", "task", ".", "failed", ")", "{", "return", "npmLoad", "(", "context", ",", "task", ".", "next", "(", ")", ")", ";", "}", "return", "task", ".", "getPackage", "(", ")", ";", "}", ")", ";", "}" ]
Loads package.json if it finds one, it sets that package in paths so it won't be loaded twice.
[ "Loads", "package", ".", "json", "if", "it", "finds", "one", "it", "sets", "that", "package", "in", "paths", "so", "it", "won", "t", "be", "loaded", "twice", "." ]
216463c552cabe7d9dad86d754da784b5dea3d78
https://github.com/stealjs/steal-npm/blob/216463c552cabe7d9dad86d754da784b5dea3d78/npm-crawl.js#L644-L655
train
grasshopper-cms/grasshopper-core-nodejs
dev/server/public/admin/vendor/svg-edit-2.7/svgtransformlist.js
transformToString
function transformToString(xform) { var m = xform.matrix, text = ''; switch(xform.type) { case 1: // MATRIX text = 'matrix(' + [m.a, m.b, m.c, m.d, m.e, m.f].join(',') + ')'; break; case 2: // TRANSLATE text = 'translate(' + m.e + ',' + m.f + ')'; break; case 3: // SCALE if (m.a == m.d) {text = 'scale(' + m.a + ')';} else {text = 'scale(' + m.a + ',' + m.d + ')';} break; case 4: // ROTATE var cx = 0, cy = 0; // this prevents divide by zero if (xform.angle != 0) { var K = 1 - m.a; cy = ( K * m.f + m.b*m.e ) / ( K*K + m.b*m.b ); cx = ( m.e - m.b * cy ) / K; } text = 'rotate(' + xform.angle + ' ' + cx + ',' + cy + ')'; break; } return text; }
javascript
function transformToString(xform) { var m = xform.matrix, text = ''; switch(xform.type) { case 1: // MATRIX text = 'matrix(' + [m.a, m.b, m.c, m.d, m.e, m.f].join(',') + ')'; break; case 2: // TRANSLATE text = 'translate(' + m.e + ',' + m.f + ')'; break; case 3: // SCALE if (m.a == m.d) {text = 'scale(' + m.a + ')';} else {text = 'scale(' + m.a + ',' + m.d + ')';} break; case 4: // ROTATE var cx = 0, cy = 0; // this prevents divide by zero if (xform.angle != 0) { var K = 1 - m.a; cy = ( K * m.f + m.b*m.e ) / ( K*K + m.b*m.b ); cx = ( m.e - m.b * cy ) / K; } text = 'rotate(' + xform.angle + ' ' + cx + ',' + cy + ')'; break; } return text; }
[ "function", "transformToString", "(", "xform", ")", "{", "var", "m", "=", "xform", ".", "matrix", ",", "text", "=", "''", ";", "switch", "(", "xform", ".", "type", ")", "{", "case", "1", ":", "text", "=", "'matrix('", "+", "[", "m", ".", "a", ",", "m", ".", "b", ",", "m", ".", "c", ",", "m", ".", "d", ",", "m", ".", "e", ",", "m", ".", "f", "]", ".", "join", "(", "','", ")", "+", "')'", ";", "break", ";", "case", "2", ":", "text", "=", "'translate('", "+", "m", ".", "e", "+", "','", "+", "m", ".", "f", "+", "')'", ";", "break", ";", "case", "3", ":", "if", "(", "m", ".", "a", "==", "m", ".", "d", ")", "{", "text", "=", "'scale('", "+", "m", ".", "a", "+", "')'", ";", "}", "else", "{", "text", "=", "'scale('", "+", "m", ".", "a", "+", "','", "+", "m", ".", "d", "+", "')'", ";", "}", "break", ";", "case", "4", ":", "var", "cx", "=", "0", ",", "cy", "=", "0", ";", "if", "(", "xform", ".", "angle", "!=", "0", ")", "{", "var", "K", "=", "1", "-", "m", ".", "a", ";", "cy", "=", "(", "K", "*", "m", ".", "f", "+", "m", ".", "b", "*", "m", ".", "e", ")", "/", "(", "K", "*", "K", "+", "m", ".", "b", "*", "m", ".", "b", ")", ";", "cx", "=", "(", "m", ".", "e", "-", "m", ".", "b", "*", "cy", ")", "/", "K", ";", "}", "text", "=", "'rotate('", "+", "xform", ".", "angle", "+", "' '", "+", "cx", "+", "','", "+", "cy", "+", "')'", ";", "break", ";", "}", "return", "text", ";", "}" ]
Helper function.
[ "Helper", "function", "." ]
8fabc3bfc5b18855ead443db0644608a277d0ea0
https://github.com/grasshopper-cms/grasshopper-core-nodejs/blob/8fabc3bfc5b18855ead443db0644608a277d0ea0/dev/server/public/admin/vendor/svg-edit-2.7/svgtransformlist.js#L24-L50
train
grasshopper-cms/grasshopper-core-nodejs
lib/middleware/users/validate.js
basicIdentityIsSet
function basicIdentityIsSet(){ return _.has(user, 'identities') && _.has(user.identities, 'basic') && !_.isEmpty(user.identities.basic); }
javascript
function basicIdentityIsSet(){ return _.has(user, 'identities') && _.has(user.identities, 'basic') && !_.isEmpty(user.identities.basic); }
[ "function", "basicIdentityIsSet", "(", ")", "{", "return", "_", ".", "has", "(", "user", ",", "'identities'", ")", "&&", "_", ".", "has", "(", "user", ".", "identities", ",", "'basic'", ")", "&&", "!", "_", ".", "isEmpty", "(", "user", ".", "identities", ".", "basic", ")", ";", "}" ]
Function that returns is the user.identities.basic property has been set to a value.
[ "Function", "that", "returns", "is", "the", "user", ".", "identities", ".", "basic", "property", "has", "been", "set", "to", "a", "value", "." ]
8fabc3bfc5b18855ead443db0644608a277d0ea0
https://github.com/grasshopper-cms/grasshopper-core-nodejs/blob/8fabc3bfc5b18855ead443db0644608a277d0ea0/lib/middleware/users/validate.js#L80-L82
train
prscX/pod-installer
index.js
exists
function exists(cmd) { return run(`which ${cmd}`).then(stdout => { if (stdout.trim().length === 0) { // maybe an empty command was supplied? // are we running on Windows?? return Promise.reject(new Error("No output")); } const rNotFound = /^[\w\-]+ not found/g; if (rNotFound.test(cmd)) { return Promise.resolve(false); } return Promise.resolve(true); }); }
javascript
function exists(cmd) { return run(`which ${cmd}`).then(stdout => { if (stdout.trim().length === 0) { // maybe an empty command was supplied? // are we running on Windows?? return Promise.reject(new Error("No output")); } const rNotFound = /^[\w\-]+ not found/g; if (rNotFound.test(cmd)) { return Promise.resolve(false); } return Promise.resolve(true); }); }
[ "function", "exists", "(", "cmd", ")", "{", "return", "run", "(", "`", "${", "cmd", "}", "`", ")", ".", "then", "(", "stdout", "=>", "{", "if", "(", "stdout", ".", "trim", "(", ")", ".", "length", "===", "0", ")", "{", "return", "Promise", ".", "reject", "(", "new", "Error", "(", "\"No output\"", ")", ")", ";", "}", "const", "rNotFound", "=", "/", "^[\\w\\-]+ not found", "/", "g", ";", "if", "(", "rNotFound", ".", "test", "(", "cmd", ")", ")", "{", "return", "Promise", ".", "resolve", "(", "false", ")", ";", "}", "return", "Promise", ".", "resolve", "(", "true", ")", ";", "}", ")", ";", "}" ]
returns Promise which fulfills with true if command exists
[ "returns", "Promise", "which", "fulfills", "with", "true", "if", "command", "exists" ]
dc582b349d673be79a1114a22325ba3d36131a1e
https://github.com/prscX/pod-installer/blob/dc582b349d673be79a1114a22325ba3d36131a1e/index.js#L66-L82
train
casetext/fireproof
index.js
Fireproof
function Fireproof(firebaseRef, promise) { if (!Fireproof.Promise) { try { Fireproof.Promise = Promise; } catch(e) { throw new Error('You must supply a Promise library to Fireproof!'); } } else if (typeof Fireproof.Promise !== 'function') { throw new Error('The supplied value of Fireproof.Promise is not a constructor (got ' + Fireproof.Promise + ')'); } this._ref = firebaseRef; if (promise && promise.then) { this.then = promise.then.bind(promise); } else { this.then = function(ok, fail) { return this.once('value', function() {}) .then(ok || null, fail || null); }; } }
javascript
function Fireproof(firebaseRef, promise) { if (!Fireproof.Promise) { try { Fireproof.Promise = Promise; } catch(e) { throw new Error('You must supply a Promise library to Fireproof!'); } } else if (typeof Fireproof.Promise !== 'function') { throw new Error('The supplied value of Fireproof.Promise is not a constructor (got ' + Fireproof.Promise + ')'); } this._ref = firebaseRef; if (promise && promise.then) { this.then = promise.then.bind(promise); } else { this.then = function(ok, fail) { return this.once('value', function() {}) .then(ok || null, fail || null); }; } }
[ "function", "Fireproof", "(", "firebaseRef", ",", "promise", ")", "{", "if", "(", "!", "Fireproof", ".", "Promise", ")", "{", "try", "{", "Fireproof", ".", "Promise", "=", "Promise", ";", "}", "catch", "(", "e", ")", "{", "throw", "new", "Error", "(", "'You must supply a Promise library to Fireproof!'", ")", ";", "}", "}", "else", "if", "(", "typeof", "Fireproof", ".", "Promise", "!==", "'function'", ")", "{", "throw", "new", "Error", "(", "'The supplied value of Fireproof.Promise is not a constructor (got '", "+", "Fireproof", ".", "Promise", "+", "')'", ")", ";", "}", "this", ".", "_ref", "=", "firebaseRef", ";", "if", "(", "promise", "&&", "promise", ".", "then", ")", "{", "this", ".", "then", "=", "promise", ".", "then", ".", "bind", "(", "promise", ")", ";", "}", "else", "{", "this", ".", "then", "=", "function", "(", "ok", ",", "fail", ")", "{", "return", "this", ".", "once", "(", "'value'", ",", "function", "(", ")", "{", "}", ")", ".", "then", "(", "ok", "||", "null", ",", "fail", "||", "null", ")", ";", "}", ";", "}", "}" ]
Fireproofs an existing Firebase reference, giving it magic promise powers. @name Fireproof @constructor @global @param {Firebase} firebaseRef A Firebase reference object. @property then A promise shortcut for .once('value'), except for references created by .push(), where it resolves on success and rejects on failure of the property object. @example var fp = new Fireproof(new Firebase('https://test.firebaseio.com/something')); fp.then(function(snap) { console.log(snap.val()); });
[ "Fireproofs", "an", "existing", "Firebase", "reference", "giving", "it", "magic", "promise", "powers", "." ]
a568157310d965d2c115e5a3c9e8287fc8fe021b
https://github.com/casetext/fireproof/blob/a568157310d965d2c115e5a3c9e8287fc8fe021b/index.js#L17-L46
train
grasshopper-cms/grasshopper-core-nodejs
dev/server/public/admin/vendor/svg-edit-2.7/svg-editor - Copy.js
function(win, elems) { var mode = svgCanvas.getMode(); if (mode === 'select') { setSelectMode(); } var is_node = (mode == "pathedit"); // if elems[1] is present, then we have more than one element selectedElement = (elems.length === 1 || elems[1] == null ? elems[0] : null); multiselected = (elems.length >= 2 && elems[1] != null); if (selectedElement != null) { // unless we're already in always set the mode of the editor to select because // upon creation of a text element the editor is switched into // select mode and this event fires - we need our UI to be in sync if (!is_node) { updateToolbar(); } } // if (elem != null) // Deal with pathedit mode togglePathEditMode(is_node, elems); updateContextPanel(); svgCanvas.runExtensions('selectedChanged', { elems: elems, selectedElement: selectedElement, multiselected: multiselected }); }
javascript
function(win, elems) { var mode = svgCanvas.getMode(); if (mode === 'select') { setSelectMode(); } var is_node = (mode == "pathedit"); // if elems[1] is present, then we have more than one element selectedElement = (elems.length === 1 || elems[1] == null ? elems[0] : null); multiselected = (elems.length >= 2 && elems[1] != null); if (selectedElement != null) { // unless we're already in always set the mode of the editor to select because // upon creation of a text element the editor is switched into // select mode and this event fires - we need our UI to be in sync if (!is_node) { updateToolbar(); } } // if (elem != null) // Deal with pathedit mode togglePathEditMode(is_node, elems); updateContextPanel(); svgCanvas.runExtensions('selectedChanged', { elems: elems, selectedElement: selectedElement, multiselected: multiselected }); }
[ "function", "(", "win", ",", "elems", ")", "{", "var", "mode", "=", "svgCanvas", ".", "getMode", "(", ")", ";", "if", "(", "mode", "===", "'select'", ")", "{", "setSelectMode", "(", ")", ";", "}", "var", "is_node", "=", "(", "mode", "==", "\"pathedit\"", ")", ";", "selectedElement", "=", "(", "elems", ".", "length", "===", "1", "||", "elems", "[", "1", "]", "==", "null", "?", "elems", "[", "0", "]", ":", "null", ")", ";", "multiselected", "=", "(", "elems", ".", "length", ">=", "2", "&&", "elems", "[", "1", "]", "!=", "null", ")", ";", "if", "(", "selectedElement", "!=", "null", ")", "{", "if", "(", "!", "is_node", ")", "{", "updateToolbar", "(", ")", ";", "}", "}", "togglePathEditMode", "(", "is_node", ",", "elems", ")", ";", "updateContextPanel", "(", ")", ";", "svgCanvas", ".", "runExtensions", "(", "'selectedChanged'", ",", "{", "elems", ":", "elems", ",", "selectedElement", ":", "selectedElement", ",", "multiselected", ":", "multiselected", "}", ")", ";", "}" ]
called when we've selected a different element
[ "called", "when", "we", "ve", "selected", "a", "different", "element" ]
8fabc3bfc5b18855ead443db0644608a277d0ea0
https://github.com/grasshopper-cms/grasshopper-core-nodejs/blob/8fabc3bfc5b18855ead443db0644608a277d0ea0/dev/server/public/admin/vendor/svg-edit-2.7/svg-editor - Copy.js#L1601-L1628
train
grasshopper-cms/grasshopper-core-nodejs
dev/server/public/admin/vendor/svg-edit-2.7/svg-editor - Copy.js
function(win, elems) { var mode = svgCanvas.getMode(); var elem = elems[0]; if (!elem) { return; } multiselected = (elems.length >= 2 && elems[1] != null); // Only updating fields for single elements for now if (!multiselected) { switch (mode) { case 'rotate': var ang = svgCanvas.getRotationAngle(elem); $('#angle').val(ang); $('#tool_reorient').toggleClass('disabled', ang === 0); break; // TODO: Update values that change on move/resize, etc // case "select": // case "resize": // break; } } svgCanvas.runExtensions('elementTransition', { elems: elems }); }
javascript
function(win, elems) { var mode = svgCanvas.getMode(); var elem = elems[0]; if (!elem) { return; } multiselected = (elems.length >= 2 && elems[1] != null); // Only updating fields for single elements for now if (!multiselected) { switch (mode) { case 'rotate': var ang = svgCanvas.getRotationAngle(elem); $('#angle').val(ang); $('#tool_reorient').toggleClass('disabled', ang === 0); break; // TODO: Update values that change on move/resize, etc // case "select": // case "resize": // break; } } svgCanvas.runExtensions('elementTransition', { elems: elems }); }
[ "function", "(", "win", ",", "elems", ")", "{", "var", "mode", "=", "svgCanvas", ".", "getMode", "(", ")", ";", "var", "elem", "=", "elems", "[", "0", "]", ";", "if", "(", "!", "elem", ")", "{", "return", ";", "}", "multiselected", "=", "(", "elems", ".", "length", ">=", "2", "&&", "elems", "[", "1", "]", "!=", "null", ")", ";", "if", "(", "!", "multiselected", ")", "{", "switch", "(", "mode", ")", "{", "case", "'rotate'", ":", "var", "ang", "=", "svgCanvas", ".", "getRotationAngle", "(", "elem", ")", ";", "$", "(", "'#angle'", ")", ".", "val", "(", "ang", ")", ";", "$", "(", "'#tool_reorient'", ")", ".", "toggleClass", "(", "'disabled'", ",", "ang", "===", "0", ")", ";", "break", ";", "}", "}", "svgCanvas", ".", "runExtensions", "(", "'elementTransition'", ",", "{", "elems", ":", "elems", "}", ")", ";", "}" ]
Call when part of element is in process of changing, generally on mousemove actions like rotate, move, etc.
[ "Call", "when", "part", "of", "element", "is", "in", "process", "of", "changing", "generally", "on", "mousemove", "actions", "like", "rotate", "move", "etc", "." ]
8fabc3bfc5b18855ead443db0644608a277d0ea0
https://github.com/grasshopper-cms/grasshopper-core-nodejs/blob/8fabc3bfc5b18855ead443db0644608a277d0ea0/dev/server/public/admin/vendor/svg-edit-2.7/svg-editor - Copy.js#L1632-L1659
train
grasshopper-cms/grasshopper-core-nodejs
dev/server/public/admin/vendor/svg-edit-2.7/svg-editor - Copy.js
function(win, elems) { var i, mode = svgCanvas.getMode(); if (mode === 'select') { setSelectMode(); } for (i = 0; i < elems.length; ++i) { var elem = elems[i]; // if the element changed was the svg, then it could be a resolution change if (elem && elem.tagName === 'svg') { populateLayers(); updateCanvas(); } // Update selectedElement if element is no longer part of the image. // This occurs for the text elements in Firefox else if (elem && selectedElement && selectedElement.parentNode == null) { // || elem && elem.tagName == "path" && !multiselected) { // This was added in r1430, but not sure why selectedElement = elem; } } Editor.showSaveWarning = true; // we update the contextual panel with potentially new // positional/sizing information (we DON'T want to update the // toolbar here as that creates an infinite loop) // also this updates the history buttons // we tell it to skip focusing the text control if the // text element was previously in focus updateContextPanel(); // In the event a gradient was flipped: if (selectedElement && mode === 'select') { paintBox.fill.update(); paintBox.stroke.update(); } svgCanvas.runExtensions('elementChanged', { elems: elems }); }
javascript
function(win, elems) { var i, mode = svgCanvas.getMode(); if (mode === 'select') { setSelectMode(); } for (i = 0; i < elems.length; ++i) { var elem = elems[i]; // if the element changed was the svg, then it could be a resolution change if (elem && elem.tagName === 'svg') { populateLayers(); updateCanvas(); } // Update selectedElement if element is no longer part of the image. // This occurs for the text elements in Firefox else if (elem && selectedElement && selectedElement.parentNode == null) { // || elem && elem.tagName == "path" && !multiselected) { // This was added in r1430, but not sure why selectedElement = elem; } } Editor.showSaveWarning = true; // we update the contextual panel with potentially new // positional/sizing information (we DON'T want to update the // toolbar here as that creates an infinite loop) // also this updates the history buttons // we tell it to skip focusing the text control if the // text element was previously in focus updateContextPanel(); // In the event a gradient was flipped: if (selectedElement && mode === 'select') { paintBox.fill.update(); paintBox.stroke.update(); } svgCanvas.runExtensions('elementChanged', { elems: elems }); }
[ "function", "(", "win", ",", "elems", ")", "{", "var", "i", ",", "mode", "=", "svgCanvas", ".", "getMode", "(", ")", ";", "if", "(", "mode", "===", "'select'", ")", "{", "setSelectMode", "(", ")", ";", "}", "for", "(", "i", "=", "0", ";", "i", "<", "elems", ".", "length", ";", "++", "i", ")", "{", "var", "elem", "=", "elems", "[", "i", "]", ";", "if", "(", "elem", "&&", "elem", ".", "tagName", "===", "'svg'", ")", "{", "populateLayers", "(", ")", ";", "updateCanvas", "(", ")", ";", "}", "else", "if", "(", "elem", "&&", "selectedElement", "&&", "selectedElement", ".", "parentNode", "==", "null", ")", "{", "selectedElement", "=", "elem", ";", "}", "}", "Editor", ".", "showSaveWarning", "=", "true", ";", "updateContextPanel", "(", ")", ";", "if", "(", "selectedElement", "&&", "mode", "===", "'select'", ")", "{", "paintBox", ".", "fill", ".", "update", "(", ")", ";", "paintBox", ".", "stroke", ".", "update", "(", ")", ";", "}", "svgCanvas", ".", "runExtensions", "(", "'elementChanged'", ",", "{", "elems", ":", "elems", "}", ")", ";", "}" ]
called when any element has changed
[ "called", "when", "any", "element", "has", "changed" ]
8fabc3bfc5b18855ead443db0644608a277d0ea0
https://github.com/grasshopper-cms/grasshopper-core-nodejs/blob/8fabc3bfc5b18855ead443db0644608a277d0ea0/dev/server/public/admin/vendor/svg-edit-2.7/svg-editor - Copy.js#L1662-L1705
train
grasshopper-cms/grasshopper-core-nodejs
dev/server/public/admin/vendor/svg-edit-2.7/svg-editor - Copy.js
function(event) { var options = opts; //find the currently selected tool if comes from keystroke if (event.type === 'keydown') { var flyoutIsSelected = $(options.parent + '_show').hasClass('tool_button_current'); var currentOperation = $(options.parent + '_show').attr('data-curopt'); $.each(holders[opts.parent], function(i, tool) { if (tool.sel == currentOperation) { if (!event.shiftKey || !flyoutIsSelected) { options = tool; } else { options = holders[opts.parent][i+1] || holders[opts.parent][0]; } } }); } if ($(this).hasClass('disabled')) {return false;} if (toolButtonClick(show_sel)) { options.fn(); } var icon; if (options.icon) { icon = $.getSvgIcon(options.icon, true); } else { icon = $(options.sel).children().eq(0).clone(); } icon[0].setAttribute('width', shower.width()); icon[0].setAttribute('height', shower.height()); shower.children(':not(.flyout_arrow_horiz)').remove(); shower.append(icon).attr('data-curopt', options.sel); // This sets the current mode }
javascript
function(event) { var options = opts; //find the currently selected tool if comes from keystroke if (event.type === 'keydown') { var flyoutIsSelected = $(options.parent + '_show').hasClass('tool_button_current'); var currentOperation = $(options.parent + '_show').attr('data-curopt'); $.each(holders[opts.parent], function(i, tool) { if (tool.sel == currentOperation) { if (!event.shiftKey || !flyoutIsSelected) { options = tool; } else { options = holders[opts.parent][i+1] || holders[opts.parent][0]; } } }); } if ($(this).hasClass('disabled')) {return false;} if (toolButtonClick(show_sel)) { options.fn(); } var icon; if (options.icon) { icon = $.getSvgIcon(options.icon, true); } else { icon = $(options.sel).children().eq(0).clone(); } icon[0].setAttribute('width', shower.width()); icon[0].setAttribute('height', shower.height()); shower.children(':not(.flyout_arrow_horiz)').remove(); shower.append(icon).attr('data-curopt', options.sel); // This sets the current mode }
[ "function", "(", "event", ")", "{", "var", "options", "=", "opts", ";", "if", "(", "event", ".", "type", "===", "'keydown'", ")", "{", "var", "flyoutIsSelected", "=", "$", "(", "options", ".", "parent", "+", "'_show'", ")", ".", "hasClass", "(", "'tool_button_current'", ")", ";", "var", "currentOperation", "=", "$", "(", "options", ".", "parent", "+", "'_show'", ")", ".", "attr", "(", "'data-curopt'", ")", ";", "$", ".", "each", "(", "holders", "[", "opts", ".", "parent", "]", ",", "function", "(", "i", ",", "tool", ")", "{", "if", "(", "tool", ".", "sel", "==", "currentOperation", ")", "{", "if", "(", "!", "event", ".", "shiftKey", "||", "!", "flyoutIsSelected", ")", "{", "options", "=", "tool", ";", "}", "else", "{", "options", "=", "holders", "[", "opts", ".", "parent", "]", "[", "i", "+", "1", "]", "||", "holders", "[", "opts", ".", "parent", "]", "[", "0", "]", ";", "}", "}", "}", ")", ";", "}", "if", "(", "$", "(", "this", ")", ".", "hasClass", "(", "'disabled'", ")", ")", "{", "return", "false", ";", "}", "if", "(", "toolButtonClick", "(", "show_sel", ")", ")", "{", "options", ".", "fn", "(", ")", ";", "}", "var", "icon", ";", "if", "(", "options", ".", "icon", ")", "{", "icon", "=", "$", ".", "getSvgIcon", "(", "options", ".", "icon", ",", "true", ")", ";", "}", "else", "{", "icon", "=", "$", "(", "options", ".", "sel", ")", ".", "children", "(", ")", ".", "eq", "(", "0", ")", ".", "clone", "(", ")", ";", "}", "icon", "[", "0", "]", ".", "setAttribute", "(", "'width'", ",", "shower", ".", "width", "(", ")", ")", ";", "icon", "[", "0", "]", ".", "setAttribute", "(", "'height'", ",", "shower", ".", "height", "(", ")", ")", ";", "shower", ".", "children", "(", "':not(.flyout_arrow_horiz)'", ")", ".", "remove", "(", ")", ";", "shower", ".", "append", "(", "icon", ")", ".", "attr", "(", "'data-curopt'", ",", "options", ".", "sel", ")", ";", "}" ]
Clicking the icon in flyout should set this set's icon
[ "Clicking", "the", "icon", "in", "flyout", "should", "set", "this", "set", "s", "icon" ]
8fabc3bfc5b18855ead443db0644608a277d0ea0
https://github.com/grasshopper-cms/grasshopper-core-nodejs/blob/8fabc3bfc5b18855ead443db0644608a277d0ea0/dev/server/public/admin/vendor/svg-edit-2.7/svg-editor - Copy.js#L1850-L1881
train
grasshopper-cms/grasshopper-core-nodejs
dev/server/public/admin/vendor/svg-edit-2.7/svg-editor - Copy.js
function(close) { var w = $('#sidepanels').width(); var deltaX = (w > 2 || close ? 2 : SIDEPANEL_OPENWIDTH) - w; changeSidePanelWidth(deltaX); }
javascript
function(close) { var w = $('#sidepanels').width(); var deltaX = (w > 2 || close ? 2 : SIDEPANEL_OPENWIDTH) - w; changeSidePanelWidth(deltaX); }
[ "function", "(", "close", ")", "{", "var", "w", "=", "$", "(", "'#sidepanels'", ")", ".", "width", "(", ")", ";", "var", "deltaX", "=", "(", "w", ">", "2", "||", "close", "?", "2", ":", "SIDEPANEL_OPENWIDTH", ")", "-", "w", ";", "changeSidePanelWidth", "(", "deltaX", ")", ";", "}" ]
if width is non-zero, then fully close it, otherwise fully open it the optional close argument forces the side panel closed
[ "if", "width", "is", "non", "-", "zero", "then", "fully", "close", "it", "otherwise", "fully", "open", "it", "the", "optional", "close", "argument", "forces", "the", "side", "panel", "closed" ]
8fabc3bfc5b18855ead443db0644608a277d0ea0
https://github.com/grasshopper-cms/grasshopper-core-nodejs/blob/8fabc3bfc5b18855ead443db0644608a277d0ea0/dev/server/public/admin/vendor/svg-edit-2.7/svg-editor - Copy.js#L4161-L4165
train
grasshopper-cms/grasshopper-core-nodejs
dev/server/public/admin/vendor/svg-edit-2.7/svg-editor - Copy.js
function(width, height) { var newImage = svgCanvas.addSvgElementFromJson({ element: 'image', attr: { x: 0, y: 0, width: width, height: height, id: svgCanvas.getNextId(), style: 'pointer-events:inherit' } }); svgCanvas.setHref(newImage, e.target.result); svgCanvas.selectOnly([newImage]); svgCanvas.alignSelectedElements('m', 'page'); svgCanvas.alignSelectedElements('c', 'page'); updateContextPanel(); }
javascript
function(width, height) { var newImage = svgCanvas.addSvgElementFromJson({ element: 'image', attr: { x: 0, y: 0, width: width, height: height, id: svgCanvas.getNextId(), style: 'pointer-events:inherit' } }); svgCanvas.setHref(newImage, e.target.result); svgCanvas.selectOnly([newImage]); svgCanvas.alignSelectedElements('m', 'page'); svgCanvas.alignSelectedElements('c', 'page'); updateContextPanel(); }
[ "function", "(", "width", ",", "height", ")", "{", "var", "newImage", "=", "svgCanvas", ".", "addSvgElementFromJson", "(", "{", "element", ":", "'image'", ",", "attr", ":", "{", "x", ":", "0", ",", "y", ":", "0", ",", "width", ":", "width", ",", "height", ":", "height", ",", "id", ":", "svgCanvas", ".", "getNextId", "(", ")", ",", "style", ":", "'pointer-events:inherit'", "}", "}", ")", ";", "svgCanvas", ".", "setHref", "(", "newImage", ",", "e", ".", "target", ".", "result", ")", ";", "svgCanvas", ".", "selectOnly", "(", "[", "newImage", "]", ")", ";", "svgCanvas", ".", "alignSelectedElements", "(", "'m'", ",", "'page'", ")", ";", "svgCanvas", ".", "alignSelectedElements", "(", "'c'", ",", "'page'", ")", ";", "updateContextPanel", "(", ")", ";", "}" ]
let's insert the new image until we know its dimensions
[ "let", "s", "insert", "the", "new", "image", "until", "we", "know", "its", "dimensions" ]
8fabc3bfc5b18855ead443db0644608a277d0ea0
https://github.com/grasshopper-cms/grasshopper-core-nodejs/blob/8fabc3bfc5b18855ead443db0644608a277d0ea0/dev/server/public/admin/vendor/svg-edit-2.7/svg-editor - Copy.js#L4741-L4758
train
grasshopper-cms/grasshopper-core-nodejs
dev/server/public/admin/vendor/ace/lib/ace/keyboard/vim.js
function(data, hashId, key) { if (hashId == -1) { // record key data.inputChar = key; data.lastEvent = "input"; } else if (data.inputChar && data.$lastHash == hashId && data.$lastKey == key) { // check for repeated keypress if (data.lastEvent == "input") { data.lastEvent = "input1"; } else if (data.lastEvent == "input1") { // simulate textinput return true; } } else { // reset data.$lastHash = hashId; data.$lastKey = key; data.lastEvent = "keypress"; } }
javascript
function(data, hashId, key) { if (hashId == -1) { // record key data.inputChar = key; data.lastEvent = "input"; } else if (data.inputChar && data.$lastHash == hashId && data.$lastKey == key) { // check for repeated keypress if (data.lastEvent == "input") { data.lastEvent = "input1"; } else if (data.lastEvent == "input1") { // simulate textinput return true; } } else { // reset data.$lastHash = hashId; data.$lastKey = key; data.lastEvent = "keypress"; } }
[ "function", "(", "data", ",", "hashId", ",", "key", ")", "{", "if", "(", "hashId", "==", "-", "1", ")", "{", "data", ".", "inputChar", "=", "key", ";", "data", ".", "lastEvent", "=", "\"input\"", ";", "}", "else", "if", "(", "data", ".", "inputChar", "&&", "data", ".", "$lastHash", "==", "hashId", "&&", "data", ".", "$lastKey", "==", "key", ")", "{", "if", "(", "data", ".", "lastEvent", "==", "\"input\"", ")", "{", "data", ".", "lastEvent", "=", "\"input1\"", ";", "}", "else", "if", "(", "data", ".", "lastEvent", "==", "\"input1\"", ")", "{", "return", "true", ";", "}", "}", "else", "{", "data", ".", "$lastHash", "=", "hashId", ";", "data", ".", "$lastKey", "=", "key", ";", "data", ".", "lastEvent", "=", "\"keypress\"", ";", "}", "}" ]
workaround for j not repeating with `defaults write -g ApplePressAndHoldEnabled -bool true`
[ "workaround", "for", "j", "not", "repeating", "with", "defaults", "write", "-", "g", "ApplePressAndHoldEnabled", "-", "bool", "true" ]
8fabc3bfc5b18855ead443db0644608a277d0ea0
https://github.com/grasshopper-cms/grasshopper-core-nodejs/blob/8fabc3bfc5b18855ead443db0644608a277d0ea0/dev/server/public/admin/vendor/ace/lib/ace/keyboard/vim.js#L63-L82
train
stealjs/steal-npm
npm-convert.js
convertPropertyNames
function convertPropertyNames (context, pkg, map , root, waiting) { if(!map) { return map; } var clone = {}, value; for(var property in map ) { value = convertName(context, pkg, map, root, property, waiting); if(typeof value === 'string') { clone[value] = map[property]; } // do root paths b/c we don't know if they are going to be included with the package name or not. if(root) { value = convertName(context, pkg, map, false, property, waiting); if(typeof value === 'string') { clone[value] = map[property]; } } } return clone; }
javascript
function convertPropertyNames (context, pkg, map , root, waiting) { if(!map) { return map; } var clone = {}, value; for(var property in map ) { value = convertName(context, pkg, map, root, property, waiting); if(typeof value === 'string') { clone[value] = map[property]; } // do root paths b/c we don't know if they are going to be included with the package name or not. if(root) { value = convertName(context, pkg, map, false, property, waiting); if(typeof value === 'string') { clone[value] = map[property]; } } } return clone; }
[ "function", "convertPropertyNames", "(", "context", ",", "pkg", ",", "map", ",", "root", ",", "waiting", ")", "{", "if", "(", "!", "map", ")", "{", "return", "map", ";", "}", "var", "clone", "=", "{", "}", ",", "value", ";", "for", "(", "var", "property", "in", "map", ")", "{", "value", "=", "convertName", "(", "context", ",", "pkg", ",", "map", ",", "root", ",", "property", ",", "waiting", ")", ";", "if", "(", "typeof", "value", "===", "'string'", ")", "{", "clone", "[", "value", "]", "=", "map", "[", "property", "]", ";", "}", "if", "(", "root", ")", "{", "value", "=", "convertName", "(", "context", ",", "pkg", ",", "map", ",", "false", ",", "property", ",", "waiting", ")", ";", "if", "(", "typeof", "value", "===", "'string'", ")", "{", "clone", "[", "value", "]", "=", "map", "[", "property", "]", ";", "}", "}", "}", "return", "clone", ";", "}" ]
converts only the property name
[ "converts", "only", "the", "property", "name" ]
216463c552cabe7d9dad86d754da784b5dea3d78
https://github.com/stealjs/steal-npm/blob/216463c552cabe7d9dad86d754da784b5dea3d78/npm-convert.js#L88-L108
train
stealjs/steal-npm
npm-convert.js
convertPropertyNamesAndValues
function convertPropertyNamesAndValues (context, pkg, map, root, waiting) { if(!map) { return map; } var clone = {}, val, name; for(var property in map ) { val = map[property]; name = convertName(context, pkg, map, root, property, waiting); val = typeof val === "object" ? convertPropertyNamesAndValues(context, pkg, val, root, waiting) : convertName(context, pkg, map, root, val, waiting); if(typeof name !== 'undefined' && typeof val !== 'undefined') { clone[name] = val; } } return clone; }
javascript
function convertPropertyNamesAndValues (context, pkg, map, root, waiting) { if(!map) { return map; } var clone = {}, val, name; for(var property in map ) { val = map[property]; name = convertName(context, pkg, map, root, property, waiting); val = typeof val === "object" ? convertPropertyNamesAndValues(context, pkg, val, root, waiting) : convertName(context, pkg, map, root, val, waiting); if(typeof name !== 'undefined' && typeof val !== 'undefined') { clone[name] = val; } } return clone; }
[ "function", "convertPropertyNamesAndValues", "(", "context", ",", "pkg", ",", "map", ",", "root", ",", "waiting", ")", "{", "if", "(", "!", "map", ")", "{", "return", "map", ";", "}", "var", "clone", "=", "{", "}", ",", "val", ",", "name", ";", "for", "(", "var", "property", "in", "map", ")", "{", "val", "=", "map", "[", "property", "]", ";", "name", "=", "convertName", "(", "context", ",", "pkg", ",", "map", ",", "root", ",", "property", ",", "waiting", ")", ";", "val", "=", "typeof", "val", "===", "\"object\"", "?", "convertPropertyNamesAndValues", "(", "context", ",", "pkg", ",", "val", ",", "root", ",", "waiting", ")", ":", "convertName", "(", "context", ",", "pkg", ",", "map", ",", "root", ",", "val", ",", "waiting", ")", ";", "if", "(", "typeof", "name", "!==", "'undefined'", "&&", "typeof", "val", "!==", "'undefined'", ")", "{", "clone", "[", "name", "]", "=", "val", ";", "}", "}", "return", "clone", ";", "}" ]
converts both property name and value
[ "converts", "both", "property", "name", "and", "value" ]
216463c552cabe7d9dad86d754da784b5dea3d78
https://github.com/stealjs/steal-npm/blob/216463c552cabe7d9dad86d754da784b5dea3d78/npm-convert.js#L111-L127
train
stealjs/steal-npm
npm-convert.js
convertBrowser
function convertBrowser(pkg, browser) { var type = typeof browser; if(type === "string" || type === "undefined") { return browser; } var map = {}; for(var fromName in browser) { convertBrowserProperty(map, pkg, fromName, browser[fromName]); } return map; }
javascript
function convertBrowser(pkg, browser) { var type = typeof browser; if(type === "string" || type === "undefined") { return browser; } var map = {}; for(var fromName in browser) { convertBrowserProperty(map, pkg, fromName, browser[fromName]); } return map; }
[ "function", "convertBrowser", "(", "pkg", ",", "browser", ")", "{", "var", "type", "=", "typeof", "browser", ";", "if", "(", "type", "===", "\"string\"", "||", "type", "===", "\"undefined\"", ")", "{", "return", "browser", ";", "}", "var", "map", "=", "{", "}", ";", "for", "(", "var", "fromName", "in", "browser", ")", "{", "convertBrowserProperty", "(", "map", ",", "pkg", ",", "fromName", ",", "browser", "[", "fromName", "]", ")", ";", "}", "return", "map", ";", "}" ]
Converts browser names into actual module names. Example: ``` { "foo": "browser-foo" "traceur#src/node/traceur": "./browser/traceur" "./foo" : "./foo-browser" } ``` converted to: ``` { // any foo ... regardless of where "foo": "browser-foo" // this module ... ideally minus version "traceur#src/node/traceur": "transpile#./browser/traceur" "transpile#./foo" : "transpile#./foo-browser" } ```
[ "Converts", "browser", "names", "into", "actual", "module", "names", "." ]
216463c552cabe7d9dad86d754da784b5dea3d78
https://github.com/stealjs/steal-npm/blob/216463c552cabe7d9dad86d754da784b5dea3d78/npm-convert.js#L236-L246
train
stealjs/steal-npm
npm-convert.js
convertForPackage
function convertForPackage(context, pkg) { var name = pkg.name; var version = pkg.version; var conv = context.deferredConversions; var pkgConv = conv[name]; var depPkg, fns, keys = 0; if(pkgConv) { for(var range in pkgConv) { depPkg = crawl.matchedVersion(context, name, range); if(depPkg) { fns = pkgConv[range]; for(var i = 0, len = fns.length; i < len; i++) { fns[i].call(context); } delete pkgConv[range]; } else { keys++; } } if(keys === 0) { delete conv[name]; } } }
javascript
function convertForPackage(context, pkg) { var name = pkg.name; var version = pkg.version; var conv = context.deferredConversions; var pkgConv = conv[name]; var depPkg, fns, keys = 0; if(pkgConv) { for(var range in pkgConv) { depPkg = crawl.matchedVersion(context, name, range); if(depPkg) { fns = pkgConv[range]; for(var i = 0, len = fns.length; i < len; i++) { fns[i].call(context); } delete pkgConv[range]; } else { keys++; } } if(keys === 0) { delete conv[name]; } } }
[ "function", "convertForPackage", "(", "context", ",", "pkg", ")", "{", "var", "name", "=", "pkg", ".", "name", ";", "var", "version", "=", "pkg", ".", "version", ";", "var", "conv", "=", "context", ".", "deferredConversions", ";", "var", "pkgConv", "=", "conv", "[", "name", "]", ";", "var", "depPkg", ",", "fns", ",", "keys", "=", "0", ";", "if", "(", "pkgConv", ")", "{", "for", "(", "var", "range", "in", "pkgConv", ")", "{", "depPkg", "=", "crawl", ".", "matchedVersion", "(", "context", ",", "name", ",", "range", ")", ";", "if", "(", "depPkg", ")", "{", "fns", "=", "pkgConv", "[", "range", "]", ";", "for", "(", "var", "i", "=", "0", ",", "len", "=", "fns", ".", "length", ";", "i", "<", "len", ";", "i", "++", ")", "{", "fns", "[", "i", "]", ".", "call", "(", "context", ")", ";", "}", "delete", "pkgConv", "[", "range", "]", ";", "}", "else", "{", "keys", "++", ";", "}", "}", "if", "(", "keys", "===", "0", ")", "{", "delete", "conv", "[", "name", "]", ";", "}", "}", "}" ]
When progressively loading package.jsons we need to convert any config that is waiting on a package.json to load. This function is called after a package is loaded and will call all of the callbacks that cause the config to be applied.
[ "When", "progressively", "loading", "package", ".", "jsons", "we", "need", "to", "convert", "any", "config", "that", "is", "waiting", "on", "a", "package", ".", "json", "to", "load", ".", "This", "function", "is", "called", "after", "a", "package", "is", "loaded", "and", "will", "call", "all", "of", "the", "callbacks", "that", "cause", "the", "config", "to", "be", "applied", "." ]
216463c552cabe7d9dad86d754da784b5dea3d78
https://github.com/stealjs/steal-npm/blob/216463c552cabe7d9dad86d754da784b5dea3d78/npm-convert.js#L350-L374
train
grasshopper-cms/grasshopper-core-nodejs
dev/server/public/admin/vendor/svg-edit-2.7/extensions/ext-server_opensave.js
rebuildInput
function rebuildInput(form) { form.empty(); var inp = $('<input type="file" name="svg_file">').appendTo(form); function submit() { // This submits the form, which returns the file data using svgEditor.processFile() form.submit(); rebuildInput(form); $.process_cancel("Uploading...", function() { cancelled = true; $('#dialog_box').hide(); }); } if(form[0] == open_svg_form[0]) { inp.change(function() { // This takes care of the "are you sure" dialog box svgEditor.openPrep(function(ok) { if(!ok) { rebuildInput(form); return; } submit(); }); }); } else { inp.change(function() { // This submits the form, which returns the file data using svgEditor.processFile() submit(); }); } }
javascript
function rebuildInput(form) { form.empty(); var inp = $('<input type="file" name="svg_file">').appendTo(form); function submit() { // This submits the form, which returns the file data using svgEditor.processFile() form.submit(); rebuildInput(form); $.process_cancel("Uploading...", function() { cancelled = true; $('#dialog_box').hide(); }); } if(form[0] == open_svg_form[0]) { inp.change(function() { // This takes care of the "are you sure" dialog box svgEditor.openPrep(function(ok) { if(!ok) { rebuildInput(form); return; } submit(); }); }); } else { inp.change(function() { // This submits the form, which returns the file data using svgEditor.processFile() submit(); }); } }
[ "function", "rebuildInput", "(", "form", ")", "{", "form", ".", "empty", "(", ")", ";", "var", "inp", "=", "$", "(", "'<input type=\"file\" name=\"svg_file\">'", ")", ".", "appendTo", "(", "form", ")", ";", "function", "submit", "(", ")", "{", "form", ".", "submit", "(", ")", ";", "rebuildInput", "(", "form", ")", ";", "$", ".", "process_cancel", "(", "\"Uploading...\"", ",", "function", "(", ")", "{", "cancelled", "=", "true", ";", "$", "(", "'#dialog_box'", ")", ".", "hide", "(", ")", ";", "}", ")", ";", "}", "if", "(", "form", "[", "0", "]", "==", "open_svg_form", "[", "0", "]", ")", "{", "inp", ".", "change", "(", "function", "(", ")", "{", "svgEditor", ".", "openPrep", "(", "function", "(", "ok", ")", "{", "if", "(", "!", "ok", ")", "{", "rebuildInput", "(", "form", ")", ";", "return", ";", "}", "submit", "(", ")", ";", "}", ")", ";", "}", ")", ";", "}", "else", "{", "inp", ".", "change", "(", "function", "(", ")", "{", "submit", "(", ")", ";", "}", ")", ";", "}", "}" ]
It appears necessary to rebuild this input every time a file is selected so the same file can be picked and the change event can fire.
[ "It", "appears", "necessary", "to", "rebuild", "this", "input", "every", "time", "a", "file", "is", "selected", "so", "the", "same", "file", "can", "be", "picked", "and", "the", "change", "event", "can", "fire", "." ]
8fabc3bfc5b18855ead443db0644608a277d0ea0
https://github.com/grasshopper-cms/grasshopper-core-nodejs/blob/8fabc3bfc5b18855ead443db0644608a277d0ea0/dev/server/public/admin/vendor/svg-edit-2.7/extensions/ext-server_opensave.js#L164-L197
train
aureooms/js-itertools
lib/reduce/max.js
max
function max(compare, iterable, dflt = undefined) { let iterator = (0, _iter.iter)(iterable); let first = iterator.next(); if (first.done) return dflt; let largest = first.value; for (let candidate of iterator) { if (compare(candidate, largest) > 0) { largest = candidate; } } return largest; }
javascript
function max(compare, iterable, dflt = undefined) { let iterator = (0, _iter.iter)(iterable); let first = iterator.next(); if (first.done) return dflt; let largest = first.value; for (let candidate of iterator) { if (compare(candidate, largest) > 0) { largest = candidate; } } return largest; }
[ "function", "max", "(", "compare", ",", "iterable", ",", "dflt", "=", "undefined", ")", "{", "let", "iterator", "=", "(", "0", ",", "_iter", ".", "iter", ")", "(", "iterable", ")", ";", "let", "first", "=", "iterator", ".", "next", "(", ")", ";", "if", "(", "first", ".", "done", ")", "return", "dflt", ";", "let", "largest", "=", "first", ".", "value", ";", "for", "(", "let", "candidate", "of", "iterator", ")", "{", "if", "(", "compare", "(", "candidate", ",", "largest", ")", ">", "0", ")", "{", "largest", "=", "candidate", ";", "}", "}", "return", "largest", ";", "}" ]
Returns the largest element of the input iterable according to some comparison function. @example max( ( a , b ) => a - b , range( 10 ) ) ; // returns 9 @example max( ( a , b ) => a - b , range( 0 ) ) ; // returns undefined @param {Function} compare - The comparison function to use. This function must be 2-ary. It must return -1, 0, or 1 depending whether the first parameter is, respectively, less than, equal to, or greater than the second parameter. @param {Iterable} iterable - The input iterable. @param {Object} [dflt=undefined] - The default value to return in the case that the input iterable is empty. @returns {Object} The largest element of <code>iterable</code> according to <code>compare</code>.
[ "Returns", "the", "largest", "element", "of", "the", "input", "iterable", "according", "to", "some", "comparison", "function", "." ]
72bafa5f3f957ceb37bdfa87a222364fe4974be3
https://github.com/aureooms/js-itertools/blob/72bafa5f3f957ceb37bdfa87a222364fe4974be3/lib/reduce/max.js#L30-L49
train
w3co/jcf
js/jcf.scrollable.js
function() { self.value += stepValue; self.setValue(self.value); self.triggerScrollEvent(self.value); if (isFinishedScrolling()) { clearInterval(self.pageScrollTimer); } }
javascript
function() { self.value += stepValue; self.setValue(self.value); self.triggerScrollEvent(self.value); if (isFinishedScrolling()) { clearInterval(self.pageScrollTimer); } }
[ "function", "(", ")", "{", "self", ".", "value", "+=", "stepValue", ";", "self", ".", "setValue", "(", "self", ".", "value", ")", ";", "self", ".", "triggerScrollEvent", "(", "self", ".", "value", ")", ";", "if", "(", "isFinishedScrolling", "(", ")", ")", "{", "clearInterval", "(", "self", ".", "pageScrollTimer", ")", ";", "}", "}" ]
scroll by page when track is pressed
[ "scroll", "by", "page", "when", "track", "is", "pressed" ]
d002e9f5a10cb386089f58592abca4a01edc9518
https://github.com/w3co/jcf/blob/d002e9f5a10cb386089f58592abca4a01edc9518/js/jcf.scrollable.js#L525-L533
train
w3co/jcf
js/jcf.select.js
SelectList
function SelectList(options) { this.options = $.extend({ holder: null, maxVisibleItems: 10, selectOnClick: true, useHoverClass: false, useCustomScroll: false, handleResize: true, multipleSelectWithoutKey: false, alwaysPreventMouseWheel: false, indexAttribute: 'data-index', cloneClassPrefix: 'jcf-option-', containerStructure: '<span class="jcf-list"><span class="jcf-list-content"></span></span>', containerSelector: '.jcf-list-content', captionClass: 'jcf-optgroup-caption', disabledClass: 'jcf-disabled', optionClass: 'jcf-option', groupClass: 'jcf-optgroup', hoverClass: 'jcf-hover', selectedClass: 'jcf-selected', scrollClass: 'jcf-scroll-active' }, options); this.init(); }
javascript
function SelectList(options) { this.options = $.extend({ holder: null, maxVisibleItems: 10, selectOnClick: true, useHoverClass: false, useCustomScroll: false, handleResize: true, multipleSelectWithoutKey: false, alwaysPreventMouseWheel: false, indexAttribute: 'data-index', cloneClassPrefix: 'jcf-option-', containerStructure: '<span class="jcf-list"><span class="jcf-list-content"></span></span>', containerSelector: '.jcf-list-content', captionClass: 'jcf-optgroup-caption', disabledClass: 'jcf-disabled', optionClass: 'jcf-option', groupClass: 'jcf-optgroup', hoverClass: 'jcf-hover', selectedClass: 'jcf-selected', scrollClass: 'jcf-scroll-active' }, options); this.init(); }
[ "function", "SelectList", "(", "options", ")", "{", "this", ".", "options", "=", "$", ".", "extend", "(", "{", "holder", ":", "null", ",", "maxVisibleItems", ":", "10", ",", "selectOnClick", ":", "true", ",", "useHoverClass", ":", "false", ",", "useCustomScroll", ":", "false", ",", "handleResize", ":", "true", ",", "multipleSelectWithoutKey", ":", "false", ",", "alwaysPreventMouseWheel", ":", "false", ",", "indexAttribute", ":", "'data-index'", ",", "cloneClassPrefix", ":", "'jcf-option-'", ",", "containerStructure", ":", "'<span class=\"jcf-list\"><span class=\"jcf-list-content\"></span></span>'", ",", "containerSelector", ":", "'.jcf-list-content'", ",", "captionClass", ":", "'jcf-optgroup-caption'", ",", "disabledClass", ":", "'jcf-disabled'", ",", "optionClass", ":", "'jcf-option'", ",", "groupClass", ":", "'jcf-optgroup'", ",", "hoverClass", ":", "'jcf-hover'", ",", "selectedClass", ":", "'jcf-selected'", ",", "scrollClass", ":", "'jcf-scroll-active'", "}", ",", "options", ")", ";", "this", ".", "init", "(", ")", ";", "}" ]
options list module
[ "options", "list", "module" ]
d002e9f5a10cb386089f58592abca4a01edc9518
https://github.com/w3co/jcf/blob/d002e9f5a10cb386089f58592abca4a01edc9518/js/jcf.select.js#L586-L609
train
canjs/can-reflect
reflections/shape/shape.js
isSerializedHelper
function isSerializedHelper(obj){ if (typeReflections.isPrimitive(obj)) { return true; } if(hasUpdateSymbol(obj)) { return false; } return typeReflections.isBuiltIn(obj) && !typeReflections.isPlainObject(obj) && !Array.isArray(obj); }
javascript
function isSerializedHelper(obj){ if (typeReflections.isPrimitive(obj)) { return true; } if(hasUpdateSymbol(obj)) { return false; } return typeReflections.isBuiltIn(obj) && !typeReflections.isPlainObject(obj) && !Array.isArray(obj); }
[ "function", "isSerializedHelper", "(", "obj", ")", "{", "if", "(", "typeReflections", ".", "isPrimitive", "(", "obj", ")", ")", "{", "return", "true", ";", "}", "if", "(", "hasUpdateSymbol", "(", "obj", ")", ")", "{", "return", "false", ";", "}", "return", "typeReflections", ".", "isBuiltIn", "(", "obj", ")", "&&", "!", "typeReflections", ".", "isPlainObject", "(", "obj", ")", "&&", "!", "Array", ".", "isArray", "(", "obj", ")", ";", "}" ]
is the value itself its serialized value
[ "is", "the", "value", "itself", "its", "serialized", "value" ]
6b8c65a6fc52ee26973adbf6fb8c21fb6725b365
https://github.com/canjs/can-reflect/blob/6b8c65a6fc52ee26973adbf6fb8c21fb6725b365/reflections/shape/shape.js#L101-L109
train
canjs/can-reflect
reflections/shape/shape.js
function(obj){ var hasOwnKey = obj[canSymbol.for("can.hasOwnKey")]; if(hasOwnKey) { return hasOwnKey.bind(obj); } else { var map = makeMap( shapeReflections.getOwnEnumerableKeys(obj) ); return function(key) { return map.get(key); }; } }
javascript
function(obj){ var hasOwnKey = obj[canSymbol.for("can.hasOwnKey")]; if(hasOwnKey) { return hasOwnKey.bind(obj); } else { var map = makeMap( shapeReflections.getOwnEnumerableKeys(obj) ); return function(key) { return map.get(key); }; } }
[ "function", "(", "obj", ")", "{", "var", "hasOwnKey", "=", "obj", "[", "canSymbol", ".", "for", "(", "\"can.hasOwnKey\"", ")", "]", ";", "if", "(", "hasOwnKey", ")", "{", "return", "hasOwnKey", ".", "bind", "(", "obj", ")", ";", "}", "else", "{", "var", "map", "=", "makeMap", "(", "shapeReflections", ".", "getOwnEnumerableKeys", "(", "obj", ")", ")", ";", "return", "function", "(", "key", ")", "{", "return", "map", ".", "get", "(", "key", ")", ";", "}", ";", "}", "}" ]
creates an optimized hasOwnKey lookup. If the object has hasOwnKey, then we just use that. Otherwise, try to put all keys in a map.
[ "creates", "an", "optimized", "hasOwnKey", "lookup", ".", "If", "the", "object", "has", "hasOwnKey", "then", "we", "just", "use", "that", ".", "Otherwise", "try", "to", "put", "all", "keys", "in", "a", "map", "." ]
6b8c65a6fc52ee26973adbf6fb8c21fb6725b365
https://github.com/canjs/can-reflect/blob/6b8c65a6fc52ee26973adbf6fb8c21fb6725b365/reflections/shape/shape.js#L278-L288
train
canjs/can-reflect
reflections/shape/shape.js
addPatch
function addPatch(patches, patch) { var lastPatch = patches[patches.length -1]; if(lastPatch) { // same number of deletes and counts as the index is back if(lastPatch.deleteCount === lastPatch.insert.length && (patch.index - lastPatch.index === lastPatch.deleteCount) ) { lastPatch.insert.push.apply(lastPatch.insert, patch.insert); lastPatch.deleteCount += patch.deleteCount; return; } } patches.push(patch); }
javascript
function addPatch(patches, patch) { var lastPatch = patches[patches.length -1]; if(lastPatch) { // same number of deletes and counts as the index is back if(lastPatch.deleteCount === lastPatch.insert.length && (patch.index - lastPatch.index === lastPatch.deleteCount) ) { lastPatch.insert.push.apply(lastPatch.insert, patch.insert); lastPatch.deleteCount += patch.deleteCount; return; } } patches.push(patch); }
[ "function", "addPatch", "(", "patches", ",", "patch", ")", "{", "var", "lastPatch", "=", "patches", "[", "patches", ".", "length", "-", "1", "]", ";", "if", "(", "lastPatch", ")", "{", "if", "(", "lastPatch", ".", "deleteCount", "===", "lastPatch", ".", "insert", ".", "length", "&&", "(", "patch", ".", "index", "-", "lastPatch", ".", "index", "===", "lastPatch", ".", "deleteCount", ")", ")", "{", "lastPatch", ".", "insert", ".", "push", ".", "apply", "(", "lastPatch", ".", "insert", ",", "patch", ".", "insert", ")", ";", "lastPatch", ".", "deleteCount", "+=", "patch", ".", "deleteCount", ";", "return", ";", "}", "}", "patches", ".", "push", "(", "patch", ")", ";", "}" ]
combines patches if it makes sense
[ "combines", "patches", "if", "it", "makes", "sense" ]
6b8c65a6fc52ee26973adbf6fb8c21fb6725b365
https://github.com/canjs/can-reflect/blob/6b8c65a6fc52ee26973adbf6fb8c21fb6725b365/reflections/shape/shape.js#L292-L303
train
shibukawa/i18n4v
docs/_static/websupport.js
setComparator
function setComparator() { // If the first three letters are "asc", sort in ascending order // and remove the prefix. if (by.substring(0,3) == 'asc') { var i = by.substring(3); comp = function(a, b) { return a[i] - b[i]; }; } else { // Otherwise sort in descending order. comp = function(a, b) { return b[by] - a[by]; }; } // Reset link styles and format the selected sort option. $('a.sel').attr('href', '#').removeClass('sel'); $('a.by' + by).removeAttr('href').addClass('sel'); }
javascript
function setComparator() { // If the first three letters are "asc", sort in ascending order // and remove the prefix. if (by.substring(0,3) == 'asc') { var i = by.substring(3); comp = function(a, b) { return a[i] - b[i]; }; } else { // Otherwise sort in descending order. comp = function(a, b) { return b[by] - a[by]; }; } // Reset link styles and format the selected sort option. $('a.sel').attr('href', '#').removeClass('sel'); $('a.by' + by).removeAttr('href').addClass('sel'); }
[ "function", "setComparator", "(", ")", "{", "if", "(", "by", ".", "substring", "(", "0", ",", "3", ")", "==", "'asc'", ")", "{", "var", "i", "=", "by", ".", "substring", "(", "3", ")", ";", "comp", "=", "function", "(", "a", ",", "b", ")", "{", "return", "a", "[", "i", "]", "-", "b", "[", "i", "]", ";", "}", ";", "}", "else", "{", "comp", "=", "function", "(", "a", ",", "b", ")", "{", "return", "b", "[", "by", "]", "-", "a", "[", "by", "]", ";", "}", ";", "}", "$", "(", "'a.sel'", ")", ".", "attr", "(", "'href'", ",", "'#'", ")", ".", "removeClass", "(", "'sel'", ")", ";", "$", "(", "'a.by'", "+", "by", ")", ".", "removeAttr", "(", "'href'", ")", ".", "addClass", "(", "'sel'", ")", ";", "}" ]
Set comp, which is a comparator function used for sorting and inserting comments into the list.
[ "Set", "comp", "which", "is", "a", "comparator", "function", "used", "for", "sorting", "and", "inserting", "comments", "into", "the", "list", "." ]
0074ec080b988e78d99b6d1f6d297f07bf82efce
https://github.com/shibukawa/i18n4v/blob/0074ec080b988e78d99b6d1f6d297f07bf82efce/docs/_static/websupport.js#L107-L121
train
shibukawa/i18n4v
docs/_static/websupport.js
initComparator
function initComparator() { by = 'rating'; // Default to sort by rating. // If the sortBy cookie is set, use that instead. if (document.cookie.length > 0) { var start = document.cookie.indexOf('sortBy='); if (start != -1) { start = start + 7; var end = document.cookie.indexOf(";", start); if (end == -1) { end = document.cookie.length; by = unescape(document.cookie.substring(start, end)); } } } setComparator(); }
javascript
function initComparator() { by = 'rating'; // Default to sort by rating. // If the sortBy cookie is set, use that instead. if (document.cookie.length > 0) { var start = document.cookie.indexOf('sortBy='); if (start != -1) { start = start + 7; var end = document.cookie.indexOf(";", start); if (end == -1) { end = document.cookie.length; by = unescape(document.cookie.substring(start, end)); } } } setComparator(); }
[ "function", "initComparator", "(", ")", "{", "by", "=", "'rating'", ";", "if", "(", "document", ".", "cookie", ".", "length", ">", "0", ")", "{", "var", "start", "=", "document", ".", "cookie", ".", "indexOf", "(", "'sortBy='", ")", ";", "if", "(", "start", "!=", "-", "1", ")", "{", "start", "=", "start", "+", "7", ";", "var", "end", "=", "document", ".", "cookie", ".", "indexOf", "(", "\";\"", ",", "start", ")", ";", "if", "(", "end", "==", "-", "1", ")", "{", "end", "=", "document", ".", "cookie", ".", "length", ";", "by", "=", "unescape", "(", "document", ".", "cookie", ".", "substring", "(", "start", ",", "end", ")", ")", ";", "}", "}", "}", "setComparator", "(", ")", ";", "}" ]
Create a comp function. If the user has preferences stored in the sortBy cookie, use those, otherwise use the default.
[ "Create", "a", "comp", "function", ".", "If", "the", "user", "has", "preferences", "stored", "in", "the", "sortBy", "cookie", "use", "those", "otherwise", "use", "the", "default", "." ]
0074ec080b988e78d99b6d1f6d297f07bf82efce
https://github.com/shibukawa/i18n4v/blob/0074ec080b988e78d99b6d1f6d297f07bf82efce/docs/_static/websupport.js#L127-L142
train
shibukawa/i18n4v
docs/_static/websupport.js
show
function show(id) { $('#ao' + id).hide(); $('#ah' + id).show(); var context = $.extend({id: id}, opts); var popup = $(renderTemplate(popupTemplate, context)).hide(); popup.find('textarea[name="proposal"]').hide(); popup.find('a.by' + by).addClass('sel'); var form = popup.find('#cf' + id); form.submit(function(event) { event.preventDefault(); addComment(form); }); $('#s' + id).after(popup); popup.slideDown('fast', function() { getComments(id); }); }
javascript
function show(id) { $('#ao' + id).hide(); $('#ah' + id).show(); var context = $.extend({id: id}, opts); var popup = $(renderTemplate(popupTemplate, context)).hide(); popup.find('textarea[name="proposal"]').hide(); popup.find('a.by' + by).addClass('sel'); var form = popup.find('#cf' + id); form.submit(function(event) { event.preventDefault(); addComment(form); }); $('#s' + id).after(popup); popup.slideDown('fast', function() { getComments(id); }); }
[ "function", "show", "(", "id", ")", "{", "$", "(", "'#ao'", "+", "id", ")", ".", "hide", "(", ")", ";", "$", "(", "'#ah'", "+", "id", ")", ".", "show", "(", ")", ";", "var", "context", "=", "$", ".", "extend", "(", "{", "id", ":", "id", "}", ",", "opts", ")", ";", "var", "popup", "=", "$", "(", "renderTemplate", "(", "popupTemplate", ",", "context", ")", ")", ".", "hide", "(", ")", ";", "popup", ".", "find", "(", "'textarea[name=\"proposal\"]'", ")", ".", "hide", "(", ")", ";", "popup", ".", "find", "(", "'a.by'", "+", "by", ")", ".", "addClass", "(", "'sel'", ")", ";", "var", "form", "=", "popup", ".", "find", "(", "'#cf'", "+", "id", ")", ";", "form", ".", "submit", "(", "function", "(", "event", ")", "{", "event", ".", "preventDefault", "(", ")", ";", "addComment", "(", "form", ")", ";", "}", ")", ";", "$", "(", "'#s'", "+", "id", ")", ".", "after", "(", "popup", ")", ";", "popup", ".", "slideDown", "(", "'fast'", ",", "function", "(", ")", "{", "getComments", "(", "id", ")", ";", "}", ")", ";", "}" ]
Show a comment div.
[ "Show", "a", "comment", "div", "." ]
0074ec080b988e78d99b6d1f6d297f07bf82efce
https://github.com/shibukawa/i18n4v/blob/0074ec080b988e78d99b6d1f6d297f07bf82efce/docs/_static/websupport.js#L147-L163
train
shibukawa/i18n4v
docs/_static/websupport.js
hide
function hide(id) { $('#ah' + id).hide(); $('#ao' + id).show(); var div = $('#sc' + id); div.slideUp('fast', function() { div.remove(); }); }
javascript
function hide(id) { $('#ah' + id).hide(); $('#ao' + id).show(); var div = $('#sc' + id); div.slideUp('fast', function() { div.remove(); }); }
[ "function", "hide", "(", "id", ")", "{", "$", "(", "'#ah'", "+", "id", ")", ".", "hide", "(", ")", ";", "$", "(", "'#ao'", "+", "id", ")", ".", "show", "(", ")", ";", "var", "div", "=", "$", "(", "'#sc'", "+", "id", ")", ";", "div", ".", "slideUp", "(", "'fast'", ",", "function", "(", ")", "{", "div", ".", "remove", "(", ")", ";", "}", ")", ";", "}" ]
Hide a comment div.
[ "Hide", "a", "comment", "div", "." ]
0074ec080b988e78d99b6d1f6d297f07bf82efce
https://github.com/shibukawa/i18n4v/blob/0074ec080b988e78d99b6d1f6d297f07bf82efce/docs/_static/websupport.js#L168-L175
train
shibukawa/i18n4v
docs/_static/websupport.js
getComments
function getComments(id) { $.ajax({ type: 'GET', url: opts.getCommentsURL, data: {node: id}, success: function(data, textStatus, request) { var ul = $('#cl' + id); var speed = 100; $('#cf' + id) .find('textarea[name="proposal"]') .data('source', data.source); if (data.comments.length === 0) { ul.html('<li>No comments yet.</li>'); ul.data('empty', true); } else { // If there are comments, sort them and put them in the list. var comments = sortComments(data.comments); speed = data.comments.length * 100; appendComments(comments, ul); ul.data('empty', false); } $('#cn' + id).slideUp(speed + 200); ul.slideDown(speed); }, error: function(request, textStatus, error) { showError('Oops, there was a problem retrieving the comments.'); }, dataType: 'json' }); }
javascript
function getComments(id) { $.ajax({ type: 'GET', url: opts.getCommentsURL, data: {node: id}, success: function(data, textStatus, request) { var ul = $('#cl' + id); var speed = 100; $('#cf' + id) .find('textarea[name="proposal"]') .data('source', data.source); if (data.comments.length === 0) { ul.html('<li>No comments yet.</li>'); ul.data('empty', true); } else { // If there are comments, sort them and put them in the list. var comments = sortComments(data.comments); speed = data.comments.length * 100; appendComments(comments, ul); ul.data('empty', false); } $('#cn' + id).slideUp(speed + 200); ul.slideDown(speed); }, error: function(request, textStatus, error) { showError('Oops, there was a problem retrieving the comments.'); }, dataType: 'json' }); }
[ "function", "getComments", "(", "id", ")", "{", "$", ".", "ajax", "(", "{", "type", ":", "'GET'", ",", "url", ":", "opts", ".", "getCommentsURL", ",", "data", ":", "{", "node", ":", "id", "}", ",", "success", ":", "function", "(", "data", ",", "textStatus", ",", "request", ")", "{", "var", "ul", "=", "$", "(", "'#cl'", "+", "id", ")", ";", "var", "speed", "=", "100", ";", "$", "(", "'#cf'", "+", "id", ")", ".", "find", "(", "'textarea[name=\"proposal\"]'", ")", ".", "data", "(", "'source'", ",", "data", ".", "source", ")", ";", "if", "(", "data", ".", "comments", ".", "length", "===", "0", ")", "{", "ul", ".", "html", "(", "'<li>No comments yet.</li>'", ")", ";", "ul", ".", "data", "(", "'empty'", ",", "true", ")", ";", "}", "else", "{", "var", "comments", "=", "sortComments", "(", "data", ".", "comments", ")", ";", "speed", "=", "data", ".", "comments", ".", "length", "*", "100", ";", "appendComments", "(", "comments", ",", "ul", ")", ";", "ul", ".", "data", "(", "'empty'", ",", "false", ")", ";", "}", "$", "(", "'#cn'", "+", "id", ")", ".", "slideUp", "(", "speed", "+", "200", ")", ";", "ul", ".", "slideDown", "(", "speed", ")", ";", "}", ",", "error", ":", "function", "(", "request", ",", "textStatus", ",", "error", ")", "{", "showError", "(", "'Oops, there was a problem retrieving the comments.'", ")", ";", "}", ",", "dataType", ":", "'json'", "}", ")", ";", "}" ]
Perform an ajax request to get comments for a node and insert the comments into the comments tree.
[ "Perform", "an", "ajax", "request", "to", "get", "comments", "for", "a", "node", "and", "insert", "the", "comments", "into", "the", "comments", "tree", "." ]
0074ec080b988e78d99b6d1f6d297f07bf82efce
https://github.com/shibukawa/i18n4v/blob/0074ec080b988e78d99b6d1f6d297f07bf82efce/docs/_static/websupport.js#L181-L211
train
shibukawa/i18n4v
docs/_static/websupport.js
addComment
function addComment(form) { var node_id = form.find('input[name="node"]').val(); var parent_id = form.find('input[name="parent"]').val(); var text = form.find('textarea[name="comment"]').val(); var proposal = form.find('textarea[name="proposal"]').val(); if (text == '') { showError('Please enter a comment.'); return; } // Disable the form that is being submitted. form.find('textarea,input').attr('disabled', 'disabled'); // Send the comment to the server. $.ajax({ type: "POST", url: opts.addCommentURL, dataType: 'json', data: { node: node_id, parent: parent_id, text: text, proposal: proposal }, success: function(data, textStatus, error) { // Reset the form. if (node_id) { hideProposeChange(node_id); } form.find('textarea') .val('') .add(form.find('input')) .removeAttr('disabled'); var ul = $('#cl' + (node_id || parent_id)); if (ul.data('empty')) { $(ul).empty(); ul.data('empty', false); } insertComment(data.comment); var ao = $('#ao' + node_id); ao.find('img').attr({'src': opts.commentBrightImage}); if (node_id) { // if this was a "root" comment, remove the commenting box // (the user can get it back by reopening the comment popup) $('#ca' + node_id).slideUp(); } }, error: function(request, textStatus, error) { form.find('textarea,input').removeAttr('disabled'); showError('Oops, there was a problem adding the comment.'); } }); }
javascript
function addComment(form) { var node_id = form.find('input[name="node"]').val(); var parent_id = form.find('input[name="parent"]').val(); var text = form.find('textarea[name="comment"]').val(); var proposal = form.find('textarea[name="proposal"]').val(); if (text == '') { showError('Please enter a comment.'); return; } // Disable the form that is being submitted. form.find('textarea,input').attr('disabled', 'disabled'); // Send the comment to the server. $.ajax({ type: "POST", url: opts.addCommentURL, dataType: 'json', data: { node: node_id, parent: parent_id, text: text, proposal: proposal }, success: function(data, textStatus, error) { // Reset the form. if (node_id) { hideProposeChange(node_id); } form.find('textarea') .val('') .add(form.find('input')) .removeAttr('disabled'); var ul = $('#cl' + (node_id || parent_id)); if (ul.data('empty')) { $(ul).empty(); ul.data('empty', false); } insertComment(data.comment); var ao = $('#ao' + node_id); ao.find('img').attr({'src': opts.commentBrightImage}); if (node_id) { // if this was a "root" comment, remove the commenting box // (the user can get it back by reopening the comment popup) $('#ca' + node_id).slideUp(); } }, error: function(request, textStatus, error) { form.find('textarea,input').removeAttr('disabled'); showError('Oops, there was a problem adding the comment.'); } }); }
[ "function", "addComment", "(", "form", ")", "{", "var", "node_id", "=", "form", ".", "find", "(", "'input[name=\"node\"]'", ")", ".", "val", "(", ")", ";", "var", "parent_id", "=", "form", ".", "find", "(", "'input[name=\"parent\"]'", ")", ".", "val", "(", ")", ";", "var", "text", "=", "form", ".", "find", "(", "'textarea[name=\"comment\"]'", ")", ".", "val", "(", ")", ";", "var", "proposal", "=", "form", ".", "find", "(", "'textarea[name=\"proposal\"]'", ")", ".", "val", "(", ")", ";", "if", "(", "text", "==", "''", ")", "{", "showError", "(", "'Please enter a comment.'", ")", ";", "return", ";", "}", "form", ".", "find", "(", "'textarea,input'", ")", ".", "attr", "(", "'disabled'", ",", "'disabled'", ")", ";", "$", ".", "ajax", "(", "{", "type", ":", "\"POST\"", ",", "url", ":", "opts", ".", "addCommentURL", ",", "dataType", ":", "'json'", ",", "data", ":", "{", "node", ":", "node_id", ",", "parent", ":", "parent_id", ",", "text", ":", "text", ",", "proposal", ":", "proposal", "}", ",", "success", ":", "function", "(", "data", ",", "textStatus", ",", "error", ")", "{", "if", "(", "node_id", ")", "{", "hideProposeChange", "(", "node_id", ")", ";", "}", "form", ".", "find", "(", "'textarea'", ")", ".", "val", "(", "''", ")", ".", "add", "(", "form", ".", "find", "(", "'input'", ")", ")", ".", "removeAttr", "(", "'disabled'", ")", ";", "var", "ul", "=", "$", "(", "'#cl'", "+", "(", "node_id", "||", "parent_id", ")", ")", ";", "if", "(", "ul", ".", "data", "(", "'empty'", ")", ")", "{", "$", "(", "ul", ")", ".", "empty", "(", ")", ";", "ul", ".", "data", "(", "'empty'", ",", "false", ")", ";", "}", "insertComment", "(", "data", ".", "comment", ")", ";", "var", "ao", "=", "$", "(", "'#ao'", "+", "node_id", ")", ";", "ao", ".", "find", "(", "'img'", ")", ".", "attr", "(", "{", "'src'", ":", "opts", ".", "commentBrightImage", "}", ")", ";", "if", "(", "node_id", ")", "{", "$", "(", "'#ca'", "+", "node_id", ")", ".", "slideUp", "(", ")", ";", "}", "}", ",", "error", ":", "function", "(", "request", ",", "textStatus", ",", "error", ")", "{", "form", ".", "find", "(", "'textarea,input'", ")", ".", "removeAttr", "(", "'disabled'", ")", ";", "showError", "(", "'Oops, there was a problem adding the comment.'", ")", ";", "}", "}", ")", ";", "}" ]
Add a comment via ajax and insert the comment into the comment tree.
[ "Add", "a", "comment", "via", "ajax", "and", "insert", "the", "comment", "into", "the", "comment", "tree", "." ]
0074ec080b988e78d99b6d1f6d297f07bf82efce
https://github.com/shibukawa/i18n4v/blob/0074ec080b988e78d99b6d1f6d297f07bf82efce/docs/_static/websupport.js#L216-L269
train
shibukawa/i18n4v
docs/_static/websupport.js
appendComments
function appendComments(comments, ul) { $.each(comments, function() { var div = createCommentDiv(this); ul.append($(document.createElement('li')).html(div)); appendComments(this.children, div.find('ul.comment-children')); // To avoid stagnating data, don't store the comments children in data. this.children = null; div.data('comment', this); }); }
javascript
function appendComments(comments, ul) { $.each(comments, function() { var div = createCommentDiv(this); ul.append($(document.createElement('li')).html(div)); appendComments(this.children, div.find('ul.comment-children')); // To avoid stagnating data, don't store the comments children in data. this.children = null; div.data('comment', this); }); }
[ "function", "appendComments", "(", "comments", ",", "ul", ")", "{", "$", ".", "each", "(", "comments", ",", "function", "(", ")", "{", "var", "div", "=", "createCommentDiv", "(", "this", ")", ";", "ul", ".", "append", "(", "$", "(", "document", ".", "createElement", "(", "'li'", ")", ")", ".", "html", "(", "div", ")", ")", ";", "appendComments", "(", "this", ".", "children", ",", "div", ".", "find", "(", "'ul.comment-children'", ")", ")", ";", "this", ".", "children", "=", "null", ";", "div", ".", "data", "(", "'comment'", ",", "this", ")", ";", "}", ")", ";", "}" ]
Recursively append comments to the main comment list and children lists, creating the comment tree.
[ "Recursively", "append", "comments", "to", "the", "main", "comment", "list", "and", "children", "lists", "creating", "the", "comment", "tree", "." ]
0074ec080b988e78d99b6d1f6d297f07bf82efce
https://github.com/shibukawa/i18n4v/blob/0074ec080b988e78d99b6d1f6d297f07bf82efce/docs/_static/websupport.js#L275-L284
train
shibukawa/i18n4v
docs/_static/websupport.js
insertComment
function insertComment(comment) { var div = createCommentDiv(comment); // To avoid stagnating data, don't store the comments children in data. comment.children = null; div.data('comment', comment); var ul = $('#cl' + (comment.node || comment.parent)); var siblings = getChildren(ul); var li = $(document.createElement('li')); li.hide(); // Determine where in the parents children list to insert this comment. for(i=0; i < siblings.length; i++) { if (comp(comment, siblings[i]) <= 0) { $('#cd' + siblings[i].id) .parent() .before(li.html(div)); li.slideDown('fast'); return; } } // If we get here, this comment rates lower than all the others, // or it is the only comment in the list. ul.append(li.html(div)); li.slideDown('fast'); }
javascript
function insertComment(comment) { var div = createCommentDiv(comment); // To avoid stagnating data, don't store the comments children in data. comment.children = null; div.data('comment', comment); var ul = $('#cl' + (comment.node || comment.parent)); var siblings = getChildren(ul); var li = $(document.createElement('li')); li.hide(); // Determine where in the parents children list to insert this comment. for(i=0; i < siblings.length; i++) { if (comp(comment, siblings[i]) <= 0) { $('#cd' + siblings[i].id) .parent() .before(li.html(div)); li.slideDown('fast'); return; } } // If we get here, this comment rates lower than all the others, // or it is the only comment in the list. ul.append(li.html(div)); li.slideDown('fast'); }
[ "function", "insertComment", "(", "comment", ")", "{", "var", "div", "=", "createCommentDiv", "(", "comment", ")", ";", "comment", ".", "children", "=", "null", ";", "div", ".", "data", "(", "'comment'", ",", "comment", ")", ";", "var", "ul", "=", "$", "(", "'#cl'", "+", "(", "comment", ".", "node", "||", "comment", ".", "parent", ")", ")", ";", "var", "siblings", "=", "getChildren", "(", "ul", ")", ";", "var", "li", "=", "$", "(", "document", ".", "createElement", "(", "'li'", ")", ")", ";", "li", ".", "hide", "(", ")", ";", "for", "(", "i", "=", "0", ";", "i", "<", "siblings", ".", "length", ";", "i", "++", ")", "{", "if", "(", "comp", "(", "comment", ",", "siblings", "[", "i", "]", ")", "<=", "0", ")", "{", "$", "(", "'#cd'", "+", "siblings", "[", "i", "]", ".", "id", ")", ".", "parent", "(", ")", ".", "before", "(", "li", ".", "html", "(", "div", ")", ")", ";", "li", ".", "slideDown", "(", "'fast'", ")", ";", "return", ";", "}", "}", "ul", ".", "append", "(", "li", ".", "html", "(", "div", ")", ")", ";", "li", ".", "slideDown", "(", "'fast'", ")", ";", "}" ]
After adding a new comment, it must be inserted in the correct location in the comment tree.
[ "After", "adding", "a", "new", "comment", "it", "must", "be", "inserted", "in", "the", "correct", "location", "in", "the", "comment", "tree", "." ]
0074ec080b988e78d99b6d1f6d297f07bf82efce
https://github.com/shibukawa/i18n4v/blob/0074ec080b988e78d99b6d1f6d297f07bf82efce/docs/_static/websupport.js#L290-L318
train
shibukawa/i18n4v
docs/_static/websupport.js
handleReSort
function handleReSort(link) { var classes = link.attr('class').split(/\s+/); for (var i=0; i<classes.length; i++) { if (classes[i] != 'sort-option') { by = classes[i].substring(2); } } setComparator(); // Save/update the sortBy cookie. var expiration = new Date(); expiration.setDate(expiration.getDate() + 365); document.cookie= 'sortBy=' + escape(by) + ';expires=' + expiration.toUTCString(); $('ul.comment-ul').each(function(index, ul) { var comments = getChildren($(ul), true); comments = sortComments(comments); appendComments(comments, $(ul).empty()); }); }
javascript
function handleReSort(link) { var classes = link.attr('class').split(/\s+/); for (var i=0; i<classes.length; i++) { if (classes[i] != 'sort-option') { by = classes[i].substring(2); } } setComparator(); // Save/update the sortBy cookie. var expiration = new Date(); expiration.setDate(expiration.getDate() + 365); document.cookie= 'sortBy=' + escape(by) + ';expires=' + expiration.toUTCString(); $('ul.comment-ul').each(function(index, ul) { var comments = getChildren($(ul), true); comments = sortComments(comments); appendComments(comments, $(ul).empty()); }); }
[ "function", "handleReSort", "(", "link", ")", "{", "var", "classes", "=", "link", ".", "attr", "(", "'class'", ")", ".", "split", "(", "/", "\\s+", "/", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "classes", ".", "length", ";", "i", "++", ")", "{", "if", "(", "classes", "[", "i", "]", "!=", "'sort-option'", ")", "{", "by", "=", "classes", "[", "i", "]", ".", "substring", "(", "2", ")", ";", "}", "}", "setComparator", "(", ")", ";", "var", "expiration", "=", "new", "Date", "(", ")", ";", "expiration", ".", "setDate", "(", "expiration", ".", "getDate", "(", ")", "+", "365", ")", ";", "document", ".", "cookie", "=", "'sortBy='", "+", "escape", "(", "by", ")", "+", "';expires='", "+", "expiration", ".", "toUTCString", "(", ")", ";", "$", "(", "'ul.comment-ul'", ")", ".", "each", "(", "function", "(", "index", ",", "ul", ")", "{", "var", "comments", "=", "getChildren", "(", "$", "(", "ul", ")", ",", "true", ")", ";", "comments", "=", "sortComments", "(", "comments", ")", ";", "appendComments", "(", "comments", ",", "$", "(", "ul", ")", ".", "empty", "(", ")", ")", ";", "}", ")", ";", "}" ]
Handle when the user clicks on a sort by link.
[ "Handle", "when", "the", "user", "clicks", "on", "a", "sort", "by", "link", "." ]
0074ec080b988e78d99b6d1f6d297f07bf82efce
https://github.com/shibukawa/i18n4v/blob/0074ec080b988e78d99b6d1f6d297f07bf82efce/docs/_static/websupport.js#L403-L421
train
shibukawa/i18n4v
docs/_static/websupport.js
handleVote
function handleVote(link) { if (!opts.voting) { showError("You'll need to login to vote."); return; } var id = link.attr('id'); if (!id) { // Didn't click on one of the voting arrows. return; } // If it is an unvote, the new vote value is 0, // Otherwise it's 1 for an upvote, or -1 for a downvote. var value = 0; if (id.charAt(1) != 'u') { value = id.charAt(0) == 'u' ? 1 : -1; } // The data to be sent to the server. var d = { comment_id: id.substring(2), value: value }; // Swap the vote and unvote links. link.hide(); $('#' + id.charAt(0) + (id.charAt(1) == 'u' ? 'v' : 'u') + d.comment_id) .show(); // The div the comment is displayed in. var div = $('div#cd' + d.comment_id); var data = div.data('comment'); // If this is not an unvote, and the other vote arrow has // already been pressed, unpress it. if ((d.value !== 0) && (data.vote === d.value * -1)) { $('#' + (d.value == 1 ? 'd' : 'u') + 'u' + d.comment_id).hide(); $('#' + (d.value == 1 ? 'd' : 'u') + 'v' + d.comment_id).show(); } // Update the comments rating in the local data. data.rating += (data.vote === 0) ? d.value : (d.value - data.vote); data.vote = d.value; div.data('comment', data); // Change the rating text. div.find('.rating:first') .text(data.rating + ' point' + (data.rating == 1 ? '' : 's')); // Send the vote information to the server. $.ajax({ type: "POST", url: opts.processVoteURL, data: d, error: function(request, textStatus, error) { showError('Oops, there was a problem casting that vote.'); } }); }
javascript
function handleVote(link) { if (!opts.voting) { showError("You'll need to login to vote."); return; } var id = link.attr('id'); if (!id) { // Didn't click on one of the voting arrows. return; } // If it is an unvote, the new vote value is 0, // Otherwise it's 1 for an upvote, or -1 for a downvote. var value = 0; if (id.charAt(1) != 'u') { value = id.charAt(0) == 'u' ? 1 : -1; } // The data to be sent to the server. var d = { comment_id: id.substring(2), value: value }; // Swap the vote and unvote links. link.hide(); $('#' + id.charAt(0) + (id.charAt(1) == 'u' ? 'v' : 'u') + d.comment_id) .show(); // The div the comment is displayed in. var div = $('div#cd' + d.comment_id); var data = div.data('comment'); // If this is not an unvote, and the other vote arrow has // already been pressed, unpress it. if ((d.value !== 0) && (data.vote === d.value * -1)) { $('#' + (d.value == 1 ? 'd' : 'u') + 'u' + d.comment_id).hide(); $('#' + (d.value == 1 ? 'd' : 'u') + 'v' + d.comment_id).show(); } // Update the comments rating in the local data. data.rating += (data.vote === 0) ? d.value : (d.value - data.vote); data.vote = d.value; div.data('comment', data); // Change the rating text. div.find('.rating:first') .text(data.rating + ' point' + (data.rating == 1 ? '' : 's')); // Send the vote information to the server. $.ajax({ type: "POST", url: opts.processVoteURL, data: d, error: function(request, textStatus, error) { showError('Oops, there was a problem casting that vote.'); } }); }
[ "function", "handleVote", "(", "link", ")", "{", "if", "(", "!", "opts", ".", "voting", ")", "{", "showError", "(", "\"You'll need to login to vote.\"", ")", ";", "return", ";", "}", "var", "id", "=", "link", ".", "attr", "(", "'id'", ")", ";", "if", "(", "!", "id", ")", "{", "return", ";", "}", "var", "value", "=", "0", ";", "if", "(", "id", ".", "charAt", "(", "1", ")", "!=", "'u'", ")", "{", "value", "=", "id", ".", "charAt", "(", "0", ")", "==", "'u'", "?", "1", ":", "-", "1", ";", "}", "var", "d", "=", "{", "comment_id", ":", "id", ".", "substring", "(", "2", ")", ",", "value", ":", "value", "}", ";", "link", ".", "hide", "(", ")", ";", "$", "(", "'#'", "+", "id", ".", "charAt", "(", "0", ")", "+", "(", "id", ".", "charAt", "(", "1", ")", "==", "'u'", "?", "'v'", ":", "'u'", ")", "+", "d", ".", "comment_id", ")", ".", "show", "(", ")", ";", "var", "div", "=", "$", "(", "'div#cd'", "+", "d", ".", "comment_id", ")", ";", "var", "data", "=", "div", ".", "data", "(", "'comment'", ")", ";", "if", "(", "(", "d", ".", "value", "!==", "0", ")", "&&", "(", "data", ".", "vote", "===", "d", ".", "value", "*", "-", "1", ")", ")", "{", "$", "(", "'#'", "+", "(", "d", ".", "value", "==", "1", "?", "'d'", ":", "'u'", ")", "+", "'u'", "+", "d", ".", "comment_id", ")", ".", "hide", "(", ")", ";", "$", "(", "'#'", "+", "(", "d", ".", "value", "==", "1", "?", "'d'", ":", "'u'", ")", "+", "'v'", "+", "d", ".", "comment_id", ")", ".", "show", "(", ")", ";", "}", "data", ".", "rating", "+=", "(", "data", ".", "vote", "===", "0", ")", "?", "d", ".", "value", ":", "(", "d", ".", "value", "-", "data", ".", "vote", ")", ";", "data", ".", "vote", "=", "d", ".", "value", ";", "div", ".", "data", "(", "'comment'", ",", "data", ")", ";", "div", ".", "find", "(", "'.rating:first'", ")", ".", "text", "(", "data", ".", "rating", "+", "' point'", "+", "(", "data", ".", "rating", "==", "1", "?", "''", ":", "'s'", ")", ")", ";", "$", ".", "ajax", "(", "{", "type", ":", "\"POST\"", ",", "url", ":", "opts", ".", "processVoteURL", ",", "data", ":", "d", ",", "error", ":", "function", "(", "request", ",", "textStatus", ",", "error", ")", "{", "showError", "(", "'Oops, there was a problem casting that vote.'", ")", ";", "}", "}", ")", ";", "}" ]
Function to process a vote when a user clicks an arrow.
[ "Function", "to", "process", "a", "vote", "when", "a", "user", "clicks", "an", "arrow", "." ]
0074ec080b988e78d99b6d1f6d297f07bf82efce
https://github.com/shibukawa/i18n4v/blob/0074ec080b988e78d99b6d1f6d297f07bf82efce/docs/_static/websupport.js#L426-L483
train
shibukawa/i18n4v
docs/_static/websupport.js
openReply
function openReply(id) { // Swap out the reply link for the hide link $('#rl' + id).hide(); $('#cr' + id).show(); // Add the reply li to the children ul. var div = $(renderTemplate(replyTemplate, {id: id})).hide(); $('#cl' + id) .prepend(div) // Setup the submit handler for the reply form. .find('#rf' + id) .submit(function(event) { event.preventDefault(); addComment($('#rf' + id)); closeReply(id); }) .find('input[type=button]') .click(function() { closeReply(id); }); div.slideDown('fast', function() { $('#rf' + id).find('textarea').focus(); }); }
javascript
function openReply(id) { // Swap out the reply link for the hide link $('#rl' + id).hide(); $('#cr' + id).show(); // Add the reply li to the children ul. var div = $(renderTemplate(replyTemplate, {id: id})).hide(); $('#cl' + id) .prepend(div) // Setup the submit handler for the reply form. .find('#rf' + id) .submit(function(event) { event.preventDefault(); addComment($('#rf' + id)); closeReply(id); }) .find('input[type=button]') .click(function() { closeReply(id); }); div.slideDown('fast', function() { $('#rf' + id).find('textarea').focus(); }); }
[ "function", "openReply", "(", "id", ")", "{", "$", "(", "'#rl'", "+", "id", ")", ".", "hide", "(", ")", ";", "$", "(", "'#cr'", "+", "id", ")", ".", "show", "(", ")", ";", "var", "div", "=", "$", "(", "renderTemplate", "(", "replyTemplate", ",", "{", "id", ":", "id", "}", ")", ")", ".", "hide", "(", ")", ";", "$", "(", "'#cl'", "+", "id", ")", ".", "prepend", "(", "div", ")", ".", "find", "(", "'#rf'", "+", "id", ")", ".", "submit", "(", "function", "(", "event", ")", "{", "event", ".", "preventDefault", "(", ")", ";", "addComment", "(", "$", "(", "'#rf'", "+", "id", ")", ")", ";", "closeReply", "(", "id", ")", ";", "}", ")", ".", "find", "(", "'input[type=button]'", ")", ".", "click", "(", "function", "(", ")", "{", "closeReply", "(", "id", ")", ";", "}", ")", ";", "div", ".", "slideDown", "(", "'fast'", ",", "function", "(", ")", "{", "$", "(", "'#rf'", "+", "id", ")", ".", "find", "(", "'textarea'", ")", ".", "focus", "(", ")", ";", "}", ")", ";", "}" ]
Open a reply form used to reply to an existing comment.
[ "Open", "a", "reply", "form", "used", "to", "reply", "to", "an", "existing", "comment", "." ]
0074ec080b988e78d99b6d1f6d297f07bf82efce
https://github.com/shibukawa/i18n4v/blob/0074ec080b988e78d99b6d1f6d297f07bf82efce/docs/_static/websupport.js#L488-L511
train
shibukawa/i18n4v
docs/_static/websupport.js
sortComments
function sortComments(comments) { comments.sort(comp); $.each(comments, function() { this.children = sortComments(this.children); }); return comments; }
javascript
function sortComments(comments) { comments.sort(comp); $.each(comments, function() { this.children = sortComments(this.children); }); return comments; }
[ "function", "sortComments", "(", "comments", ")", "{", "comments", ".", "sort", "(", "comp", ")", ";", "$", ".", "each", "(", "comments", ",", "function", "(", ")", "{", "this", ".", "children", "=", "sortComments", "(", "this", ".", "children", ")", ";", "}", ")", ";", "return", "comments", ";", "}" ]
Recursively sort a tree of comments using the comp comparator.
[ "Recursively", "sort", "a", "tree", "of", "comments", "using", "the", "comp", "comparator", "." ]
0074ec080b988e78d99b6d1f6d297f07bf82efce
https://github.com/shibukawa/i18n4v/blob/0074ec080b988e78d99b6d1f6d297f07bf82efce/docs/_static/websupport.js#L530-L536
train
shibukawa/i18n4v
docs/_static/websupport.js
getChildren
function getChildren(ul, recursive) { var children = []; ul.children().children("[id^='cd']") .each(function() { var comment = $(this).data('comment'); if (recursive) comment.children = getChildren($(this).find('#cl' + comment.id), true); children.push(comment); }); return children; }
javascript
function getChildren(ul, recursive) { var children = []; ul.children().children("[id^='cd']") .each(function() { var comment = $(this).data('comment'); if (recursive) comment.children = getChildren($(this).find('#cl' + comment.id), true); children.push(comment); }); return children; }
[ "function", "getChildren", "(", "ul", ",", "recursive", ")", "{", "var", "children", "=", "[", "]", ";", "ul", ".", "children", "(", ")", ".", "children", "(", "\"[id^='cd']\"", ")", ".", "each", "(", "function", "(", ")", "{", "var", "comment", "=", "$", "(", "this", ")", ".", "data", "(", "'comment'", ")", ";", "if", "(", "recursive", ")", "comment", ".", "children", "=", "getChildren", "(", "$", "(", "this", ")", ".", "find", "(", "'#cl'", "+", "comment", ".", "id", ")", ",", "true", ")", ";", "children", ".", "push", "(", "comment", ")", ";", "}", ")", ";", "return", "children", ";", "}" ]
Get the children comments from a ul. If recursive is true, recursively include childrens' children.
[ "Get", "the", "children", "comments", "from", "a", "ul", ".", "If", "recursive", "is", "true", "recursively", "include", "childrens", "children", "." ]
0074ec080b988e78d99b6d1f6d297f07bf82efce
https://github.com/shibukawa/i18n4v/blob/0074ec080b988e78d99b6d1f6d297f07bf82efce/docs/_static/websupport.js#L542-L552
train
shibukawa/i18n4v
docs/_static/websupport.js
createCommentDiv
function createCommentDiv(comment) { if (!comment.displayed && !opts.moderator) { return $('<div class="moderate">Thank you! Your comment will show up ' + 'once it is has been approved by a moderator.</div>'); } // Prettify the comment rating. comment.pretty_rating = comment.rating + ' point' + (comment.rating == 1 ? '' : 's'); // Make a class (for displaying not yet moderated comments differently) comment.css_class = comment.displayed ? '' : ' moderate'; // Create a div for this comment. var context = $.extend({}, opts, comment); var div = $(renderTemplate(commentTemplate, context)); // If the user has voted on this comment, highlight the correct arrow. if (comment.vote) { var direction = (comment.vote == 1) ? 'u' : 'd'; div.find('#' + direction + 'v' + comment.id).hide(); div.find('#' + direction + 'u' + comment.id).show(); } if (opts.moderator || comment.text != '[deleted]') { div.find('a.reply').show(); if (comment.proposal_diff) div.find('#sp' + comment.id).show(); if (opts.moderator && !comment.displayed) div.find('#cm' + comment.id).show(); if (opts.moderator || (opts.username == comment.username)) div.find('#dc' + comment.id).show(); } return div; }
javascript
function createCommentDiv(comment) { if (!comment.displayed && !opts.moderator) { return $('<div class="moderate">Thank you! Your comment will show up ' + 'once it is has been approved by a moderator.</div>'); } // Prettify the comment rating. comment.pretty_rating = comment.rating + ' point' + (comment.rating == 1 ? '' : 's'); // Make a class (for displaying not yet moderated comments differently) comment.css_class = comment.displayed ? '' : ' moderate'; // Create a div for this comment. var context = $.extend({}, opts, comment); var div = $(renderTemplate(commentTemplate, context)); // If the user has voted on this comment, highlight the correct arrow. if (comment.vote) { var direction = (comment.vote == 1) ? 'u' : 'd'; div.find('#' + direction + 'v' + comment.id).hide(); div.find('#' + direction + 'u' + comment.id).show(); } if (opts.moderator || comment.text != '[deleted]') { div.find('a.reply').show(); if (comment.proposal_diff) div.find('#sp' + comment.id).show(); if (opts.moderator && !comment.displayed) div.find('#cm' + comment.id).show(); if (opts.moderator || (opts.username == comment.username)) div.find('#dc' + comment.id).show(); } return div; }
[ "function", "createCommentDiv", "(", "comment", ")", "{", "if", "(", "!", "comment", ".", "displayed", "&&", "!", "opts", ".", "moderator", ")", "{", "return", "$", "(", "'<div class=\"moderate\">Thank you! Your comment will show up '", "+", "'once it is has been approved by a moderator.</div>'", ")", ";", "}", "comment", ".", "pretty_rating", "=", "comment", ".", "rating", "+", "' point'", "+", "(", "comment", ".", "rating", "==", "1", "?", "''", ":", "'s'", ")", ";", "comment", ".", "css_class", "=", "comment", ".", "displayed", "?", "''", ":", "' moderate'", ";", "var", "context", "=", "$", ".", "extend", "(", "{", "}", ",", "opts", ",", "comment", ")", ";", "var", "div", "=", "$", "(", "renderTemplate", "(", "commentTemplate", ",", "context", ")", ")", ";", "if", "(", "comment", ".", "vote", ")", "{", "var", "direction", "=", "(", "comment", ".", "vote", "==", "1", ")", "?", "'u'", ":", "'d'", ";", "div", ".", "find", "(", "'#'", "+", "direction", "+", "'v'", "+", "comment", ".", "id", ")", ".", "hide", "(", ")", ";", "div", ".", "find", "(", "'#'", "+", "direction", "+", "'u'", "+", "comment", ".", "id", ")", ".", "show", "(", ")", ";", "}", "if", "(", "opts", ".", "moderator", "||", "comment", ".", "text", "!=", "'[deleted]'", ")", "{", "div", ".", "find", "(", "'a.reply'", ")", ".", "show", "(", ")", ";", "if", "(", "comment", ".", "proposal_diff", ")", "div", ".", "find", "(", "'#sp'", "+", "comment", ".", "id", ")", ".", "show", "(", ")", ";", "if", "(", "opts", ".", "moderator", "&&", "!", "comment", ".", "displayed", ")", "div", ".", "find", "(", "'#cm'", "+", "comment", ".", "id", ")", ".", "show", "(", ")", ";", "if", "(", "opts", ".", "moderator", "||", "(", "opts", ".", "username", "==", "comment", ".", "username", ")", ")", "div", ".", "find", "(", "'#dc'", "+", "comment", ".", "id", ")", ".", "show", "(", ")", ";", "}", "return", "div", ";", "}" ]
Create a div to display a comment in.
[ "Create", "a", "div", "to", "display", "a", "comment", "in", "." ]
0074ec080b988e78d99b6d1f6d297f07bf82efce
https://github.com/shibukawa/i18n4v/blob/0074ec080b988e78d99b6d1f6d297f07bf82efce/docs/_static/websupport.js#L555-L586
train
shibukawa/i18n4v
docs/_static/websupport.js
showError
function showError(message) { $(document.createElement('div')).attr({'class': 'popup-error'}) .append($(document.createElement('div')) .attr({'class': 'error-message'}).text(message)) .appendTo('body') .fadeIn("slow") .delay(2000) .fadeOut("slow"); }
javascript
function showError(message) { $(document.createElement('div')).attr({'class': 'popup-error'}) .append($(document.createElement('div')) .attr({'class': 'error-message'}).text(message)) .appendTo('body') .fadeIn("slow") .delay(2000) .fadeOut("slow"); }
[ "function", "showError", "(", "message", ")", "{", "$", "(", "document", ".", "createElement", "(", "'div'", ")", ")", ".", "attr", "(", "{", "'class'", ":", "'popup-error'", "}", ")", ".", "append", "(", "$", "(", "document", ".", "createElement", "(", "'div'", ")", ")", ".", "attr", "(", "{", "'class'", ":", "'error-message'", "}", ")", ".", "text", "(", "message", ")", ")", ".", "appendTo", "(", "'body'", ")", ".", "fadeIn", "(", "\"slow\"", ")", ".", "delay", "(", "2000", ")", ".", "fadeOut", "(", "\"slow\"", ")", ";", "}" ]
Flash an error message briefly.
[ "Flash", "an", "error", "message", "briefly", "." ]
0074ec080b988e78d99b6d1f6d297f07bf82efce
https://github.com/shibukawa/i18n4v/blob/0074ec080b988e78d99b6d1f6d297f07bf82efce/docs/_static/websupport.js#L610-L618
train
shibukawa/i18n4v
docs/_static/searchtools.js
function(object, otherterms) { var filenames = this._index.filenames; var docnames = this._index.docnames; var objects = this._index.objects; var objnames = this._index.objnames; var titles = this._index.titles; var i; var results = []; for (var prefix in objects) { for (var name in objects[prefix]) { var fullname = (prefix ? prefix + '.' : '') + name; if (fullname.toLowerCase().indexOf(object) > -1) { var score = 0; var parts = fullname.split('.'); // check for different match types: exact matches of full name or // "last name" (i.e. last dotted part) if (fullname == object || parts[parts.length - 1] == object) { score += Scorer.objNameMatch; // matches in last name } else if (parts[parts.length - 1].indexOf(object) > -1) { score += Scorer.objPartialMatch; } var match = objects[prefix][name]; var objname = objnames[match[1]][2]; var title = titles[match[0]]; // If more than one term searched for, we require other words to be // found in the name/title/description if (otherterms.length > 0) { var haystack = (prefix + ' ' + name + ' ' + objname + ' ' + title).toLowerCase(); var allfound = true; for (i = 0; i < otherterms.length; i++) { if (haystack.indexOf(otherterms[i]) == -1) { allfound = false; break; } } if (!allfound) { continue; } } var descr = objname + _(', in ') + title; var anchor = match[3]; if (anchor === '') anchor = fullname; else if (anchor == '-') anchor = objnames[match[1]][1] + '-' + fullname; // add custom score for some objects according to scorer if (Scorer.objPrio.hasOwnProperty(match[2])) { score += Scorer.objPrio[match[2]]; } else { score += Scorer.objPrioDefault; } results.push([docnames[match[0]], fullname, '#'+anchor, descr, score, filenames[match[0]]]); } } } return results; }
javascript
function(object, otherterms) { var filenames = this._index.filenames; var docnames = this._index.docnames; var objects = this._index.objects; var objnames = this._index.objnames; var titles = this._index.titles; var i; var results = []; for (var prefix in objects) { for (var name in objects[prefix]) { var fullname = (prefix ? prefix + '.' : '') + name; if (fullname.toLowerCase().indexOf(object) > -1) { var score = 0; var parts = fullname.split('.'); // check for different match types: exact matches of full name or // "last name" (i.e. last dotted part) if (fullname == object || parts[parts.length - 1] == object) { score += Scorer.objNameMatch; // matches in last name } else if (parts[parts.length - 1].indexOf(object) > -1) { score += Scorer.objPartialMatch; } var match = objects[prefix][name]; var objname = objnames[match[1]][2]; var title = titles[match[0]]; // If more than one term searched for, we require other words to be // found in the name/title/description if (otherterms.length > 0) { var haystack = (prefix + ' ' + name + ' ' + objname + ' ' + title).toLowerCase(); var allfound = true; for (i = 0; i < otherterms.length; i++) { if (haystack.indexOf(otherterms[i]) == -1) { allfound = false; break; } } if (!allfound) { continue; } } var descr = objname + _(', in ') + title; var anchor = match[3]; if (anchor === '') anchor = fullname; else if (anchor == '-') anchor = objnames[match[1]][1] + '-' + fullname; // add custom score for some objects according to scorer if (Scorer.objPrio.hasOwnProperty(match[2])) { score += Scorer.objPrio[match[2]]; } else { score += Scorer.objPrioDefault; } results.push([docnames[match[0]], fullname, '#'+anchor, descr, score, filenames[match[0]]]); } } } return results; }
[ "function", "(", "object", ",", "otherterms", ")", "{", "var", "filenames", "=", "this", ".", "_index", ".", "filenames", ";", "var", "docnames", "=", "this", ".", "_index", ".", "docnames", ";", "var", "objects", "=", "this", ".", "_index", ".", "objects", ";", "var", "objnames", "=", "this", ".", "_index", ".", "objnames", ";", "var", "titles", "=", "this", ".", "_index", ".", "titles", ";", "var", "i", ";", "var", "results", "=", "[", "]", ";", "for", "(", "var", "prefix", "in", "objects", ")", "{", "for", "(", "var", "name", "in", "objects", "[", "prefix", "]", ")", "{", "var", "fullname", "=", "(", "prefix", "?", "prefix", "+", "'.'", ":", "''", ")", "+", "name", ";", "if", "(", "fullname", ".", "toLowerCase", "(", ")", ".", "indexOf", "(", "object", ")", ">", "-", "1", ")", "{", "var", "score", "=", "0", ";", "var", "parts", "=", "fullname", ".", "split", "(", "'.'", ")", ";", "if", "(", "fullname", "==", "object", "||", "parts", "[", "parts", ".", "length", "-", "1", "]", "==", "object", ")", "{", "score", "+=", "Scorer", ".", "objNameMatch", ";", "}", "else", "if", "(", "parts", "[", "parts", ".", "length", "-", "1", "]", ".", "indexOf", "(", "object", ")", ">", "-", "1", ")", "{", "score", "+=", "Scorer", ".", "objPartialMatch", ";", "}", "var", "match", "=", "objects", "[", "prefix", "]", "[", "name", "]", ";", "var", "objname", "=", "objnames", "[", "match", "[", "1", "]", "]", "[", "2", "]", ";", "var", "title", "=", "titles", "[", "match", "[", "0", "]", "]", ";", "if", "(", "otherterms", ".", "length", ">", "0", ")", "{", "var", "haystack", "=", "(", "prefix", "+", "' '", "+", "name", "+", "' '", "+", "objname", "+", "' '", "+", "title", ")", ".", "toLowerCase", "(", ")", ";", "var", "allfound", "=", "true", ";", "for", "(", "i", "=", "0", ";", "i", "<", "otherterms", ".", "length", ";", "i", "++", ")", "{", "if", "(", "haystack", ".", "indexOf", "(", "otherterms", "[", "i", "]", ")", "==", "-", "1", ")", "{", "allfound", "=", "false", ";", "break", ";", "}", "}", "if", "(", "!", "allfound", ")", "{", "continue", ";", "}", "}", "var", "descr", "=", "objname", "+", "_", "(", "', in '", ")", "+", "title", ";", "var", "anchor", "=", "match", "[", "3", "]", ";", "if", "(", "anchor", "===", "''", ")", "anchor", "=", "fullname", ";", "else", "if", "(", "anchor", "==", "'-'", ")", "anchor", "=", "objnames", "[", "match", "[", "1", "]", "]", "[", "1", "]", "+", "'-'", "+", "fullname", ";", "if", "(", "Scorer", ".", "objPrio", ".", "hasOwnProperty", "(", "match", "[", "2", "]", ")", ")", "{", "score", "+=", "Scorer", ".", "objPrio", "[", "match", "[", "2", "]", "]", ";", "}", "else", "{", "score", "+=", "Scorer", ".", "objPrioDefault", ";", "}", "results", ".", "push", "(", "[", "docnames", "[", "match", "[", "0", "]", "]", ",", "fullname", ",", "'#'", "+", "anchor", ",", "descr", ",", "score", ",", "filenames", "[", "match", "[", "0", "]", "]", "]", ")", ";", "}", "}", "}", "return", "results", ";", "}" ]
search for object names
[ "search", "for", "object", "names" ]
0074ec080b988e78d99b6d1f6d297f07bf82efce
https://github.com/shibukawa/i18n4v/blob/0074ec080b988e78d99b6d1f6d297f07bf82efce/docs/_static/searchtools.js#L580-L642
train
shibukawa/i18n4v
docs/_static/searchtools.js
function(searchterms, excluded, terms, titleterms) { var docnames = this._index.docnames; var filenames = this._index.filenames; var titles = this._index.titles; var i, j, file; var fileMap = {}; var scoreMap = {}; var results = []; // perform the search on the required terms for (i = 0; i < searchterms.length; i++) { var word = searchterms[i]; var files = []; var _o = [ {files: terms[word], score: Scorer.term}, {files: titleterms[word], score: Scorer.title} ]; // no match but word was a required one if ($u.every(_o, function(o){return o.files === undefined;})) { break; } // found search word in contents $u.each(_o, function(o) { var _files = o.files; if (_files === undefined) return if (_files.length === undefined) _files = [_files]; files = files.concat(_files); // set score for the word in each file to Scorer.term for (j = 0; j < _files.length; j++) { file = _files[j]; if (!(file in scoreMap)) scoreMap[file] = {} scoreMap[file][word] = o.score; } }); // create the mapping for (j = 0; j < files.length; j++) { file = files[j]; if (file in fileMap) fileMap[file].push(word); else fileMap[file] = [word]; } } // now check if the files don't contain excluded terms for (file in fileMap) { var valid = true; // check if all requirements are matched if (fileMap[file].length != searchterms.length) continue; // ensure that none of the excluded terms is in the search result for (i = 0; i < excluded.length; i++) { if (terms[excluded[i]] == file || titleterms[excluded[i]] == file || $u.contains(terms[excluded[i]] || [], file) || $u.contains(titleterms[excluded[i]] || [], file)) { valid = false; break; } } // if we have still a valid result we can add it to the result list if (valid) { // select one (max) score for the file. // for better ranking, we should calculate ranking by using words statistics like basic tf-idf... var score = $u.max($u.map(fileMap[file], function(w){return scoreMap[file][w]})); results.push([docnames[file], titles[file], '', null, score, filenames[file]]); } } return results; }
javascript
function(searchterms, excluded, terms, titleterms) { var docnames = this._index.docnames; var filenames = this._index.filenames; var titles = this._index.titles; var i, j, file; var fileMap = {}; var scoreMap = {}; var results = []; // perform the search on the required terms for (i = 0; i < searchterms.length; i++) { var word = searchterms[i]; var files = []; var _o = [ {files: terms[word], score: Scorer.term}, {files: titleterms[word], score: Scorer.title} ]; // no match but word was a required one if ($u.every(_o, function(o){return o.files === undefined;})) { break; } // found search word in contents $u.each(_o, function(o) { var _files = o.files; if (_files === undefined) return if (_files.length === undefined) _files = [_files]; files = files.concat(_files); // set score for the word in each file to Scorer.term for (j = 0; j < _files.length; j++) { file = _files[j]; if (!(file in scoreMap)) scoreMap[file] = {} scoreMap[file][word] = o.score; } }); // create the mapping for (j = 0; j < files.length; j++) { file = files[j]; if (file in fileMap) fileMap[file].push(word); else fileMap[file] = [word]; } } // now check if the files don't contain excluded terms for (file in fileMap) { var valid = true; // check if all requirements are matched if (fileMap[file].length != searchterms.length) continue; // ensure that none of the excluded terms is in the search result for (i = 0; i < excluded.length; i++) { if (terms[excluded[i]] == file || titleterms[excluded[i]] == file || $u.contains(terms[excluded[i]] || [], file) || $u.contains(titleterms[excluded[i]] || [], file)) { valid = false; break; } } // if we have still a valid result we can add it to the result list if (valid) { // select one (max) score for the file. // for better ranking, we should calculate ranking by using words statistics like basic tf-idf... var score = $u.max($u.map(fileMap[file], function(w){return scoreMap[file][w]})); results.push([docnames[file], titles[file], '', null, score, filenames[file]]); } } return results; }
[ "function", "(", "searchterms", ",", "excluded", ",", "terms", ",", "titleterms", ")", "{", "var", "docnames", "=", "this", ".", "_index", ".", "docnames", ";", "var", "filenames", "=", "this", ".", "_index", ".", "filenames", ";", "var", "titles", "=", "this", ".", "_index", ".", "titles", ";", "var", "i", ",", "j", ",", "file", ";", "var", "fileMap", "=", "{", "}", ";", "var", "scoreMap", "=", "{", "}", ";", "var", "results", "=", "[", "]", ";", "for", "(", "i", "=", "0", ";", "i", "<", "searchterms", ".", "length", ";", "i", "++", ")", "{", "var", "word", "=", "searchterms", "[", "i", "]", ";", "var", "files", "=", "[", "]", ";", "var", "_o", "=", "[", "{", "files", ":", "terms", "[", "word", "]", ",", "score", ":", "Scorer", ".", "term", "}", ",", "{", "files", ":", "titleterms", "[", "word", "]", ",", "score", ":", "Scorer", ".", "title", "}", "]", ";", "if", "(", "$u", ".", "every", "(", "_o", ",", "function", "(", "o", ")", "{", "return", "o", ".", "files", "===", "undefined", ";", "}", ")", ")", "{", "break", ";", "}", "$u", ".", "each", "(", "_o", ",", "function", "(", "o", ")", "{", "var", "_files", "=", "o", ".", "files", ";", "if", "(", "_files", "===", "undefined", ")", "return", "if", "(", "_files", ".", "length", "===", "undefined", ")", "_files", "=", "[", "_files", "]", ";", "files", "=", "files", ".", "concat", "(", "_files", ")", ";", "for", "(", "j", "=", "0", ";", "j", "<", "_files", ".", "length", ";", "j", "++", ")", "{", "file", "=", "_files", "[", "j", "]", ";", "if", "(", "!", "(", "file", "in", "scoreMap", ")", ")", "scoreMap", "[", "file", "]", "=", "{", "}", "scoreMap", "[", "file", "]", "[", "word", "]", "=", "o", ".", "score", ";", "}", "}", ")", ";", "for", "(", "j", "=", "0", ";", "j", "<", "files", ".", "length", ";", "j", "++", ")", "{", "file", "=", "files", "[", "j", "]", ";", "if", "(", "file", "in", "fileMap", ")", "fileMap", "[", "file", "]", ".", "push", "(", "word", ")", ";", "else", "fileMap", "[", "file", "]", "=", "[", "word", "]", ";", "}", "}", "for", "(", "file", "in", "fileMap", ")", "{", "var", "valid", "=", "true", ";", "if", "(", "fileMap", "[", "file", "]", ".", "length", "!=", "searchterms", ".", "length", ")", "continue", ";", "for", "(", "i", "=", "0", ";", "i", "<", "excluded", ".", "length", ";", "i", "++", ")", "{", "if", "(", "terms", "[", "excluded", "[", "i", "]", "]", "==", "file", "||", "titleterms", "[", "excluded", "[", "i", "]", "]", "==", "file", "||", "$u", ".", "contains", "(", "terms", "[", "excluded", "[", "i", "]", "]", "||", "[", "]", ",", "file", ")", "||", "$u", ".", "contains", "(", "titleterms", "[", "excluded", "[", "i", "]", "]", "||", "[", "]", ",", "file", ")", ")", "{", "valid", "=", "false", ";", "break", ";", "}", "}", "if", "(", "valid", ")", "{", "var", "score", "=", "$u", ".", "max", "(", "$u", ".", "map", "(", "fileMap", "[", "file", "]", ",", "function", "(", "w", ")", "{", "return", "scoreMap", "[", "file", "]", "[", "w", "]", "}", ")", ")", ";", "results", ".", "push", "(", "[", "docnames", "[", "file", "]", ",", "titles", "[", "file", "]", ",", "''", ",", "null", ",", "score", ",", "filenames", "[", "file", "]", "]", ")", ";", "}", "}", "return", "results", ";", "}" ]
search for full-text terms in the index
[ "search", "for", "full", "-", "text", "terms", "in", "the", "index" ]
0074ec080b988e78d99b6d1f6d297f07bf82efce
https://github.com/shibukawa/i18n4v/blob/0074ec080b988e78d99b6d1f6d297f07bf82efce/docs/_static/searchtools.js#L647-L727
train
redfin/stratocacher
packages/stratocacher/src/wrap.js
clean
function clean(args) { return Array.prototype.filter.call(args, v => v !== INVALIDATE); }
javascript
function clean(args) { return Array.prototype.filter.call(args, v => v !== INVALIDATE); }
[ "function", "clean", "(", "args", ")", "{", "return", "Array", ".", "prototype", ".", "filter", ".", "call", "(", "args", ",", "v", "=>", "v", "!==", "INVALIDATE", ")", ";", "}" ]
Return an array containing elements from supplied `arguments` object that are not control symbols.
[ "Return", "an", "array", "containing", "elements", "from", "supplied", "arguments", "object", "that", "are", "not", "control", "symbols", "." ]
43e2af5e04966a0ce73012ebba62ff6184cceba6
https://github.com/redfin/stratocacher/blob/43e2af5e04966a0ce73012ebba62ff6184cceba6/packages/stratocacher/src/wrap.js#L221-L223
train
bigeasy/proof
proof.js
json
function json (program, callback) { var formatterRedux = formatter(jsonRedux()) parse(program.stdin, program.stderr, printer(formatterRedux, program.stdout, program.stderr), callback) }
javascript
function json (program, callback) { var formatterRedux = formatter(jsonRedux()) parse(program.stdin, program.stderr, printer(formatterRedux, program.stdout, program.stderr), callback) }
[ "function", "json", "(", "program", ",", "callback", ")", "{", "var", "formatterRedux", "=", "formatter", "(", "jsonRedux", "(", ")", ")", "parse", "(", "program", ".", "stdin", ",", "program", ".", "stderr", ",", "printer", "(", "formatterRedux", ",", "program", ".", "stdout", ",", "program", ".", "stderr", ")", ",", "callback", ")", "}" ]
Moved exports.json to its own file.
[ "Moved", "exports", ".", "json", "to", "its", "own", "file", "." ]
a59210838cc80457ae77e54a2e6d7ce955be9596
https://github.com/bigeasy/proof/blob/a59210838cc80457ae77e54a2e6d7ce955be9596/proof.js#L25-L28
train
thusoy/grunt-pylint
tasks/pylint.js
getPythonExecutable
function getPythonExecutable(options, platform) { if (options.virtualenv) { var isWin = /^win/.test(platform); var pythonExec = isWin ? path.join(options.virtualenv, 'Scripts', 'python.exe') : path.join(options.virtualenv, 'bin', 'python'); delete options.virtualenv; return pythonExec; } else { return 'python'; } }
javascript
function getPythonExecutable(options, platform) { if (options.virtualenv) { var isWin = /^win/.test(platform); var pythonExec = isWin ? path.join(options.virtualenv, 'Scripts', 'python.exe') : path.join(options.virtualenv, 'bin', 'python'); delete options.virtualenv; return pythonExec; } else { return 'python'; } }
[ "function", "getPythonExecutable", "(", "options", ",", "platform", ")", "{", "if", "(", "options", ".", "virtualenv", ")", "{", "var", "isWin", "=", "/", "^win", "/", ".", "test", "(", "platform", ")", ";", "var", "pythonExec", "=", "isWin", "?", "path", ".", "join", "(", "options", ".", "virtualenv", ",", "'Scripts'", ",", "'python.exe'", ")", ":", "path", ".", "join", "(", "options", ".", "virtualenv", ",", "'bin'", ",", "'python'", ")", ";", "delete", "options", ".", "virtualenv", ";", "return", "pythonExec", ";", "}", "else", "{", "return", "'python'", ";", "}", "}" ]
Get the path to the python executable, using the options.virtualenv parameter. Will remove the virtualenv parameter from the options object if present
[ "Get", "the", "path", "to", "the", "python", "executable", "using", "the", "options", ".", "virtualenv", "parameter", ".", "Will", "remove", "the", "virtualenv", "parameter", "from", "the", "options", "object", "if", "present" ]
1911144b76b144c991e721c794640c06101a8bf1
https://github.com/thusoy/grunt-pylint/blob/1911144b76b144c991e721c794640c06101a8bf1/tasks/pylint.js#L23-L34
train
thusoy/grunt-pylint
tasks/pylint.js
getPythonCode
function getPythonCode(options) { var pythonCode = [], internalPylint = !options.externalPylint, pylintPath = path.join(__dirname, 'lib'), initHook = options.initHook; delete options.initHook; if (initHook) { pythonCode.push(initHook); } if (internalPylint) { pythonCode.push('import sys', 'sys.path.insert(0, r"' + pylintPath + '")'); } pythonCode.push('import pylint', 'pylint.run_pylint()'); delete options.externalPylint; return pythonCode.join('; '); }
javascript
function getPythonCode(options) { var pythonCode = [], internalPylint = !options.externalPylint, pylintPath = path.join(__dirname, 'lib'), initHook = options.initHook; delete options.initHook; if (initHook) { pythonCode.push(initHook); } if (internalPylint) { pythonCode.push('import sys', 'sys.path.insert(0, r"' + pylintPath + '")'); } pythonCode.push('import pylint', 'pylint.run_pylint()'); delete options.externalPylint; return pythonCode.join('; '); }
[ "function", "getPythonCode", "(", "options", ")", "{", "var", "pythonCode", "=", "[", "]", ",", "internalPylint", "=", "!", "options", ".", "externalPylint", ",", "pylintPath", "=", "path", ".", "join", "(", "__dirname", ",", "'lib'", ")", ",", "initHook", "=", "options", ".", "initHook", ";", "delete", "options", ".", "initHook", ";", "if", "(", "initHook", ")", "{", "pythonCode", ".", "push", "(", "initHook", ")", ";", "}", "if", "(", "internalPylint", ")", "{", "pythonCode", ".", "push", "(", "'import sys'", ",", "'sys.path.insert(0, r\"'", "+", "pylintPath", "+", "'\")'", ")", ";", "}", "pythonCode", ".", "push", "(", "'import pylint'", ",", "'pylint.run_pylint()'", ")", ";", "delete", "options", ".", "externalPylint", ";", "return", "pythonCode", ".", "join", "(", "'; '", ")", ";", "}" ]
Get the python code that will import and execute pylint Uses the options.externalPylint parameter to determine whether to use the pylint included with the plugin or an external one. externalPylint is deleted from the options object.
[ "Get", "the", "python", "code", "that", "will", "import", "and", "execute", "pylint", "Uses", "the", "options", ".", "externalPylint", "parameter", "to", "determine", "whether", "to", "use", "the", "pylint", "included", "with", "the", "plugin", "or", "an", "external", "one", ".", "externalPylint", "is", "deleted", "from", "the", "options", "object", "." ]
1911144b76b144c991e721c794640c06101a8bf1
https://github.com/thusoy/grunt-pylint/blob/1911144b76b144c991e721c794640c06101a8bf1/tasks/pylint.js#L39-L57
train
thusoy/grunt-pylint
tasks/pylint.js
function (options) { var pylintArgs = []; var enable = options.enable; delete options.enable; if (enable) { pylintArgs.push('--enable=' + enable); } var disable = options.disable; delete options.disable; if (disable) { pylintArgs.push('--disable=' + disable); } var messageTemplate = options.messageTemplate; delete options.messageTemplate; if (messageTemplate) { var aliases = { 'short': "line {line}: {msg} ({symbol})", 'msvs': "{path}({line}): [{msg_id}({symbol}){obj}] {msg}", 'parseable': "{path}:{line}: [{msg_id}({symbol}), {obj}] {msg}", }; if (aliases[messageTemplate] !== undefined) { pylintArgs.push('--msg-template="' + aliases[messageTemplate] + '"'); } else { pylintArgs.push('--msg-template="' + messageTemplate + '"'); } } var outputFormat = options.outputFormat; delete options.outputFormat; if (outputFormat) { pylintArgs.push('--output-format=' + outputFormat); } var report = options.report; delete options.report; // Make compatible with --reports as well if (options.reports) { report = options.reports; delete options.reports; } if (report) { pylintArgs.push('--reports=y'); } else { pylintArgs.push('--reports=n'); } var rcfile = options.rcfile; delete options.rcfile; if (rcfile) { pylintArgs.push('--rcfile=' + rcfile); } var score = options.score; delete options.score; if (score) { pylintArgs.push('--score=y'); } else { pylintArgs.push('--score=n'); } var errorsOnly = options.errorsOnly; delete options.errorsOnly; if (errorsOnly) { pylintArgs.push('--errors-only'); } var ignore = options.ignore; delete options.ignore; if (ignore) { pylintArgs.push('--ignore=' + ignore); } // Fail if there's any options remaining now for (var prop in options) { if (options.hasOwnProperty(prop)) { grunt.fail.warn("Unknown option to pylint: '" + prop + "'"); } } return pylintArgs; }
javascript
function (options) { var pylintArgs = []; var enable = options.enable; delete options.enable; if (enable) { pylintArgs.push('--enable=' + enable); } var disable = options.disable; delete options.disable; if (disable) { pylintArgs.push('--disable=' + disable); } var messageTemplate = options.messageTemplate; delete options.messageTemplate; if (messageTemplate) { var aliases = { 'short': "line {line}: {msg} ({symbol})", 'msvs': "{path}({line}): [{msg_id}({symbol}){obj}] {msg}", 'parseable': "{path}:{line}: [{msg_id}({symbol}), {obj}] {msg}", }; if (aliases[messageTemplate] !== undefined) { pylintArgs.push('--msg-template="' + aliases[messageTemplate] + '"'); } else { pylintArgs.push('--msg-template="' + messageTemplate + '"'); } } var outputFormat = options.outputFormat; delete options.outputFormat; if (outputFormat) { pylintArgs.push('--output-format=' + outputFormat); } var report = options.report; delete options.report; // Make compatible with --reports as well if (options.reports) { report = options.reports; delete options.reports; } if (report) { pylintArgs.push('--reports=y'); } else { pylintArgs.push('--reports=n'); } var rcfile = options.rcfile; delete options.rcfile; if (rcfile) { pylintArgs.push('--rcfile=' + rcfile); } var score = options.score; delete options.score; if (score) { pylintArgs.push('--score=y'); } else { pylintArgs.push('--score=n'); } var errorsOnly = options.errorsOnly; delete options.errorsOnly; if (errorsOnly) { pylintArgs.push('--errors-only'); } var ignore = options.ignore; delete options.ignore; if (ignore) { pylintArgs.push('--ignore=' + ignore); } // Fail if there's any options remaining now for (var prop in options) { if (options.hasOwnProperty(prop)) { grunt.fail.warn("Unknown option to pylint: '" + prop + "'"); } } return pylintArgs; }
[ "function", "(", "options", ")", "{", "var", "pylintArgs", "=", "[", "]", ";", "var", "enable", "=", "options", ".", "enable", ";", "delete", "options", ".", "enable", ";", "if", "(", "enable", ")", "{", "pylintArgs", ".", "push", "(", "'--enable='", "+", "enable", ")", ";", "}", "var", "disable", "=", "options", ".", "disable", ";", "delete", "options", ".", "disable", ";", "if", "(", "disable", ")", "{", "pylintArgs", ".", "push", "(", "'--disable='", "+", "disable", ")", ";", "}", "var", "messageTemplate", "=", "options", ".", "messageTemplate", ";", "delete", "options", ".", "messageTemplate", ";", "if", "(", "messageTemplate", ")", "{", "var", "aliases", "=", "{", "'short'", ":", "\"line {line}: {msg} ({symbol})\"", ",", "'msvs'", ":", "\"{path}({line}): [{msg_id}({symbol}){obj}] {msg}\"", ",", "'parseable'", ":", "\"{path}:{line}: [{msg_id}({symbol}), {obj}] {msg}\"", ",", "}", ";", "if", "(", "aliases", "[", "messageTemplate", "]", "!==", "undefined", ")", "{", "pylintArgs", ".", "push", "(", "'--msg-template=\"'", "+", "aliases", "[", "messageTemplate", "]", "+", "'\"'", ")", ";", "}", "else", "{", "pylintArgs", ".", "push", "(", "'--msg-template=\"'", "+", "messageTemplate", "+", "'\"'", ")", ";", "}", "}", "var", "outputFormat", "=", "options", ".", "outputFormat", ";", "delete", "options", ".", "outputFormat", ";", "if", "(", "outputFormat", ")", "{", "pylintArgs", ".", "push", "(", "'--output-format='", "+", "outputFormat", ")", ";", "}", "var", "report", "=", "options", ".", "report", ";", "delete", "options", ".", "report", ";", "if", "(", "options", ".", "reports", ")", "{", "report", "=", "options", ".", "reports", ";", "delete", "options", ".", "reports", ";", "}", "if", "(", "report", ")", "{", "pylintArgs", ".", "push", "(", "'--reports=y'", ")", ";", "}", "else", "{", "pylintArgs", ".", "push", "(", "'--reports=n'", ")", ";", "}", "var", "rcfile", "=", "options", ".", "rcfile", ";", "delete", "options", ".", "rcfile", ";", "if", "(", "rcfile", ")", "{", "pylintArgs", ".", "push", "(", "'--rcfile='", "+", "rcfile", ")", ";", "}", "var", "score", "=", "options", ".", "score", ";", "delete", "options", ".", "score", ";", "if", "(", "score", ")", "{", "pylintArgs", ".", "push", "(", "'--score=y'", ")", ";", "}", "else", "{", "pylintArgs", ".", "push", "(", "'--score=n'", ")", ";", "}", "var", "errorsOnly", "=", "options", ".", "errorsOnly", ";", "delete", "options", ".", "errorsOnly", ";", "if", "(", "errorsOnly", ")", "{", "pylintArgs", ".", "push", "(", "'--errors-only'", ")", ";", "}", "var", "ignore", "=", "options", ".", "ignore", ";", "delete", "options", ".", "ignore", ";", "if", "(", "ignore", ")", "{", "pylintArgs", ".", "push", "(", "'--ignore='", "+", "ignore", ")", ";", "}", "for", "(", "var", "prop", "in", "options", ")", "{", "if", "(", "options", ".", "hasOwnProperty", "(", "prop", ")", ")", "{", "grunt", ".", "fail", ".", "warn", "(", "\"Unknown option to pylint: '\"", "+", "prop", "+", "\"'\"", ")", ";", "}", "}", "return", "pylintArgs", ";", "}" ]
Build the argument list sent to pylint from the options object
[ "Build", "the", "argument", "list", "sent", "to", "pylint", "from", "the", "options", "object" ]
1911144b76b144c991e721c794640c06101a8bf1
https://github.com/thusoy/grunt-pylint/blob/1911144b76b144c991e721c794640c06101a8bf1/tasks/pylint.js#L60-L153
train
ctco/rosemary-ui
src/Eventplanner/Selection.js
normalizeDistance
function normalizeDistance(distance = 0) { if (typeof distance !== 'object') distance = { top: distance, left: distance, right: distance, bottom: distance }; return distance; }
javascript
function normalizeDistance(distance = 0) { if (typeof distance !== 'object') distance = { top: distance, left: distance, right: distance, bottom: distance }; return distance; }
[ "function", "normalizeDistance", "(", "distance", "=", "0", ")", "{", "if", "(", "typeof", "distance", "!==", "'object'", ")", "distance", "=", "{", "top", ":", "distance", ",", "left", ":", "distance", ",", "right", ":", "distance", ",", "bottom", ":", "distance", "}", ";", "return", "distance", ";", "}" ]
Resolve the disance prop from either an Int or an Object @return {Object}
[ "Resolve", "the", "disance", "prop", "from", "either", "an", "Int", "or", "an", "Object" ]
b9b91f5a23bd5e832563fbca93da2d271c3720bb
https://github.com/ctco/rosemary-ui/blob/b9b91f5a23bd5e832563fbca93da2d271c3720bb/src/Eventplanner/Selection.js#L196-L200
train
opendigitaleducation/sijil.js
docs/libs/typescript.js
mark
function mark(markName) { if (enabled) { marks[markName] = ts.timestamp(); counts[markName] = (counts[markName] || 0) + 1; profilerEvent(markName); } }
javascript
function mark(markName) { if (enabled) { marks[markName] = ts.timestamp(); counts[markName] = (counts[markName] || 0) + 1; profilerEvent(markName); } }
[ "function", "mark", "(", "markName", ")", "{", "if", "(", "enabled", ")", "{", "marks", "[", "markName", "]", "=", "ts", ".", "timestamp", "(", ")", ";", "counts", "[", "markName", "]", "=", "(", "counts", "[", "markName", "]", "||", "0", ")", "+", "1", ";", "profilerEvent", "(", "markName", ")", ";", "}", "}" ]
Marks a performance event. @param markName The name of the mark.
[ "Marks", "a", "performance", "event", "." ]
c0cd5250a573689a8bcd9733b958d4215b0ecfa4
https://github.com/opendigitaleducation/sijil.js/blob/c0cd5250a573689a8bcd9733b958d4215b0ecfa4/docs/libs/typescript.js#L935-L941
train
opendigitaleducation/sijil.js
docs/libs/typescript.js
measure
function measure(measureName, startMarkName, endMarkName) { if (enabled) { var end = endMarkName && marks[endMarkName] || ts.timestamp(); var start = startMarkName && marks[startMarkName] || profilerStart; measures[measureName] = (measures[measureName] || 0) + (end - start); } }
javascript
function measure(measureName, startMarkName, endMarkName) { if (enabled) { var end = endMarkName && marks[endMarkName] || ts.timestamp(); var start = startMarkName && marks[startMarkName] || profilerStart; measures[measureName] = (measures[measureName] || 0) + (end - start); } }
[ "function", "measure", "(", "measureName", ",", "startMarkName", ",", "endMarkName", ")", "{", "if", "(", "enabled", ")", "{", "var", "end", "=", "endMarkName", "&&", "marks", "[", "endMarkName", "]", "||", "ts", ".", "timestamp", "(", ")", ";", "var", "start", "=", "startMarkName", "&&", "marks", "[", "startMarkName", "]", "||", "profilerStart", ";", "measures", "[", "measureName", "]", "=", "(", "measures", "[", "measureName", "]", "||", "0", ")", "+", "(", "end", "-", "start", ")", ";", "}", "}" ]
Adds a performance measurement with the specified name. @param measureName The name of the performance measurement. @param startMarkName The name of the starting mark. If not supplied, the point at which the profiler was enabled is used. @param endMarkName The name of the ending mark. If not supplied, the current timestamp is used.
[ "Adds", "a", "performance", "measurement", "with", "the", "specified", "name", "." ]
c0cd5250a573689a8bcd9733b958d4215b0ecfa4
https://github.com/opendigitaleducation/sijil.js/blob/c0cd5250a573689a8bcd9733b958d4215b0ecfa4/docs/libs/typescript.js#L952-L958
train
opendigitaleducation/sijil.js
docs/libs/typescript.js
find
function find(array, predicate) { for (var i = 0, len = array.length; i < len; i++) { var value = array[i]; if (predicate(value, i)) { return value; } } return undefined; }
javascript
function find(array, predicate) { for (var i = 0, len = array.length; i < len; i++) { var value = array[i]; if (predicate(value, i)) { return value; } } return undefined; }
[ "function", "find", "(", "array", ",", "predicate", ")", "{", "for", "(", "var", "i", "=", "0", ",", "len", "=", "array", ".", "length", ";", "i", "<", "len", ";", "i", "++", ")", "{", "var", "value", "=", "array", "[", "i", "]", ";", "if", "(", "predicate", "(", "value", ",", "i", ")", ")", "{", "return", "value", ";", "}", "}", "return", "undefined", ";", "}" ]
Works like Array.prototype.find, returning `undefined` if no element satisfying the predicate is found.
[ "Works", "like", "Array", ".", "prototype", ".", "find", "returning", "undefined", "if", "no", "element", "satisfying", "the", "predicate", "is", "found", "." ]
c0cd5250a573689a8bcd9733b958d4215b0ecfa4
https://github.com/opendigitaleducation/sijil.js/blob/c0cd5250a573689a8bcd9733b958d4215b0ecfa4/docs/libs/typescript.js#L1120-L1128
train
opendigitaleducation/sijil.js
docs/libs/typescript.js
findMap
function findMap(array, callback) { for (var i = 0, len = array.length; i < len; i++) { var result = callback(array[i], i); if (result) { return result; } } Debug.fail(); }
javascript
function findMap(array, callback) { for (var i = 0, len = array.length; i < len; i++) { var result = callback(array[i], i); if (result) { return result; } } Debug.fail(); }
[ "function", "findMap", "(", "array", ",", "callback", ")", "{", "for", "(", "var", "i", "=", "0", ",", "len", "=", "array", ".", "length", ";", "i", "<", "len", ";", "i", "++", ")", "{", "var", "result", "=", "callback", "(", "array", "[", "i", "]", ",", "i", ")", ";", "if", "(", "result", ")", "{", "return", "result", ";", "}", "}", "Debug", ".", "fail", "(", ")", ";", "}" ]
Returns the first truthy result of `callback`, or else fails. This is like `forEach`, but never returns undefined.
[ "Returns", "the", "first", "truthy", "result", "of", "callback", "or", "else", "fails", ".", "This", "is", "like", "forEach", "but", "never", "returns", "undefined", "." ]
c0cd5250a573689a8bcd9733b958d4215b0ecfa4
https://github.com/opendigitaleducation/sijil.js/blob/c0cd5250a573689a8bcd9733b958d4215b0ecfa4/docs/libs/typescript.js#L1134-L1142
train
opendigitaleducation/sijil.js
docs/libs/typescript.js
filter
function filter(array, f) { if (array) { var len = array.length; var i = 0; while (i < len && f(array[i])) i++; if (i < len) { var result = array.slice(0, i); i++; while (i < len) { var item = array[i]; if (f(item)) { result.push(item); } i++; } return result; } } return array; }
javascript
function filter(array, f) { if (array) { var len = array.length; var i = 0; while (i < len && f(array[i])) i++; if (i < len) { var result = array.slice(0, i); i++; while (i < len) { var item = array[i]; if (f(item)) { result.push(item); } i++; } return result; } } return array; }
[ "function", "filter", "(", "array", ",", "f", ")", "{", "if", "(", "array", ")", "{", "var", "len", "=", "array", ".", "length", ";", "var", "i", "=", "0", ";", "while", "(", "i", "<", "len", "&&", "f", "(", "array", "[", "i", "]", ")", ")", "i", "++", ";", "if", "(", "i", "<", "len", ")", "{", "var", "result", "=", "array", ".", "slice", "(", "0", ",", "i", ")", ";", "i", "++", ";", "while", "(", "i", "<", "len", ")", "{", "var", "item", "=", "array", "[", "i", "]", ";", "if", "(", "f", "(", "item", ")", ")", "{", "result", ".", "push", "(", "item", ")", ";", "}", "i", "++", ";", "}", "return", "result", ";", "}", "}", "return", "array", ";", "}" ]
Filters an array by a predicate function. Returns the same array instance if the predicate is true for all elements, otherwise returns a new array instance containing the filtered subset.
[ "Filters", "an", "array", "by", "a", "predicate", "function", ".", "Returns", "the", "same", "array", "instance", "if", "the", "predicate", "is", "true", "for", "all", "elements", "otherwise", "returns", "a", "new", "array", "instance", "containing", "the", "filtered", "subset", "." ]
c0cd5250a573689a8bcd9733b958d4215b0ecfa4
https://github.com/opendigitaleducation/sijil.js/blob/c0cd5250a573689a8bcd9733b958d4215b0ecfa4/docs/libs/typescript.js#L1193-L1213
train
opendigitaleducation/sijil.js
docs/libs/typescript.js
getOwnKeys
function getOwnKeys(map) { var keys = []; for (var key in map) if (hasOwnProperty.call(map, key)) { keys.push(key); } return keys; }
javascript
function getOwnKeys(map) { var keys = []; for (var key in map) if (hasOwnProperty.call(map, key)) { keys.push(key); } return keys; }
[ "function", "getOwnKeys", "(", "map", ")", "{", "var", "keys", "=", "[", "]", ";", "for", "(", "var", "key", "in", "map", ")", "if", "(", "hasOwnProperty", ".", "call", "(", "map", ",", "key", ")", ")", "{", "keys", ".", "push", "(", "key", ")", ";", "}", "return", "keys", ";", "}" ]
Gets the owned, enumerable property keys of a map-like. NOTE: This is intended for use with MapLike<T> objects. For Map<T> objects, use Object.keys instead as it offers better performance. @param map A map-like.
[ "Gets", "the", "owned", "enumerable", "property", "keys", "of", "a", "map", "-", "like", "." ]
c0cd5250a573689a8bcd9733b958d4215b0ecfa4
https://github.com/opendigitaleducation/sijil.js/blob/c0cd5250a573689a8bcd9733b958d4215b0ecfa4/docs/libs/typescript.js#L1432-L1439
train
opendigitaleducation/sijil.js
docs/libs/typescript.js
reduceProperties
function reduceProperties(map, callback, initial) { var result = initial; for (var key in map) { result = callback(result, map[key], String(key)); } return result; }
javascript
function reduceProperties(map, callback, initial) { var result = initial; for (var key in map) { result = callback(result, map[key], String(key)); } return result; }
[ "function", "reduceProperties", "(", "map", ",", "callback", ",", "initial", ")", "{", "var", "result", "=", "initial", ";", "for", "(", "var", "key", "in", "map", ")", "{", "result", "=", "callback", "(", "result", ",", "map", "[", "key", "]", ",", "String", "(", "key", ")", ")", ";", "}", "return", "result", ";", "}" ]
Reduce the properties of a map. NOTE: This is intended for use with Map<T> objects. For MapLike<T> objects, use reduceOwnProperties instead as it offers better runtime safety. @param map The map to reduce @param callback An aggregation function that is called for each entry in the map @param initial The initial value for the reduction.
[ "Reduce", "the", "properties", "of", "a", "map", "." ]
c0cd5250a573689a8bcd9733b958d4215b0ecfa4
https://github.com/opendigitaleducation/sijil.js/blob/c0cd5250a573689a8bcd9733b958d4215b0ecfa4/docs/libs/typescript.js#L1492-L1498
train
opendigitaleducation/sijil.js
docs/libs/typescript.js
equalOwnProperties
function equalOwnProperties(left, right, equalityComparer) { if (left === right) return true; if (!left || !right) return false; for (var key in left) if (hasOwnProperty.call(left, key)) { if (!hasOwnProperty.call(right, key) === undefined) return false; if (equalityComparer ? !equalityComparer(left[key], right[key]) : left[key] !== right[key]) return false; } for (var key in right) if (hasOwnProperty.call(right, key)) { if (!hasOwnProperty.call(left, key)) return false; } return true; }
javascript
function equalOwnProperties(left, right, equalityComparer) { if (left === right) return true; if (!left || !right) return false; for (var key in left) if (hasOwnProperty.call(left, key)) { if (!hasOwnProperty.call(right, key) === undefined) return false; if (equalityComparer ? !equalityComparer(left[key], right[key]) : left[key] !== right[key]) return false; } for (var key in right) if (hasOwnProperty.call(right, key)) { if (!hasOwnProperty.call(left, key)) return false; } return true; }
[ "function", "equalOwnProperties", "(", "left", ",", "right", ",", "equalityComparer", ")", "{", "if", "(", "left", "===", "right", ")", "return", "true", ";", "if", "(", "!", "left", "||", "!", "right", ")", "return", "false", ";", "for", "(", "var", "key", "in", "left", ")", "if", "(", "hasOwnProperty", ".", "call", "(", "left", ",", "key", ")", ")", "{", "if", "(", "!", "hasOwnProperty", ".", "call", "(", "right", ",", "key", ")", "===", "undefined", ")", "return", "false", ";", "if", "(", "equalityComparer", "?", "!", "equalityComparer", "(", "left", "[", "key", "]", ",", "right", "[", "key", "]", ")", ":", "left", "[", "key", "]", "!==", "right", "[", "key", "]", ")", "return", "false", ";", "}", "for", "(", "var", "key", "in", "right", ")", "if", "(", "hasOwnProperty", ".", "call", "(", "right", ",", "key", ")", ")", "{", "if", "(", "!", "hasOwnProperty", ".", "call", "(", "left", ",", "key", ")", ")", "return", "false", ";", "}", "return", "true", ";", "}" ]
Performs a shallow equality comparison of the contents of two map-likes. @param left A map-like whose properties should be compared. @param right A map-like whose properties should be compared.
[ "Performs", "a", "shallow", "equality", "comparison", "of", "the", "contents", "of", "two", "map", "-", "likes", "." ]
c0cd5250a573689a8bcd9733b958d4215b0ecfa4
https://github.com/opendigitaleducation/sijil.js/blob/c0cd5250a573689a8bcd9733b958d4215b0ecfa4/docs/libs/typescript.js#L1525-L1543
train
opendigitaleducation/sijil.js
docs/libs/typescript.js
removeTrailingDirectorySeparator
function removeTrailingDirectorySeparator(path) { if (path.charAt(path.length - 1) === ts.directorySeparator) { return path.substr(0, path.length - 1); } return path; }
javascript
function removeTrailingDirectorySeparator(path) { if (path.charAt(path.length - 1) === ts.directorySeparator) { return path.substr(0, path.length - 1); } return path; }
[ "function", "removeTrailingDirectorySeparator", "(", "path", ")", "{", "if", "(", "path", ".", "charAt", "(", "path", ".", "length", "-", "1", ")", "===", "ts", ".", "directorySeparator", ")", "{", "return", "path", ".", "substr", "(", "0", ",", "path", ".", "length", "-", "1", ")", ";", "}", "return", "path", ";", "}" ]
Removes a trailing directory separator from a path. @param path The path.
[ "Removes", "a", "trailing", "directory", "separator", "from", "a", "path", "." ]
c0cd5250a573689a8bcd9733b958d4215b0ecfa4
https://github.com/opendigitaleducation/sijil.js/blob/c0cd5250a573689a8bcd9733b958d4215b0ecfa4/docs/libs/typescript.js#L1971-L1976
train
opendigitaleducation/sijil.js
docs/libs/typescript.js
ensureTrailingDirectorySeparator
function ensureTrailingDirectorySeparator(path) { if (path.charAt(path.length - 1) !== ts.directorySeparator) { return path + ts.directorySeparator; } return path; }
javascript
function ensureTrailingDirectorySeparator(path) { if (path.charAt(path.length - 1) !== ts.directorySeparator) { return path + ts.directorySeparator; } return path; }
[ "function", "ensureTrailingDirectorySeparator", "(", "path", ")", "{", "if", "(", "path", ".", "charAt", "(", "path", ".", "length", "-", "1", ")", "!==", "ts", ".", "directorySeparator", ")", "{", "return", "path", "+", "ts", ".", "directorySeparator", ";", "}", "return", "path", ";", "}" ]
Adds a trailing directory separator to a path, if it does not already have one. @param path The path.
[ "Adds", "a", "trailing", "directory", "separator", "to", "a", "path", "if", "it", "does", "not", "already", "have", "one", "." ]
c0cd5250a573689a8bcd9733b958d4215b0ecfa4
https://github.com/opendigitaleducation/sijil.js/blob/c0cd5250a573689a8bcd9733b958d4215b0ecfa4/docs/libs/typescript.js#L1982-L1987
train
opendigitaleducation/sijil.js
docs/libs/typescript.js
getBasePaths
function getBasePaths(path, includes, useCaseSensitiveFileNames) { // Storage for our results in the form of literal paths (e.g. the paths as written by the user). var basePaths = [path]; if (includes) { // Storage for literal base paths amongst the include patterns. var includeBasePaths = []; for (var _i = 0, includes_1 = includes; _i < includes_1.length; _i++) { var include = includes_1[_i]; // We also need to check the relative paths by converting them to absolute and normalizing // in case they escape the base path (e.g "..\somedirectory") var absolute = isRootedDiskPath(include) ? include : normalizePath(combinePaths(path, include)); var wildcardOffset = indexOfAnyCharCode(absolute, wildcardCharCodes); var includeBasePath = wildcardOffset < 0 ? removeTrailingDirectorySeparator(getDirectoryPath(absolute)) : absolute.substring(0, absolute.lastIndexOf(ts.directorySeparator, wildcardOffset)); // Append the literal and canonical candidate base paths. includeBasePaths.push(includeBasePath); } // Sort the offsets array using either the literal or canonical path representations. includeBasePaths.sort(useCaseSensitiveFileNames ? compareStrings : compareStringsCaseInsensitive); // Iterate over each include base path and include unique base paths that are not a // subpath of an existing base path include: for (var i = 0; i < includeBasePaths.length; i++) { var includeBasePath = includeBasePaths[i]; for (var j = 0; j < basePaths.length; j++) { if (containsPath(basePaths[j], includeBasePath, path, !useCaseSensitiveFileNames)) { continue include; } } basePaths.push(includeBasePath); } } return basePaths; }
javascript
function getBasePaths(path, includes, useCaseSensitiveFileNames) { // Storage for our results in the form of literal paths (e.g. the paths as written by the user). var basePaths = [path]; if (includes) { // Storage for literal base paths amongst the include patterns. var includeBasePaths = []; for (var _i = 0, includes_1 = includes; _i < includes_1.length; _i++) { var include = includes_1[_i]; // We also need to check the relative paths by converting them to absolute and normalizing // in case they escape the base path (e.g "..\somedirectory") var absolute = isRootedDiskPath(include) ? include : normalizePath(combinePaths(path, include)); var wildcardOffset = indexOfAnyCharCode(absolute, wildcardCharCodes); var includeBasePath = wildcardOffset < 0 ? removeTrailingDirectorySeparator(getDirectoryPath(absolute)) : absolute.substring(0, absolute.lastIndexOf(ts.directorySeparator, wildcardOffset)); // Append the literal and canonical candidate base paths. includeBasePaths.push(includeBasePath); } // Sort the offsets array using either the literal or canonical path representations. includeBasePaths.sort(useCaseSensitiveFileNames ? compareStrings : compareStringsCaseInsensitive); // Iterate over each include base path and include unique base paths that are not a // subpath of an existing base path include: for (var i = 0; i < includeBasePaths.length; i++) { var includeBasePath = includeBasePaths[i]; for (var j = 0; j < basePaths.length; j++) { if (containsPath(basePaths[j], includeBasePath, path, !useCaseSensitiveFileNames)) { continue include; } } basePaths.push(includeBasePath); } } return basePaths; }
[ "function", "getBasePaths", "(", "path", ",", "includes", ",", "useCaseSensitiveFileNames", ")", "{", "var", "basePaths", "=", "[", "path", "]", ";", "if", "(", "includes", ")", "{", "var", "includeBasePaths", "=", "[", "]", ";", "for", "(", "var", "_i", "=", "0", ",", "includes_1", "=", "includes", ";", "_i", "<", "includes_1", ".", "length", ";", "_i", "++", ")", "{", "var", "include", "=", "includes_1", "[", "_i", "]", ";", "var", "absolute", "=", "isRootedDiskPath", "(", "include", ")", "?", "include", ":", "normalizePath", "(", "combinePaths", "(", "path", ",", "include", ")", ")", ";", "var", "wildcardOffset", "=", "indexOfAnyCharCode", "(", "absolute", ",", "wildcardCharCodes", ")", ";", "var", "includeBasePath", "=", "wildcardOffset", "<", "0", "?", "removeTrailingDirectorySeparator", "(", "getDirectoryPath", "(", "absolute", ")", ")", ":", "absolute", ".", "substring", "(", "0", ",", "absolute", ".", "lastIndexOf", "(", "ts", ".", "directorySeparator", ",", "wildcardOffset", ")", ")", ";", "includeBasePaths", ".", "push", "(", "includeBasePath", ")", ";", "}", "includeBasePaths", ".", "sort", "(", "useCaseSensitiveFileNames", "?", "compareStrings", ":", "compareStringsCaseInsensitive", ")", ";", "include", ":", "for", "(", "var", "i", "=", "0", ";", "i", "<", "includeBasePaths", ".", "length", ";", "i", "++", ")", "{", "var", "includeBasePath", "=", "includeBasePaths", "[", "i", "]", ";", "for", "(", "var", "j", "=", "0", ";", "j", "<", "basePaths", ".", "length", ";", "j", "++", ")", "{", "if", "(", "containsPath", "(", "basePaths", "[", "j", "]", ",", "includeBasePath", ",", "path", ",", "!", "useCaseSensitiveFileNames", ")", ")", "{", "continue", "include", ";", "}", "}", "basePaths", ".", "push", "(", "includeBasePath", ")", ";", "}", "}", "return", "basePaths", ";", "}" ]
Computes the unique non-wildcard base paths amongst the provided include patterns.
[ "Computes", "the", "unique", "non", "-", "wildcard", "base", "paths", "amongst", "the", "provided", "include", "patterns", "." ]
c0cd5250a573689a8bcd9733b958d4215b0ecfa4
https://github.com/opendigitaleducation/sijil.js/blob/c0cd5250a573689a8bcd9733b958d4215b0ecfa4/docs/libs/typescript.js#L2213-L2246
train
opendigitaleducation/sijil.js
docs/libs/typescript.js
isWhiteSpaceSingleLine
function isWhiteSpaceSingleLine(ch) { // Note: nextLine is in the Zs space, and should be considered to be a whitespace. // It is explicitly not a line-break as it isn't in the exact set specified by EcmaScript. return ch === 32 /* space */ || ch === 9 /* tab */ || ch === 11 /* verticalTab */ || ch === 12 /* formFeed */ || ch === 160 /* nonBreakingSpace */ || ch === 133 /* nextLine */ || ch === 5760 /* ogham */ || ch >= 8192 /* enQuad */ && ch <= 8203 /* zeroWidthSpace */ || ch === 8239 /* narrowNoBreakSpace */ || ch === 8287 /* mathematicalSpace */ || ch === 12288 /* ideographicSpace */ || ch === 65279 /* byteOrderMark */; }
javascript
function isWhiteSpaceSingleLine(ch) { // Note: nextLine is in the Zs space, and should be considered to be a whitespace. // It is explicitly not a line-break as it isn't in the exact set specified by EcmaScript. return ch === 32 /* space */ || ch === 9 /* tab */ || ch === 11 /* verticalTab */ || ch === 12 /* formFeed */ || ch === 160 /* nonBreakingSpace */ || ch === 133 /* nextLine */ || ch === 5760 /* ogham */ || ch >= 8192 /* enQuad */ && ch <= 8203 /* zeroWidthSpace */ || ch === 8239 /* narrowNoBreakSpace */ || ch === 8287 /* mathematicalSpace */ || ch === 12288 /* ideographicSpace */ || ch === 65279 /* byteOrderMark */; }
[ "function", "isWhiteSpaceSingleLine", "(", "ch", ")", "{", "return", "ch", "===", "32", "||", "ch", "===", "9", "||", "ch", "===", "11", "||", "ch", "===", "12", "||", "ch", "===", "160", "||", "ch", "===", "133", "||", "ch", "===", "5760", "||", "ch", ">=", "8192", "&&", "ch", "<=", "8203", "||", "ch", "===", "8239", "||", "ch", "===", "8287", "||", "ch", "===", "12288", "||", "ch", "===", "65279", ";", "}" ]
Does not include line breaks. For that, see isWhiteSpaceLike.
[ "Does", "not", "include", "line", "breaks", ".", "For", "that", "see", "isWhiteSpaceLike", "." ]
c0cd5250a573689a8bcd9733b958d4215b0ecfa4
https://github.com/opendigitaleducation/sijil.js/blob/c0cd5250a573689a8bcd9733b958d4215b0ecfa4/docs/libs/typescript.js#L4098-L4113
train
opendigitaleducation/sijil.js
docs/libs/typescript.js
isRequireCall
function isRequireCall(expression, checkArgumentIsStringLiteral) { // of the form 'require("name")' var isRequire = expression.kind === 174 /* CallExpression */ && expression.expression.kind === 69 /* Identifier */ && expression.expression.text === "require" && expression.arguments.length === 1; return isRequire && (!checkArgumentIsStringLiteral || expression.arguments[0].kind === 9 /* StringLiteral */); }
javascript
function isRequireCall(expression, checkArgumentIsStringLiteral) { // of the form 'require("name")' var isRequire = expression.kind === 174 /* CallExpression */ && expression.expression.kind === 69 /* Identifier */ && expression.expression.text === "require" && expression.arguments.length === 1; return isRequire && (!checkArgumentIsStringLiteral || expression.arguments[0].kind === 9 /* StringLiteral */); }
[ "function", "isRequireCall", "(", "expression", ",", "checkArgumentIsStringLiteral", ")", "{", "var", "isRequire", "=", "expression", ".", "kind", "===", "174", "&&", "expression", ".", "expression", ".", "kind", "===", "69", "&&", "expression", ".", "expression", ".", "text", "===", "\"require\"", "&&", "expression", ".", "arguments", ".", "length", "===", "1", ";", "return", "isRequire", "&&", "(", "!", "checkArgumentIsStringLiteral", "||", "expression", ".", "arguments", "[", "0", "]", ".", "kind", "===", "9", ")", ";", "}" ]
Returns true if the node is a CallExpression to the identifier 'require' with exactly one argument. This function does not test if the node is in a JavaScript file or not.
[ "Returns", "true", "if", "the", "node", "is", "a", "CallExpression", "to", "the", "identifier", "require", "with", "exactly", "one", "argument", ".", "This", "function", "does", "not", "test", "if", "the", "node", "is", "in", "a", "JavaScript", "file", "or", "not", "." ]
c0cd5250a573689a8bcd9733b958d4215b0ecfa4
https://github.com/opendigitaleducation/sijil.js/blob/c0cd5250a573689a8bcd9733b958d4215b0ecfa4/docs/libs/typescript.js#L6597-L6604
train
opendigitaleducation/sijil.js
docs/libs/typescript.js
isDeclarationOfFunctionExpression
function isDeclarationOfFunctionExpression(s) { if (s.valueDeclaration && s.valueDeclaration.kind === 218 /* VariableDeclaration */) { var declaration = s.valueDeclaration; return declaration.initializer && declaration.initializer.kind === 179 /* FunctionExpression */; } return false; }
javascript
function isDeclarationOfFunctionExpression(s) { if (s.valueDeclaration && s.valueDeclaration.kind === 218 /* VariableDeclaration */) { var declaration = s.valueDeclaration; return declaration.initializer && declaration.initializer.kind === 179 /* FunctionExpression */; } return false; }
[ "function", "isDeclarationOfFunctionExpression", "(", "s", ")", "{", "if", "(", "s", ".", "valueDeclaration", "&&", "s", ".", "valueDeclaration", ".", "kind", "===", "218", ")", "{", "var", "declaration", "=", "s", ".", "valueDeclaration", ";", "return", "declaration", ".", "initializer", "&&", "declaration", ".", "initializer", ".", "kind", "===", "179", ";", "}", "return", "false", ";", "}" ]
Returns true if the node is a variable declaration whose initializer is a function expression. This function does not test if the node is in a JavaScript file or not.
[ "Returns", "true", "if", "the", "node", "is", "a", "variable", "declaration", "whose", "initializer", "is", "a", "function", "expression", ".", "This", "function", "does", "not", "test", "if", "the", "node", "is", "in", "a", "JavaScript", "file", "or", "not", "." ]
c0cd5250a573689a8bcd9733b958d4215b0ecfa4
https://github.com/opendigitaleducation/sijil.js/blob/c0cd5250a573689a8bcd9733b958d4215b0ecfa4/docs/libs/typescript.js#L6614-L6620
train
opendigitaleducation/sijil.js
docs/libs/typescript.js
cloneNode
function cloneNode(node, location, flags, parent) { // We don't use "clone" from core.ts here, as we need to preserve the prototype chain of // the original node. We also need to exclude specific properties and only include own- // properties (to skip members already defined on the shared prototype). var clone = location !== undefined ? ts.createNode(node.kind, location.pos, location.end) : createSynthesizedNode(node.kind); for (var key in node) { if (clone.hasOwnProperty(key) || !node.hasOwnProperty(key)) { continue; } clone[key] = node[key]; } if (flags !== undefined) { clone.flags = flags; } if (parent !== undefined) { clone.parent = parent; } return clone; }
javascript
function cloneNode(node, location, flags, parent) { // We don't use "clone" from core.ts here, as we need to preserve the prototype chain of // the original node. We also need to exclude specific properties and only include own- // properties (to skip members already defined on the shared prototype). var clone = location !== undefined ? ts.createNode(node.kind, location.pos, location.end) : createSynthesizedNode(node.kind); for (var key in node) { if (clone.hasOwnProperty(key) || !node.hasOwnProperty(key)) { continue; } clone[key] = node[key]; } if (flags !== undefined) { clone.flags = flags; } if (parent !== undefined) { clone.parent = parent; } return clone; }
[ "function", "cloneNode", "(", "node", ",", "location", ",", "flags", ",", "parent", ")", "{", "var", "clone", "=", "location", "!==", "undefined", "?", "ts", ".", "createNode", "(", "node", ".", "kind", ",", "location", ".", "pos", ",", "location", ".", "end", ")", ":", "createSynthesizedNode", "(", "node", ".", "kind", ")", ";", "for", "(", "var", "key", "in", "node", ")", "{", "if", "(", "clone", ".", "hasOwnProperty", "(", "key", ")", "||", "!", "node", ".", "hasOwnProperty", "(", "key", ")", ")", "{", "continue", ";", "}", "clone", "[", "key", "]", "=", "node", "[", "key", "]", ";", "}", "if", "(", "flags", "!==", "undefined", ")", "{", "clone", ".", "flags", "=", "flags", ";", "}", "if", "(", "parent", "!==", "undefined", ")", "{", "clone", ".", "parent", "=", "parent", ";", "}", "return", "clone", ";", "}" ]
Creates a shallow, memberwise clone of a node. The "kind", "pos", "end", "flags", and "parent" properties are excluded by default, and can be provided via the "location", "flags", and "parent" parameters. @param node The node to clone. @param location An optional TextRange to use to supply the new position. @param flags The NodeFlags to use for the cloned node. @param parent The parent for the new node.
[ "Creates", "a", "shallow", "memberwise", "clone", "of", "a", "node", ".", "The", "kind", "pos", "end", "flags", "and", "parent", "properties", "are", "excluded", "by", "default", "and", "can", "be", "provided", "via", "the", "location", "flags", "and", "parent", "parameters", "." ]
c0cd5250a573689a8bcd9733b958d4215b0ecfa4
https://github.com/opendigitaleducation/sijil.js/blob/c0cd5250a573689a8bcd9733b958d4215b0ecfa4/docs/libs/typescript.js#L7231-L7251
train
opendigitaleducation/sijil.js
docs/libs/typescript.js
cloneEntityName
function cloneEntityName(node, parent) { var clone = cloneNode(node, node, node.flags, parent); if (isQualifiedName(clone)) { var left = clone.left, right = clone.right; clone.left = cloneEntityName(left, clone); clone.right = cloneNode(right, right, right.flags, parent); } return clone; }
javascript
function cloneEntityName(node, parent) { var clone = cloneNode(node, node, node.flags, parent); if (isQualifiedName(clone)) { var left = clone.left, right = clone.right; clone.left = cloneEntityName(left, clone); clone.right = cloneNode(right, right, right.flags, parent); } return clone; }
[ "function", "cloneEntityName", "(", "node", ",", "parent", ")", "{", "var", "clone", "=", "cloneNode", "(", "node", ",", "node", ",", "node", ".", "flags", ",", "parent", ")", ";", "if", "(", "isQualifiedName", "(", "clone", ")", ")", "{", "var", "left", "=", "clone", ".", "left", ",", "right", "=", "clone", ".", "right", ";", "clone", ".", "left", "=", "cloneEntityName", "(", "left", ",", "clone", ")", ";", "clone", ".", "right", "=", "cloneNode", "(", "right", ",", "right", ",", "right", ".", "flags", ",", "parent", ")", ";", "}", "return", "clone", ";", "}" ]
Creates a deep clone of an EntityName, with new parent pointers. @param node The EntityName to clone. @param parent The parent for the cloned node.
[ "Creates", "a", "deep", "clone", "of", "an", "EntityName", "with", "new", "parent", "pointers", "." ]
c0cd5250a573689a8bcd9733b958d4215b0ecfa4
https://github.com/opendigitaleducation/sijil.js/blob/c0cd5250a573689a8bcd9733b958d4215b0ecfa4/docs/libs/typescript.js#L7258-L7266
train
opendigitaleducation/sijil.js
docs/libs/typescript.js
getExternalModuleNameFromPath
function getExternalModuleNameFromPath(host, fileName) { var getCanonicalFileName = function (f) { return host.getCanonicalFileName(f); }; var dir = ts.toPath(host.getCommonSourceDirectory(), host.getCurrentDirectory(), getCanonicalFileName); var filePath = ts.getNormalizedAbsolutePath(fileName, host.getCurrentDirectory()); var relativePath = ts.getRelativePathToDirectoryOrUrl(dir, filePath, dir, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); return ts.removeFileExtension(relativePath); }
javascript
function getExternalModuleNameFromPath(host, fileName) { var getCanonicalFileName = function (f) { return host.getCanonicalFileName(f); }; var dir = ts.toPath(host.getCommonSourceDirectory(), host.getCurrentDirectory(), getCanonicalFileName); var filePath = ts.getNormalizedAbsolutePath(fileName, host.getCurrentDirectory()); var relativePath = ts.getRelativePathToDirectoryOrUrl(dir, filePath, dir, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); return ts.removeFileExtension(relativePath); }
[ "function", "getExternalModuleNameFromPath", "(", "host", ",", "fileName", ")", "{", "var", "getCanonicalFileName", "=", "function", "(", "f", ")", "{", "return", "host", ".", "getCanonicalFileName", "(", "f", ")", ";", "}", ";", "var", "dir", "=", "ts", ".", "toPath", "(", "host", ".", "getCommonSourceDirectory", "(", ")", ",", "host", ".", "getCurrentDirectory", "(", ")", ",", "getCanonicalFileName", ")", ";", "var", "filePath", "=", "ts", ".", "getNormalizedAbsolutePath", "(", "fileName", ",", "host", ".", "getCurrentDirectory", "(", ")", ")", ";", "var", "relativePath", "=", "ts", ".", "getRelativePathToDirectoryOrUrl", "(", "dir", ",", "filePath", ",", "dir", ",", "getCanonicalFileName", ",", "false", ")", ";", "return", "ts", ".", "removeFileExtension", "(", "relativePath", ")", ";", "}" ]
Resolves a local path to a path which is absolute to the base of the emit
[ "Resolves", "a", "local", "path", "to", "a", "path", "which", "is", "absolute", "to", "the", "base", "of", "the", "emit" ]
c0cd5250a573689a8bcd9733b958d4215b0ecfa4
https://github.com/opendigitaleducation/sijil.js/blob/c0cd5250a573689a8bcd9733b958d4215b0ecfa4/docs/libs/typescript.js#L7496-L7502
train
opendigitaleducation/sijil.js
docs/libs/typescript.js
emitDetachedComments
function emitDetachedComments(text, lineMap, writer, writeComment, node, newLine, removeComments) { var leadingComments; var currentDetachedCommentInfo; if (removeComments) { // removeComments is true, only reserve pinned comment at the top of file // For example: // /*! Pinned Comment */ // // var x = 10; if (node.pos === 0) { leadingComments = ts.filter(ts.getLeadingCommentRanges(text, node.pos), isPinnedComment); } } else { // removeComments is false, just get detached as normal and bypass the process to filter comment leadingComments = ts.getLeadingCommentRanges(text, node.pos); } if (leadingComments) { var detachedComments = []; var lastComment = void 0; for (var _i = 0, leadingComments_1 = leadingComments; _i < leadingComments_1.length; _i++) { var comment = leadingComments_1[_i]; if (lastComment) { var lastCommentLine = getLineOfLocalPositionFromLineMap(lineMap, lastComment.end); var commentLine = getLineOfLocalPositionFromLineMap(lineMap, comment.pos); if (commentLine >= lastCommentLine + 2) { // There was a blank line between the last comment and this comment. This // comment is not part of the copyright comments. Return what we have so // far. break; } } detachedComments.push(comment); lastComment = comment; } if (detachedComments.length) { // All comments look like they could have been part of the copyright header. Make // sure there is at least one blank line between it and the node. If not, it's not // a copyright header. var lastCommentLine = getLineOfLocalPositionFromLineMap(lineMap, ts.lastOrUndefined(detachedComments).end); var nodeLine = getLineOfLocalPositionFromLineMap(lineMap, ts.skipTrivia(text, node.pos)); if (nodeLine >= lastCommentLine + 2) { // Valid detachedComments emitNewLineBeforeLeadingComments(lineMap, writer, node, leadingComments); emitComments(text, lineMap, writer, detachedComments, /*trailingSeparator*/ true, newLine, writeComment); currentDetachedCommentInfo = { nodePos: node.pos, detachedCommentEndPos: ts.lastOrUndefined(detachedComments).end }; } } } return currentDetachedCommentInfo; function isPinnedComment(comment) { return text.charCodeAt(comment.pos + 1) === 42 /* asterisk */ && text.charCodeAt(comment.pos + 2) === 33 /* exclamation */; } }
javascript
function emitDetachedComments(text, lineMap, writer, writeComment, node, newLine, removeComments) { var leadingComments; var currentDetachedCommentInfo; if (removeComments) { // removeComments is true, only reserve pinned comment at the top of file // For example: // /*! Pinned Comment */ // // var x = 10; if (node.pos === 0) { leadingComments = ts.filter(ts.getLeadingCommentRanges(text, node.pos), isPinnedComment); } } else { // removeComments is false, just get detached as normal and bypass the process to filter comment leadingComments = ts.getLeadingCommentRanges(text, node.pos); } if (leadingComments) { var detachedComments = []; var lastComment = void 0; for (var _i = 0, leadingComments_1 = leadingComments; _i < leadingComments_1.length; _i++) { var comment = leadingComments_1[_i]; if (lastComment) { var lastCommentLine = getLineOfLocalPositionFromLineMap(lineMap, lastComment.end); var commentLine = getLineOfLocalPositionFromLineMap(lineMap, comment.pos); if (commentLine >= lastCommentLine + 2) { // There was a blank line between the last comment and this comment. This // comment is not part of the copyright comments. Return what we have so // far. break; } } detachedComments.push(comment); lastComment = comment; } if (detachedComments.length) { // All comments look like they could have been part of the copyright header. Make // sure there is at least one blank line between it and the node. If not, it's not // a copyright header. var lastCommentLine = getLineOfLocalPositionFromLineMap(lineMap, ts.lastOrUndefined(detachedComments).end); var nodeLine = getLineOfLocalPositionFromLineMap(lineMap, ts.skipTrivia(text, node.pos)); if (nodeLine >= lastCommentLine + 2) { // Valid detachedComments emitNewLineBeforeLeadingComments(lineMap, writer, node, leadingComments); emitComments(text, lineMap, writer, detachedComments, /*trailingSeparator*/ true, newLine, writeComment); currentDetachedCommentInfo = { nodePos: node.pos, detachedCommentEndPos: ts.lastOrUndefined(detachedComments).end }; } } } return currentDetachedCommentInfo; function isPinnedComment(comment) { return text.charCodeAt(comment.pos + 1) === 42 /* asterisk */ && text.charCodeAt(comment.pos + 2) === 33 /* exclamation */; } }
[ "function", "emitDetachedComments", "(", "text", ",", "lineMap", ",", "writer", ",", "writeComment", ",", "node", ",", "newLine", ",", "removeComments", ")", "{", "var", "leadingComments", ";", "var", "currentDetachedCommentInfo", ";", "if", "(", "removeComments", ")", "{", "if", "(", "node", ".", "pos", "===", "0", ")", "{", "leadingComments", "=", "ts", ".", "filter", "(", "ts", ".", "getLeadingCommentRanges", "(", "text", ",", "node", ".", "pos", ")", ",", "isPinnedComment", ")", ";", "}", "}", "else", "{", "leadingComments", "=", "ts", ".", "getLeadingCommentRanges", "(", "text", ",", "node", ".", "pos", ")", ";", "}", "if", "(", "leadingComments", ")", "{", "var", "detachedComments", "=", "[", "]", ";", "var", "lastComment", "=", "void", "0", ";", "for", "(", "var", "_i", "=", "0", ",", "leadingComments_1", "=", "leadingComments", ";", "_i", "<", "leadingComments_1", ".", "length", ";", "_i", "++", ")", "{", "var", "comment", "=", "leadingComments_1", "[", "_i", "]", ";", "if", "(", "lastComment", ")", "{", "var", "lastCommentLine", "=", "getLineOfLocalPositionFromLineMap", "(", "lineMap", ",", "lastComment", ".", "end", ")", ";", "var", "commentLine", "=", "getLineOfLocalPositionFromLineMap", "(", "lineMap", ",", "comment", ".", "pos", ")", ";", "if", "(", "commentLine", ">=", "lastCommentLine", "+", "2", ")", "{", "break", ";", "}", "}", "detachedComments", ".", "push", "(", "comment", ")", ";", "lastComment", "=", "comment", ";", "}", "if", "(", "detachedComments", ".", "length", ")", "{", "var", "lastCommentLine", "=", "getLineOfLocalPositionFromLineMap", "(", "lineMap", ",", "ts", ".", "lastOrUndefined", "(", "detachedComments", ")", ".", "end", ")", ";", "var", "nodeLine", "=", "getLineOfLocalPositionFromLineMap", "(", "lineMap", ",", "ts", ".", "skipTrivia", "(", "text", ",", "node", ".", "pos", ")", ")", ";", "if", "(", "nodeLine", ">=", "lastCommentLine", "+", "2", ")", "{", "emitNewLineBeforeLeadingComments", "(", "lineMap", ",", "writer", ",", "node", ",", "leadingComments", ")", ";", "emitComments", "(", "text", ",", "lineMap", ",", "writer", ",", "detachedComments", ",", "true", ",", "newLine", ",", "writeComment", ")", ";", "currentDetachedCommentInfo", "=", "{", "nodePos", ":", "node", ".", "pos", ",", "detachedCommentEndPos", ":", "ts", ".", "lastOrUndefined", "(", "detachedComments", ")", ".", "end", "}", ";", "}", "}", "}", "return", "currentDetachedCommentInfo", ";", "function", "isPinnedComment", "(", "comment", ")", "{", "return", "text", ".", "charCodeAt", "(", "comment", ".", "pos", "+", "1", ")", "===", "42", "&&", "text", ".", "charCodeAt", "(", "comment", ".", "pos", "+", "2", ")", "===", "33", ";", "}", "}" ]
Detached comment is a comment at the top of file or function body that is separated from the next statement by space.
[ "Detached", "comment", "is", "a", "comment", "at", "the", "top", "of", "file", "or", "function", "body", "that", "is", "separated", "from", "the", "next", "statement", "by", "space", "." ]
c0cd5250a573689a8bcd9733b958d4215b0ecfa4
https://github.com/opendigitaleducation/sijil.js/blob/c0cd5250a573689a8bcd9733b958d4215b0ecfa4/docs/libs/typescript.js#L7708-L7762
train
opendigitaleducation/sijil.js
docs/libs/typescript.js
tryExtractTypeScriptExtension
function tryExtractTypeScriptExtension(fileName) { return ts.find(ts.supportedTypescriptExtensionsForExtractExtension, function (extension) { return ts.fileExtensionIs(fileName, extension); }); }
javascript
function tryExtractTypeScriptExtension(fileName) { return ts.find(ts.supportedTypescriptExtensionsForExtractExtension, function (extension) { return ts.fileExtensionIs(fileName, extension); }); }
[ "function", "tryExtractTypeScriptExtension", "(", "fileName", ")", "{", "return", "ts", ".", "find", "(", "ts", ".", "supportedTypescriptExtensionsForExtractExtension", ",", "function", "(", "extension", ")", "{", "return", "ts", ".", "fileExtensionIs", "(", "fileName", ",", "extension", ")", ";", "}", ")", ";", "}" ]
Return ".ts", ".d.ts", or ".tsx", if that is the extension.
[ "Return", ".", "ts", ".", "d", ".", "ts", "or", ".", "tsx", "if", "that", "is", "the", "extension", "." ]
c0cd5250a573689a8bcd9733b958d4215b0ecfa4
https://github.com/opendigitaleducation/sijil.js/blob/c0cd5250a573689a8bcd9733b958d4215b0ecfa4/docs/libs/typescript.js#L7937-L7939
train
opendigitaleducation/sijil.js
docs/libs/typescript.js
convertToBase64
function convertToBase64(input) { var result = ""; var charCodes = getExpandedCharCodes(input); var i = 0; var length = charCodes.length; var byte1, byte2, byte3, byte4; while (i < length) { // Convert every 6-bits in the input 3 character points // into a base64 digit byte1 = charCodes[i] >> 2; byte2 = (charCodes[i] & 3) << 4 | charCodes[i + 1] >> 4; byte3 = (charCodes[i + 1] & 15) << 2 | charCodes[i + 2] >> 6; byte4 = charCodes[i + 2] & 63; // We are out of characters in the input, set the extra // digits to 64 (padding character). if (i + 1 >= length) { byte3 = byte4 = 64; } else if (i + 2 >= length) { byte4 = 64; } // Write to the output result += base64Digits.charAt(byte1) + base64Digits.charAt(byte2) + base64Digits.charAt(byte3) + base64Digits.charAt(byte4); i += 3; } return result; }
javascript
function convertToBase64(input) { var result = ""; var charCodes = getExpandedCharCodes(input); var i = 0; var length = charCodes.length; var byte1, byte2, byte3, byte4; while (i < length) { // Convert every 6-bits in the input 3 character points // into a base64 digit byte1 = charCodes[i] >> 2; byte2 = (charCodes[i] & 3) << 4 | charCodes[i + 1] >> 4; byte3 = (charCodes[i + 1] & 15) << 2 | charCodes[i + 2] >> 6; byte4 = charCodes[i + 2] & 63; // We are out of characters in the input, set the extra // digits to 64 (padding character). if (i + 1 >= length) { byte3 = byte4 = 64; } else if (i + 2 >= length) { byte4 = 64; } // Write to the output result += base64Digits.charAt(byte1) + base64Digits.charAt(byte2) + base64Digits.charAt(byte3) + base64Digits.charAt(byte4); i += 3; } return result; }
[ "function", "convertToBase64", "(", "input", ")", "{", "var", "result", "=", "\"\"", ";", "var", "charCodes", "=", "getExpandedCharCodes", "(", "input", ")", ";", "var", "i", "=", "0", ";", "var", "length", "=", "charCodes", ".", "length", ";", "var", "byte1", ",", "byte2", ",", "byte3", ",", "byte4", ";", "while", "(", "i", "<", "length", ")", "{", "byte1", "=", "charCodes", "[", "i", "]", ">>", "2", ";", "byte2", "=", "(", "charCodes", "[", "i", "]", "&", "3", ")", "<<", "4", "|", "charCodes", "[", "i", "+", "1", "]", ">>", "4", ";", "byte3", "=", "(", "charCodes", "[", "i", "+", "1", "]", "&", "15", ")", "<<", "2", "|", "charCodes", "[", "i", "+", "2", "]", ">>", "6", ";", "byte4", "=", "charCodes", "[", "i", "+", "2", "]", "&", "63", ";", "if", "(", "i", "+", "1", ">=", "length", ")", "{", "byte3", "=", "byte4", "=", "64", ";", "}", "else", "if", "(", "i", "+", "2", ">=", "length", ")", "{", "byte4", "=", "64", ";", "}", "result", "+=", "base64Digits", ".", "charAt", "(", "byte1", ")", "+", "base64Digits", ".", "charAt", "(", "byte2", ")", "+", "base64Digits", ".", "charAt", "(", "byte3", ")", "+", "base64Digits", ".", "charAt", "(", "byte4", ")", ";", "i", "+=", "3", ";", "}", "return", "result", ";", "}" ]
Converts a string to a base-64 encoded ASCII string.
[ "Converts", "a", "string", "to", "a", "base", "-", "64", "encoded", "ASCII", "string", "." ]
c0cd5250a573689a8bcd9733b958d4215b0ecfa4
https://github.com/opendigitaleducation/sijil.js/blob/c0cd5250a573689a8bcd9733b958d4215b0ecfa4/docs/libs/typescript.js#L8020-L8046
train
opendigitaleducation/sijil.js
docs/libs/typescript.js
collapseTextChangeRangesAcrossMultipleVersions
function collapseTextChangeRangesAcrossMultipleVersions(changes) { if (changes.length === 0) { return ts.unchangedTextChangeRange; } if (changes.length === 1) { return changes[0]; } // We change from talking about { { oldStart, oldLength }, newLength } to { oldStart, oldEnd, newEnd } // as it makes things much easier to reason about. var change0 = changes[0]; var oldStartN = change0.span.start; var oldEndN = textSpanEnd(change0.span); var newEndN = oldStartN + change0.newLength; for (var i = 1; i < changes.length; i++) { var nextChange = changes[i]; // Consider the following case: // i.e. two edits. The first represents the text change range { { 10, 50 }, 30 }. i.e. The span starting // at 10, with length 50 is reduced to length 30. The second represents the text change range { { 30, 30 }, 40 }. // i.e. the span starting at 30 with length 30 is increased to length 40. // // 0 10 20 30 40 50 60 70 80 90 100 // ------------------------------------------------------------------------------------------------------- // | / // | /---- // T1 | /---- // | /---- // | /---- // ------------------------------------------------------------------------------------------------------- // | \ // | \ // T2 | \ // | \ // | \ // ------------------------------------------------------------------------------------------------------- // // Merging these turns out to not be too difficult. First, determining the new start of the change is trivial // it's just the min of the old and new starts. i.e.: // // 0 10 20 30 40 50 60 70 80 90 100 // ------------------------------------------------------------*------------------------------------------ // | / // | /---- // T1 | /---- // | /---- // | /---- // ----------------------------------------$-------------------$------------------------------------------ // . | \ // . | \ // T2 . | \ // . | \ // . | \ // ----------------------------------------------------------------------*-------------------------------- // // (Note the dots represent the newly inferred start. // Determining the new and old end is also pretty simple. Basically it boils down to paying attention to the // absolute positions at the asterisks, and the relative change between the dollar signs. Basically, we see // which if the two $'s precedes the other, and we move that one forward until they line up. in this case that // means: // // 0 10 20 30 40 50 60 70 80 90 100 // --------------------------------------------------------------------------------*---------------------- // | / // | /---- // T1 | /---- // | /---- // | /---- // ------------------------------------------------------------$------------------------------------------ // . | \ // . | \ // T2 . | \ // . | \ // . | \ // ----------------------------------------------------------------------*-------------------------------- // // In other words (in this case), we're recognizing that the second edit happened after where the first edit // ended with a delta of 20 characters (60 - 40). Thus, if we go back in time to where the first edit started // that's the same as if we started at char 80 instead of 60. // // As it so happens, the same logic applies if the second edit precedes the first edit. In that case rather // than pushing the first edit forward to match the second, we'll push the second edit forward to match the // first. // // In this case that means we have { oldStart: 10, oldEnd: 80, newEnd: 70 } or, in TextChangeRange // semantics: { { start: 10, length: 70 }, newLength: 60 } // // The math then works out as follows. // If we have { oldStart1, oldEnd1, newEnd1 } and { oldStart2, oldEnd2, newEnd2 } then we can compute the // final result like so: // // { // oldStart3: Min(oldStart1, oldStart2), // oldEnd3 : Max(oldEnd1, oldEnd1 + (oldEnd2 - newEnd1)), // newEnd3 : Max(newEnd2, newEnd2 + (newEnd1 - oldEnd2)) // } var oldStart1 = oldStartN; var oldEnd1 = oldEndN; var newEnd1 = newEndN; var oldStart2 = nextChange.span.start; var oldEnd2 = textSpanEnd(nextChange.span); var newEnd2 = oldStart2 + nextChange.newLength; oldStartN = Math.min(oldStart1, oldStart2); oldEndN = Math.max(oldEnd1, oldEnd1 + (oldEnd2 - newEnd1)); newEndN = Math.max(newEnd2, newEnd2 + (newEnd1 - oldEnd2)); } return createTextChangeRange(createTextSpanFromBounds(oldStartN, oldEndN), /*newLength:*/ newEndN - oldStartN); }
javascript
function collapseTextChangeRangesAcrossMultipleVersions(changes) { if (changes.length === 0) { return ts.unchangedTextChangeRange; } if (changes.length === 1) { return changes[0]; } // We change from talking about { { oldStart, oldLength }, newLength } to { oldStart, oldEnd, newEnd } // as it makes things much easier to reason about. var change0 = changes[0]; var oldStartN = change0.span.start; var oldEndN = textSpanEnd(change0.span); var newEndN = oldStartN + change0.newLength; for (var i = 1; i < changes.length; i++) { var nextChange = changes[i]; // Consider the following case: // i.e. two edits. The first represents the text change range { { 10, 50 }, 30 }. i.e. The span starting // at 10, with length 50 is reduced to length 30. The second represents the text change range { { 30, 30 }, 40 }. // i.e. the span starting at 30 with length 30 is increased to length 40. // // 0 10 20 30 40 50 60 70 80 90 100 // ------------------------------------------------------------------------------------------------------- // | / // | /---- // T1 | /---- // | /---- // | /---- // ------------------------------------------------------------------------------------------------------- // | \ // | \ // T2 | \ // | \ // | \ // ------------------------------------------------------------------------------------------------------- // // Merging these turns out to not be too difficult. First, determining the new start of the change is trivial // it's just the min of the old and new starts. i.e.: // // 0 10 20 30 40 50 60 70 80 90 100 // ------------------------------------------------------------*------------------------------------------ // | / // | /---- // T1 | /---- // | /---- // | /---- // ----------------------------------------$-------------------$------------------------------------------ // . | \ // . | \ // T2 . | \ // . | \ // . | \ // ----------------------------------------------------------------------*-------------------------------- // // (Note the dots represent the newly inferred start. // Determining the new and old end is also pretty simple. Basically it boils down to paying attention to the // absolute positions at the asterisks, and the relative change between the dollar signs. Basically, we see // which if the two $'s precedes the other, and we move that one forward until they line up. in this case that // means: // // 0 10 20 30 40 50 60 70 80 90 100 // --------------------------------------------------------------------------------*---------------------- // | / // | /---- // T1 | /---- // | /---- // | /---- // ------------------------------------------------------------$------------------------------------------ // . | \ // . | \ // T2 . | \ // . | \ // . | \ // ----------------------------------------------------------------------*-------------------------------- // // In other words (in this case), we're recognizing that the second edit happened after where the first edit // ended with a delta of 20 characters (60 - 40). Thus, if we go back in time to where the first edit started // that's the same as if we started at char 80 instead of 60. // // As it so happens, the same logic applies if the second edit precedes the first edit. In that case rather // than pushing the first edit forward to match the second, we'll push the second edit forward to match the // first. // // In this case that means we have { oldStart: 10, oldEnd: 80, newEnd: 70 } or, in TextChangeRange // semantics: { { start: 10, length: 70 }, newLength: 60 } // // The math then works out as follows. // If we have { oldStart1, oldEnd1, newEnd1 } and { oldStart2, oldEnd2, newEnd2 } then we can compute the // final result like so: // // { // oldStart3: Min(oldStart1, oldStart2), // oldEnd3 : Max(oldEnd1, oldEnd1 + (oldEnd2 - newEnd1)), // newEnd3 : Max(newEnd2, newEnd2 + (newEnd1 - oldEnd2)) // } var oldStart1 = oldStartN; var oldEnd1 = oldEndN; var newEnd1 = newEndN; var oldStart2 = nextChange.span.start; var oldEnd2 = textSpanEnd(nextChange.span); var newEnd2 = oldStart2 + nextChange.newLength; oldStartN = Math.min(oldStart1, oldStart2); oldEndN = Math.max(oldEnd1, oldEnd1 + (oldEnd2 - newEnd1)); newEndN = Math.max(newEnd2, newEnd2 + (newEnd1 - oldEnd2)); } return createTextChangeRange(createTextSpanFromBounds(oldStartN, oldEndN), /*newLength:*/ newEndN - oldStartN); }
[ "function", "collapseTextChangeRangesAcrossMultipleVersions", "(", "changes", ")", "{", "if", "(", "changes", ".", "length", "===", "0", ")", "{", "return", "ts", ".", "unchangedTextChangeRange", ";", "}", "if", "(", "changes", ".", "length", "===", "1", ")", "{", "return", "changes", "[", "0", "]", ";", "}", "var", "change0", "=", "changes", "[", "0", "]", ";", "var", "oldStartN", "=", "change0", ".", "span", ".", "start", ";", "var", "oldEndN", "=", "textSpanEnd", "(", "change0", ".", "span", ")", ";", "var", "newEndN", "=", "oldStartN", "+", "change0", ".", "newLength", ";", "for", "(", "var", "i", "=", "1", ";", "i", "<", "changes", ".", "length", ";", "i", "++", ")", "{", "var", "nextChange", "=", "changes", "[", "i", "]", ";", "var", "oldStart1", "=", "oldStartN", ";", "var", "oldEnd1", "=", "oldEndN", ";", "var", "newEnd1", "=", "newEndN", ";", "var", "oldStart2", "=", "nextChange", ".", "span", ".", "start", ";", "var", "oldEnd2", "=", "textSpanEnd", "(", "nextChange", ".", "span", ")", ";", "var", "newEnd2", "=", "oldStart2", "+", "nextChange", ".", "newLength", ";", "oldStartN", "=", "Math", ".", "min", "(", "oldStart1", ",", "oldStart2", ")", ";", "oldEndN", "=", "Math", ".", "max", "(", "oldEnd1", ",", "oldEnd1", "+", "(", "oldEnd2", "-", "newEnd1", ")", ")", ";", "newEndN", "=", "Math", ".", "max", "(", "newEnd2", ",", "newEnd2", "+", "(", "newEnd1", "-", "oldEnd2", ")", ")", ";", "}", "return", "createTextChangeRange", "(", "createTextSpanFromBounds", "(", "oldStartN", ",", "oldEndN", ")", ",", "newEndN", "-", "oldStartN", ")", ";", "}" ]
Called to merge all the changes that occurred across several versions of a script snapshot into a single change. i.e. if a user keeps making successive edits to a script we will have a text change from V1 to V2, V2 to V3, ..., Vn. This function will then merge those changes into a single change range valid between V1 and Vn.
[ "Called", "to", "merge", "all", "the", "changes", "that", "occurred", "across", "several", "versions", "of", "a", "script", "snapshot", "into", "a", "single", "change", ".", "i", ".", "e", ".", "if", "a", "user", "keeps", "making", "successive", "edits", "to", "a", "script", "we", "will", "have", "a", "text", "change", "from", "V1", "to", "V2", "V2", "to", "V3", "...", "Vn", "." ]
c0cd5250a573689a8bcd9733b958d4215b0ecfa4
https://github.com/opendigitaleducation/sijil.js/blob/c0cd5250a573689a8bcd9733b958d4215b0ecfa4/docs/libs/typescript.js#L8179-L8284
train
opendigitaleducation/sijil.js
docs/libs/typescript.js
isIdentifier
function isIdentifier() { if (token() === 69 /* Identifier */) { return true; } // If we have a 'yield' keyword, and we're in the [yield] context, then 'yield' is // considered a keyword and is not an identifier. if (token() === 114 /* YieldKeyword */ && inYieldContext()) { return false; } // If we have a 'await' keyword, and we're in the [Await] context, then 'await' is // considered a keyword and is not an identifier. if (token() === 119 /* AwaitKeyword */ && inAwaitContext()) { return false; } return token() > 105 /* LastReservedWord */; }
javascript
function isIdentifier() { if (token() === 69 /* Identifier */) { return true; } // If we have a 'yield' keyword, and we're in the [yield] context, then 'yield' is // considered a keyword and is not an identifier. if (token() === 114 /* YieldKeyword */ && inYieldContext()) { return false; } // If we have a 'await' keyword, and we're in the [Await] context, then 'await' is // considered a keyword and is not an identifier. if (token() === 119 /* AwaitKeyword */ && inAwaitContext()) { return false; } return token() > 105 /* LastReservedWord */; }
[ "function", "isIdentifier", "(", ")", "{", "if", "(", "token", "(", ")", "===", "69", ")", "{", "return", "true", ";", "}", "if", "(", "token", "(", ")", "===", "114", "&&", "inYieldContext", "(", ")", ")", "{", "return", "false", ";", "}", "if", "(", "token", "(", ")", "===", "119", "&&", "inAwaitContext", "(", ")", ")", "{", "return", "false", ";", "}", "return", "token", "(", ")", ">", "105", ";", "}" ]
Ignore strict mode flag because we will report an error in type checker instead.
[ "Ignore", "strict", "mode", "flag", "because", "we", "will", "report", "an", "error", "in", "type", "checker", "instead", "." ]
c0cd5250a573689a8bcd9733b958d4215b0ecfa4
https://github.com/opendigitaleducation/sijil.js/blob/c0cd5250a573689a8bcd9733b958d4215b0ecfa4/docs/libs/typescript.js#L9175-L9190
train
opendigitaleducation/sijil.js
docs/libs/typescript.js
isListElement
function isListElement(parsingContext, inErrorRecovery) { var node = currentNode(parsingContext); if (node) { return true; } switch (parsingContext) { case 0 /* SourceElements */: case 1 /* BlockStatements */: case 3 /* SwitchClauseStatements */: // If we're in error recovery, then we don't want to treat ';' as an empty statement. // The problem is that ';' can show up in far too many contexts, and if we see one // and assume it's a statement, then we may bail out inappropriately from whatever // we're parsing. For example, if we have a semicolon in the middle of a class, then // we really don't want to assume the class is over and we're on a statement in the // outer module. We just want to consume and move on. return !(token() === 23 /* SemicolonToken */ && inErrorRecovery) && isStartOfStatement(); case 2 /* SwitchClauses */: return token() === 71 /* CaseKeyword */ || token() === 77 /* DefaultKeyword */; case 4 /* TypeMembers */: return lookAhead(isTypeMemberStart); case 5 /* ClassMembers */: // We allow semicolons as class elements (as specified by ES6) as long as we're // not in error recovery. If we're in error recovery, we don't want an errant // semicolon to be treated as a class member (since they're almost always used // for statements. return lookAhead(isClassMemberStart) || (token() === 23 /* SemicolonToken */ && !inErrorRecovery); case 6 /* EnumMembers */: // Include open bracket computed properties. This technically also lets in indexers, // which would be a candidate for improved error reporting. return token() === 19 /* OpenBracketToken */ || isLiteralPropertyName(); case 12 /* ObjectLiteralMembers */: return token() === 19 /* OpenBracketToken */ || token() === 37 /* AsteriskToken */ || isLiteralPropertyName(); case 9 /* ObjectBindingElements */: return token() === 19 /* OpenBracketToken */ || isLiteralPropertyName(); case 7 /* HeritageClauseElement */: // If we see { } then only consume it as an expression if it is followed by , or { // That way we won't consume the body of a class in its heritage clause. if (token() === 15 /* OpenBraceToken */) { return lookAhead(isValidHeritageClauseObjectLiteral); } if (!inErrorRecovery) { return isStartOfLeftHandSideExpression() && !isHeritageClauseExtendsOrImplementsKeyword(); } else { // If we're in error recovery we tighten up what we're willing to match. // That way we don't treat something like "this" as a valid heritage clause // element during recovery. return isIdentifier() && !isHeritageClauseExtendsOrImplementsKeyword(); } case 8 /* VariableDeclarations */: return isIdentifierOrPattern(); case 10 /* ArrayBindingElements */: return token() === 24 /* CommaToken */ || token() === 22 /* DotDotDotToken */ || isIdentifierOrPattern(); case 17 /* TypeParameters */: return isIdentifier(); case 11 /* ArgumentExpressions */: case 15 /* ArrayLiteralMembers */: return token() === 24 /* CommaToken */ || token() === 22 /* DotDotDotToken */ || isStartOfExpression(); case 16 /* Parameters */: return isStartOfParameter(); case 18 /* TypeArguments */: case 19 /* TupleElementTypes */: return token() === 24 /* CommaToken */ || isStartOfType(); case 20 /* HeritageClauses */: return isHeritageClause(); case 21 /* ImportOrExportSpecifiers */: return ts.tokenIsIdentifierOrKeyword(token()); case 13 /* JsxAttributes */: return ts.tokenIsIdentifierOrKeyword(token()) || token() === 15 /* OpenBraceToken */; case 14 /* JsxChildren */: return true; case 22 /* JSDocFunctionParameters */: case 23 /* JSDocTypeArguments */: case 25 /* JSDocTupleTypes */: return JSDocParser.isJSDocType(); case 24 /* JSDocRecordMembers */: return isSimplePropertyName(); } ts.Debug.fail("Non-exhaustive case in 'isListElement'."); }
javascript
function isListElement(parsingContext, inErrorRecovery) { var node = currentNode(parsingContext); if (node) { return true; } switch (parsingContext) { case 0 /* SourceElements */: case 1 /* BlockStatements */: case 3 /* SwitchClauseStatements */: // If we're in error recovery, then we don't want to treat ';' as an empty statement. // The problem is that ';' can show up in far too many contexts, and if we see one // and assume it's a statement, then we may bail out inappropriately from whatever // we're parsing. For example, if we have a semicolon in the middle of a class, then // we really don't want to assume the class is over and we're on a statement in the // outer module. We just want to consume and move on. return !(token() === 23 /* SemicolonToken */ && inErrorRecovery) && isStartOfStatement(); case 2 /* SwitchClauses */: return token() === 71 /* CaseKeyword */ || token() === 77 /* DefaultKeyword */; case 4 /* TypeMembers */: return lookAhead(isTypeMemberStart); case 5 /* ClassMembers */: // We allow semicolons as class elements (as specified by ES6) as long as we're // not in error recovery. If we're in error recovery, we don't want an errant // semicolon to be treated as a class member (since they're almost always used // for statements. return lookAhead(isClassMemberStart) || (token() === 23 /* SemicolonToken */ && !inErrorRecovery); case 6 /* EnumMembers */: // Include open bracket computed properties. This technically also lets in indexers, // which would be a candidate for improved error reporting. return token() === 19 /* OpenBracketToken */ || isLiteralPropertyName(); case 12 /* ObjectLiteralMembers */: return token() === 19 /* OpenBracketToken */ || token() === 37 /* AsteriskToken */ || isLiteralPropertyName(); case 9 /* ObjectBindingElements */: return token() === 19 /* OpenBracketToken */ || isLiteralPropertyName(); case 7 /* HeritageClauseElement */: // If we see { } then only consume it as an expression if it is followed by , or { // That way we won't consume the body of a class in its heritage clause. if (token() === 15 /* OpenBraceToken */) { return lookAhead(isValidHeritageClauseObjectLiteral); } if (!inErrorRecovery) { return isStartOfLeftHandSideExpression() && !isHeritageClauseExtendsOrImplementsKeyword(); } else { // If we're in error recovery we tighten up what we're willing to match. // That way we don't treat something like "this" as a valid heritage clause // element during recovery. return isIdentifier() && !isHeritageClauseExtendsOrImplementsKeyword(); } case 8 /* VariableDeclarations */: return isIdentifierOrPattern(); case 10 /* ArrayBindingElements */: return token() === 24 /* CommaToken */ || token() === 22 /* DotDotDotToken */ || isIdentifierOrPattern(); case 17 /* TypeParameters */: return isIdentifier(); case 11 /* ArgumentExpressions */: case 15 /* ArrayLiteralMembers */: return token() === 24 /* CommaToken */ || token() === 22 /* DotDotDotToken */ || isStartOfExpression(); case 16 /* Parameters */: return isStartOfParameter(); case 18 /* TypeArguments */: case 19 /* TupleElementTypes */: return token() === 24 /* CommaToken */ || isStartOfType(); case 20 /* HeritageClauses */: return isHeritageClause(); case 21 /* ImportOrExportSpecifiers */: return ts.tokenIsIdentifierOrKeyword(token()); case 13 /* JsxAttributes */: return ts.tokenIsIdentifierOrKeyword(token()) || token() === 15 /* OpenBraceToken */; case 14 /* JsxChildren */: return true; case 22 /* JSDocFunctionParameters */: case 23 /* JSDocTypeArguments */: case 25 /* JSDocTupleTypes */: return JSDocParser.isJSDocType(); case 24 /* JSDocRecordMembers */: return isSimplePropertyName(); } ts.Debug.fail("Non-exhaustive case in 'isListElement'."); }
[ "function", "isListElement", "(", "parsingContext", ",", "inErrorRecovery", ")", "{", "var", "node", "=", "currentNode", "(", "parsingContext", ")", ";", "if", "(", "node", ")", "{", "return", "true", ";", "}", "switch", "(", "parsingContext", ")", "{", "case", "0", ":", "case", "1", ":", "case", "3", ":", "return", "!", "(", "token", "(", ")", "===", "23", "&&", "inErrorRecovery", ")", "&&", "isStartOfStatement", "(", ")", ";", "case", "2", ":", "return", "token", "(", ")", "===", "71", "||", "token", "(", ")", "===", "77", ";", "case", "4", ":", "return", "lookAhead", "(", "isTypeMemberStart", ")", ";", "case", "5", ":", "return", "lookAhead", "(", "isClassMemberStart", ")", "||", "(", "token", "(", ")", "===", "23", "&&", "!", "inErrorRecovery", ")", ";", "case", "6", ":", "return", "token", "(", ")", "===", "19", "||", "isLiteralPropertyName", "(", ")", ";", "case", "12", ":", "return", "token", "(", ")", "===", "19", "||", "token", "(", ")", "===", "37", "||", "isLiteralPropertyName", "(", ")", ";", "case", "9", ":", "return", "token", "(", ")", "===", "19", "||", "isLiteralPropertyName", "(", ")", ";", "case", "7", ":", "if", "(", "token", "(", ")", "===", "15", ")", "{", "return", "lookAhead", "(", "isValidHeritageClauseObjectLiteral", ")", ";", "}", "if", "(", "!", "inErrorRecovery", ")", "{", "return", "isStartOfLeftHandSideExpression", "(", ")", "&&", "!", "isHeritageClauseExtendsOrImplementsKeyword", "(", ")", ";", "}", "else", "{", "return", "isIdentifier", "(", ")", "&&", "!", "isHeritageClauseExtendsOrImplementsKeyword", "(", ")", ";", "}", "case", "8", ":", "return", "isIdentifierOrPattern", "(", ")", ";", "case", "10", ":", "return", "token", "(", ")", "===", "24", "||", "token", "(", ")", "===", "22", "||", "isIdentifierOrPattern", "(", ")", ";", "case", "17", ":", "return", "isIdentifier", "(", ")", ";", "case", "11", ":", "case", "15", ":", "return", "token", "(", ")", "===", "24", "||", "token", "(", ")", "===", "22", "||", "isStartOfExpression", "(", ")", ";", "case", "16", ":", "return", "isStartOfParameter", "(", ")", ";", "case", "18", ":", "case", "19", ":", "return", "token", "(", ")", "===", "24", "||", "isStartOfType", "(", ")", ";", "case", "20", ":", "return", "isHeritageClause", "(", ")", ";", "case", "21", ":", "return", "ts", ".", "tokenIsIdentifierOrKeyword", "(", "token", "(", ")", ")", ";", "case", "13", ":", "return", "ts", ".", "tokenIsIdentifierOrKeyword", "(", "token", "(", ")", ")", "||", "token", "(", ")", "===", "15", ";", "case", "14", ":", "return", "true", ";", "case", "22", ":", "case", "23", ":", "case", "25", ":", "return", "JSDocParser", ".", "isJSDocType", "(", ")", ";", "case", "24", ":", "return", "isSimplePropertyName", "(", ")", ";", "}", "ts", ".", "Debug", ".", "fail", "(", "\"Non-exhaustive case in 'isListElement'.\"", ")", ";", "}" ]
True if positioned at the start of a list element
[ "True", "if", "positioned", "at", "the", "start", "of", "a", "list", "element" ]
c0cd5250a573689a8bcd9733b958d4215b0ecfa4
https://github.com/opendigitaleducation/sijil.js/blob/c0cd5250a573689a8bcd9733b958d4215b0ecfa4/docs/libs/typescript.js#L9395-L9474
train
opendigitaleducation/sijil.js
docs/libs/typescript.js
isInSomeParsingContext
function isInSomeParsingContext() { for (var kind = 0; kind < 26 /* Count */; kind++) { if (parsingContext & (1 << kind)) { if (isListElement(kind, /*inErrorRecovery*/ true) || isListTerminator(kind)) { return true; } } } return false; }
javascript
function isInSomeParsingContext() { for (var kind = 0; kind < 26 /* Count */; kind++) { if (parsingContext & (1 << kind)) { if (isListElement(kind, /*inErrorRecovery*/ true) || isListTerminator(kind)) { return true; } } } return false; }
[ "function", "isInSomeParsingContext", "(", ")", "{", "for", "(", "var", "kind", "=", "0", ";", "kind", "<", "26", ";", "kind", "++", ")", "{", "if", "(", "parsingContext", "&", "(", "1", "<<", "kind", ")", ")", "{", "if", "(", "isListElement", "(", "kind", ",", "true", ")", "||", "isListTerminator", "(", "kind", ")", ")", "{", "return", "true", ";", "}", "}", "}", "return", "false", ";", "}" ]
True if positioned at element or terminator of the current list or any enclosing list
[ "True", "if", "positioned", "at", "element", "or", "terminator", "of", "the", "current", "list", "or", "any", "enclosing", "list" ]
c0cd5250a573689a8bcd9733b958d4215b0ecfa4
https://github.com/opendigitaleducation/sijil.js/blob/c0cd5250a573689a8bcd9733b958d4215b0ecfa4/docs/libs/typescript.js#L9585-L9594
train
opendigitaleducation/sijil.js
docs/libs/typescript.js
parseList
function parseList(kind, parseElement) { var saveParsingContext = parsingContext; parsingContext |= 1 << kind; var result = []; result.pos = getNodePos(); while (!isListTerminator(kind)) { if (isListElement(kind, /*inErrorRecovery*/ false)) { var element = parseListElement(kind, parseElement); result.push(element); continue; } if (abortParsingListOrMoveToNextToken(kind)) { break; } } result.end = getNodeEnd(); parsingContext = saveParsingContext; return result; }
javascript
function parseList(kind, parseElement) { var saveParsingContext = parsingContext; parsingContext |= 1 << kind; var result = []; result.pos = getNodePos(); while (!isListTerminator(kind)) { if (isListElement(kind, /*inErrorRecovery*/ false)) { var element = parseListElement(kind, parseElement); result.push(element); continue; } if (abortParsingListOrMoveToNextToken(kind)) { break; } } result.end = getNodeEnd(); parsingContext = saveParsingContext; return result; }
[ "function", "parseList", "(", "kind", ",", "parseElement", ")", "{", "var", "saveParsingContext", "=", "parsingContext", ";", "parsingContext", "|=", "1", "<<", "kind", ";", "var", "result", "=", "[", "]", ";", "result", ".", "pos", "=", "getNodePos", "(", ")", ";", "while", "(", "!", "isListTerminator", "(", "kind", ")", ")", "{", "if", "(", "isListElement", "(", "kind", ",", "false", ")", ")", "{", "var", "element", "=", "parseListElement", "(", "kind", ",", "parseElement", ")", ";", "result", ".", "push", "(", "element", ")", ";", "continue", ";", "}", "if", "(", "abortParsingListOrMoveToNextToken", "(", "kind", ")", ")", "{", "break", ";", "}", "}", "result", ".", "end", "=", "getNodeEnd", "(", ")", ";", "parsingContext", "=", "saveParsingContext", ";", "return", "result", ";", "}" ]
Parses a list of elements
[ "Parses", "a", "list", "of", "elements" ]
c0cd5250a573689a8bcd9733b958d4215b0ecfa4
https://github.com/opendigitaleducation/sijil.js/blob/c0cd5250a573689a8bcd9733b958d4215b0ecfa4/docs/libs/typescript.js#L9596-L9614
train
opendigitaleducation/sijil.js
docs/libs/typescript.js
parseDelimitedList
function parseDelimitedList(kind, parseElement, considerSemicolonAsDelimiter) { var saveParsingContext = parsingContext; parsingContext |= 1 << kind; var result = []; result.pos = getNodePos(); var commaStart = -1; // Meaning the previous token was not a comma while (true) { if (isListElement(kind, /*inErrorRecovery*/ false)) { result.push(parseListElement(kind, parseElement)); commaStart = scanner.getTokenPos(); if (parseOptional(24 /* CommaToken */)) { continue; } commaStart = -1; // Back to the state where the last token was not a comma if (isListTerminator(kind)) { break; } // We didn't get a comma, and the list wasn't terminated, explicitly parse // out a comma so we give a good error message. parseExpected(24 /* CommaToken */); // If the token was a semicolon, and the caller allows that, then skip it and // continue. This ensures we get back on track and don't result in tons of // parse errors. For example, this can happen when people do things like use // a semicolon to delimit object literal members. Note: we'll have already // reported an error when we called parseExpected above. if (considerSemicolonAsDelimiter && token() === 23 /* SemicolonToken */ && !scanner.hasPrecedingLineBreak()) { nextToken(); } continue; } if (isListTerminator(kind)) { break; } if (abortParsingListOrMoveToNextToken(kind)) { break; } } // Recording the trailing comma is deliberately done after the previous // loop, and not just if we see a list terminator. This is because the list // may have ended incorrectly, but it is still important to know if there // was a trailing comma. // Check if the last token was a comma. if (commaStart >= 0) { // Always preserve a trailing comma by marking it on the NodeArray result.hasTrailingComma = true; } result.end = getNodeEnd(); parsingContext = saveParsingContext; return result; }
javascript
function parseDelimitedList(kind, parseElement, considerSemicolonAsDelimiter) { var saveParsingContext = parsingContext; parsingContext |= 1 << kind; var result = []; result.pos = getNodePos(); var commaStart = -1; // Meaning the previous token was not a comma while (true) { if (isListElement(kind, /*inErrorRecovery*/ false)) { result.push(parseListElement(kind, parseElement)); commaStart = scanner.getTokenPos(); if (parseOptional(24 /* CommaToken */)) { continue; } commaStart = -1; // Back to the state where the last token was not a comma if (isListTerminator(kind)) { break; } // We didn't get a comma, and the list wasn't terminated, explicitly parse // out a comma so we give a good error message. parseExpected(24 /* CommaToken */); // If the token was a semicolon, and the caller allows that, then skip it and // continue. This ensures we get back on track and don't result in tons of // parse errors. For example, this can happen when people do things like use // a semicolon to delimit object literal members. Note: we'll have already // reported an error when we called parseExpected above. if (considerSemicolonAsDelimiter && token() === 23 /* SemicolonToken */ && !scanner.hasPrecedingLineBreak()) { nextToken(); } continue; } if (isListTerminator(kind)) { break; } if (abortParsingListOrMoveToNextToken(kind)) { break; } } // Recording the trailing comma is deliberately done after the previous // loop, and not just if we see a list terminator. This is because the list // may have ended incorrectly, but it is still important to know if there // was a trailing comma. // Check if the last token was a comma. if (commaStart >= 0) { // Always preserve a trailing comma by marking it on the NodeArray result.hasTrailingComma = true; } result.end = getNodeEnd(); parsingContext = saveParsingContext; return result; }
[ "function", "parseDelimitedList", "(", "kind", ",", "parseElement", ",", "considerSemicolonAsDelimiter", ")", "{", "var", "saveParsingContext", "=", "parsingContext", ";", "parsingContext", "|=", "1", "<<", "kind", ";", "var", "result", "=", "[", "]", ";", "result", ".", "pos", "=", "getNodePos", "(", ")", ";", "var", "commaStart", "=", "-", "1", ";", "while", "(", "true", ")", "{", "if", "(", "isListElement", "(", "kind", ",", "false", ")", ")", "{", "result", ".", "push", "(", "parseListElement", "(", "kind", ",", "parseElement", ")", ")", ";", "commaStart", "=", "scanner", ".", "getTokenPos", "(", ")", ";", "if", "(", "parseOptional", "(", "24", ")", ")", "{", "continue", ";", "}", "commaStart", "=", "-", "1", ";", "if", "(", "isListTerminator", "(", "kind", ")", ")", "{", "break", ";", "}", "parseExpected", "(", "24", ")", ";", "if", "(", "considerSemicolonAsDelimiter", "&&", "token", "(", ")", "===", "23", "&&", "!", "scanner", ".", "hasPrecedingLineBreak", "(", ")", ")", "{", "nextToken", "(", ")", ";", "}", "continue", ";", "}", "if", "(", "isListTerminator", "(", "kind", ")", ")", "{", "break", ";", "}", "if", "(", "abortParsingListOrMoveToNextToken", "(", "kind", ")", ")", "{", "break", ";", "}", "}", "if", "(", "commaStart", ">=", "0", ")", "{", "result", ".", "hasTrailingComma", "=", "true", ";", "}", "result", ".", "end", "=", "getNodeEnd", "(", ")", ";", "parsingContext", "=", "saveParsingContext", ";", "return", "result", ";", "}" ]
Parses a comma-delimited list of elements
[ "Parses", "a", "comma", "-", "delimited", "list", "of", "elements" ]
c0cd5250a573689a8bcd9733b958d4215b0ecfa4
https://github.com/opendigitaleducation/sijil.js/blob/c0cd5250a573689a8bcd9733b958d4215b0ecfa4/docs/libs/typescript.js#L9894-L9943
train
opendigitaleducation/sijil.js
docs/libs/typescript.js
parseUnaryExpressionOrHigher
function parseUnaryExpressionOrHigher() { /** * ES7 UpdateExpression: * 1) LeftHandSideExpression[?Yield] * 2) LeftHandSideExpression[?Yield][no LineTerminator here]++ * 3) LeftHandSideExpression[?Yield][no LineTerminator here]-- * 4) ++UnaryExpression[?Yield] * 5) --UnaryExpression[?Yield] */ if (isUpdateExpression()) { var incrementExpression = parseIncrementExpression(); return token() === 38 /* AsteriskAsteriskToken */ ? parseBinaryExpressionRest(getBinaryOperatorPrecedence(), incrementExpression) : incrementExpression; } /** * ES7 UnaryExpression: * 1) UpdateExpression[?yield] * 2) delete UpdateExpression[?yield] * 3) void UpdateExpression[?yield] * 4) typeof UpdateExpression[?yield] * 5) + UpdateExpression[?yield] * 6) - UpdateExpression[?yield] * 7) ~ UpdateExpression[?yield] * 8) ! UpdateExpression[?yield] */ var unaryOperator = token(); var simpleUnaryExpression = parseSimpleUnaryExpression(); if (token() === 38 /* AsteriskAsteriskToken */) { var start = ts.skipTrivia(sourceText, simpleUnaryExpression.pos); if (simpleUnaryExpression.kind === 177 /* TypeAssertionExpression */) { parseErrorAtPosition(start, simpleUnaryExpression.end - start, ts.Diagnostics.A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses); } else { parseErrorAtPosition(start, simpleUnaryExpression.end - start, ts.Diagnostics.An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses, ts.tokenToString(unaryOperator)); } } return simpleUnaryExpression; }
javascript
function parseUnaryExpressionOrHigher() { /** * ES7 UpdateExpression: * 1) LeftHandSideExpression[?Yield] * 2) LeftHandSideExpression[?Yield][no LineTerminator here]++ * 3) LeftHandSideExpression[?Yield][no LineTerminator here]-- * 4) ++UnaryExpression[?Yield] * 5) --UnaryExpression[?Yield] */ if (isUpdateExpression()) { var incrementExpression = parseIncrementExpression(); return token() === 38 /* AsteriskAsteriskToken */ ? parseBinaryExpressionRest(getBinaryOperatorPrecedence(), incrementExpression) : incrementExpression; } /** * ES7 UnaryExpression: * 1) UpdateExpression[?yield] * 2) delete UpdateExpression[?yield] * 3) void UpdateExpression[?yield] * 4) typeof UpdateExpression[?yield] * 5) + UpdateExpression[?yield] * 6) - UpdateExpression[?yield] * 7) ~ UpdateExpression[?yield] * 8) ! UpdateExpression[?yield] */ var unaryOperator = token(); var simpleUnaryExpression = parseSimpleUnaryExpression(); if (token() === 38 /* AsteriskAsteriskToken */) { var start = ts.skipTrivia(sourceText, simpleUnaryExpression.pos); if (simpleUnaryExpression.kind === 177 /* TypeAssertionExpression */) { parseErrorAtPosition(start, simpleUnaryExpression.end - start, ts.Diagnostics.A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses); } else { parseErrorAtPosition(start, simpleUnaryExpression.end - start, ts.Diagnostics.An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses, ts.tokenToString(unaryOperator)); } } return simpleUnaryExpression; }
[ "function", "parseUnaryExpressionOrHigher", "(", ")", "{", "if", "(", "isUpdateExpression", "(", ")", ")", "{", "var", "incrementExpression", "=", "parseIncrementExpression", "(", ")", ";", "return", "token", "(", ")", "===", "38", "?", "parseBinaryExpressionRest", "(", "getBinaryOperatorPrecedence", "(", ")", ",", "incrementExpression", ")", ":", "incrementExpression", ";", "}", "var", "unaryOperator", "=", "token", "(", ")", ";", "var", "simpleUnaryExpression", "=", "parseSimpleUnaryExpression", "(", ")", ";", "if", "(", "token", "(", ")", "===", "38", ")", "{", "var", "start", "=", "ts", ".", "skipTrivia", "(", "sourceText", ",", "simpleUnaryExpression", ".", "pos", ")", ";", "if", "(", "simpleUnaryExpression", ".", "kind", "===", "177", ")", "{", "parseErrorAtPosition", "(", "start", ",", "simpleUnaryExpression", ".", "end", "-", "start", ",", "ts", ".", "Diagnostics", ".", "A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses", ")", ";", "}", "else", "{", "parseErrorAtPosition", "(", "start", ",", "simpleUnaryExpression", ".", "end", "-", "start", ",", "ts", ".", "Diagnostics", ".", "An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses", ",", "ts", ".", "tokenToString", "(", "unaryOperator", ")", ")", ";", "}", "}", "return", "simpleUnaryExpression", ";", "}" ]
Parse ES7 exponential expression and await expression ES7 ExponentiationExpression: 1) UnaryExpression[?Yield] 2) UpdateExpression[?Yield] ** ExponentiationExpression[?Yield]
[ "Parse", "ES7", "exponential", "expression", "and", "await", "expression" ]
c0cd5250a573689a8bcd9733b958d4215b0ecfa4
https://github.com/opendigitaleducation/sijil.js/blob/c0cd5250a573689a8bcd9733b958d4215b0ecfa4/docs/libs/typescript.js#L11284-L11322
train
opendigitaleducation/sijil.js
docs/libs/typescript.js
parseIncrementExpression
function parseIncrementExpression() { if (token() === 41 /* PlusPlusToken */ || token() === 42 /* MinusMinusToken */) { var node = createNode(185 /* PrefixUnaryExpression */); node.operator = token(); nextToken(); node.operand = parseLeftHandSideExpressionOrHigher(); return finishNode(node); } else if (sourceFile.languageVariant === 1 /* JSX */ && token() === 25 /* LessThanToken */ && lookAhead(nextTokenIsIdentifierOrKeyword)) { // JSXElement is part of primaryExpression return parseJsxElementOrSelfClosingElement(/*inExpressionContext*/ true); } var expression = parseLeftHandSideExpressionOrHigher(); ts.Debug.assert(ts.isLeftHandSideExpression(expression)); if ((token() === 41 /* PlusPlusToken */ || token() === 42 /* MinusMinusToken */) && !scanner.hasPrecedingLineBreak()) { var node = createNode(186 /* PostfixUnaryExpression */, expression.pos); node.operand = expression; node.operator = token(); nextToken(); return finishNode(node); } return expression; }
javascript
function parseIncrementExpression() { if (token() === 41 /* PlusPlusToken */ || token() === 42 /* MinusMinusToken */) { var node = createNode(185 /* PrefixUnaryExpression */); node.operator = token(); nextToken(); node.operand = parseLeftHandSideExpressionOrHigher(); return finishNode(node); } else if (sourceFile.languageVariant === 1 /* JSX */ && token() === 25 /* LessThanToken */ && lookAhead(nextTokenIsIdentifierOrKeyword)) { // JSXElement is part of primaryExpression return parseJsxElementOrSelfClosingElement(/*inExpressionContext*/ true); } var expression = parseLeftHandSideExpressionOrHigher(); ts.Debug.assert(ts.isLeftHandSideExpression(expression)); if ((token() === 41 /* PlusPlusToken */ || token() === 42 /* MinusMinusToken */) && !scanner.hasPrecedingLineBreak()) { var node = createNode(186 /* PostfixUnaryExpression */, expression.pos); node.operand = expression; node.operator = token(); nextToken(); return finishNode(node); } return expression; }
[ "function", "parseIncrementExpression", "(", ")", "{", "if", "(", "token", "(", ")", "===", "41", "||", "token", "(", ")", "===", "42", ")", "{", "var", "node", "=", "createNode", "(", "185", ")", ";", "node", ".", "operator", "=", "token", "(", ")", ";", "nextToken", "(", ")", ";", "node", ".", "operand", "=", "parseLeftHandSideExpressionOrHigher", "(", ")", ";", "return", "finishNode", "(", "node", ")", ";", "}", "else", "if", "(", "sourceFile", ".", "languageVariant", "===", "1", "&&", "token", "(", ")", "===", "25", "&&", "lookAhead", "(", "nextTokenIsIdentifierOrKeyword", ")", ")", "{", "return", "parseJsxElementOrSelfClosingElement", "(", "true", ")", ";", "}", "var", "expression", "=", "parseLeftHandSideExpressionOrHigher", "(", ")", ";", "ts", ".", "Debug", ".", "assert", "(", "ts", ".", "isLeftHandSideExpression", "(", "expression", ")", ")", ";", "if", "(", "(", "token", "(", ")", "===", "41", "||", "token", "(", ")", "===", "42", ")", "&&", "!", "scanner", ".", "hasPrecedingLineBreak", "(", ")", ")", "{", "var", "node", "=", "createNode", "(", "186", ",", "expression", ".", "pos", ")", ";", "node", ".", "operand", "=", "expression", ";", "node", ".", "operator", "=", "token", "(", ")", ";", "nextToken", "(", ")", ";", "return", "finishNode", "(", "node", ")", ";", "}", "return", "expression", ";", "}" ]
Parse ES7 IncrementExpression. IncrementExpression is used instead of ES6's PostFixExpression. ES7 IncrementExpression[yield]: 1) LeftHandSideExpression[?yield] 2) LeftHandSideExpression[?yield] [[no LineTerminator here]]++ 3) LeftHandSideExpression[?yield] [[no LineTerminator here]]-- 4) ++LeftHandSideExpression[?yield] 5) --LeftHandSideExpression[?yield] In TypeScript (2), (3) are parsed as PostfixUnaryExpression. (4), (5) are parsed as PrefixUnaryExpression
[ "Parse", "ES7", "IncrementExpression", ".", "IncrementExpression", "is", "used", "instead", "of", "ES6", "s", "PostFixExpression", "." ]
c0cd5250a573689a8bcd9733b958d4215b0ecfa4
https://github.com/opendigitaleducation/sijil.js/blob/c0cd5250a573689a8bcd9733b958d4215b0ecfa4/docs/libs/typescript.js#L11408-L11430
train
opendigitaleducation/sijil.js
docs/libs/typescript.js
parseEnumMember
function parseEnumMember() { var node = createNode(255 /* EnumMember */, scanner.getStartPos()); node.name = parsePropertyName(); node.initializer = allowInAnd(parseNonParameterInitializer); return finishNode(node); }
javascript
function parseEnumMember() { var node = createNode(255 /* EnumMember */, scanner.getStartPos()); node.name = parsePropertyName(); node.initializer = allowInAnd(parseNonParameterInitializer); return finishNode(node); }
[ "function", "parseEnumMember", "(", ")", "{", "var", "node", "=", "createNode", "(", "255", ",", "scanner", ".", "getStartPos", "(", ")", ")", ";", "node", ".", "name", "=", "parsePropertyName", "(", ")", ";", "node", ".", "initializer", "=", "allowInAnd", "(", "parseNonParameterInitializer", ")", ";", "return", "finishNode", "(", "node", ")", ";", "}" ]
In an ambient declaration, the grammar only allows integer literals as initializers. In a non-ambient declaration, the grammar allows uninitialized members only in a ConstantEnumMemberSection, which starts at the beginning of an enum declaration or any time an integer literal initializer is encountered.
[ "In", "an", "ambient", "declaration", "the", "grammar", "only", "allows", "integer", "literals", "as", "initializers", ".", "In", "a", "non", "-", "ambient", "declaration", "the", "grammar", "allows", "uninitialized", "members", "only", "in", "a", "ConstantEnumMemberSection", "which", "starts", "at", "the", "beginning", "of", "an", "enum", "declaration", "or", "any", "time", "an", "integer", "literal", "initializer", "is", "encountered", "." ]
c0cd5250a573689a8bcd9733b958d4215b0ecfa4
https://github.com/opendigitaleducation/sijil.js/blob/c0cd5250a573689a8bcd9733b958d4215b0ecfa4/docs/libs/typescript.js#L13028-L13033
train
opendigitaleducation/sijil.js
docs/libs/typescript.js
tryFile
function tryFile(fileName, failedLookupLocation, onlyRecordFailures, state) { if (!onlyRecordFailures && state.host.fileExists(fileName)) { if (state.traceEnabled) { ts.trace(state.host, ts.Diagnostics.File_0_exist_use_it_as_a_name_resolution_result, fileName); } return fileName; } else { if (state.traceEnabled) { ts.trace(state.host, ts.Diagnostics.File_0_does_not_exist, fileName); } failedLookupLocation.push(fileName); return undefined; } }
javascript
function tryFile(fileName, failedLookupLocation, onlyRecordFailures, state) { if (!onlyRecordFailures && state.host.fileExists(fileName)) { if (state.traceEnabled) { ts.trace(state.host, ts.Diagnostics.File_0_exist_use_it_as_a_name_resolution_result, fileName); } return fileName; } else { if (state.traceEnabled) { ts.trace(state.host, ts.Diagnostics.File_0_does_not_exist, fileName); } failedLookupLocation.push(fileName); return undefined; } }
[ "function", "tryFile", "(", "fileName", ",", "failedLookupLocation", ",", "onlyRecordFailures", ",", "state", ")", "{", "if", "(", "!", "onlyRecordFailures", "&&", "state", ".", "host", ".", "fileExists", "(", "fileName", ")", ")", "{", "if", "(", "state", ".", "traceEnabled", ")", "{", "ts", ".", "trace", "(", "state", ".", "host", ",", "ts", ".", "Diagnostics", ".", "File_0_exist_use_it_as_a_name_resolution_result", ",", "fileName", ")", ";", "}", "return", "fileName", ";", "}", "else", "{", "if", "(", "state", ".", "traceEnabled", ")", "{", "ts", ".", "trace", "(", "state", ".", "host", ",", "ts", ".", "Diagnostics", ".", "File_0_does_not_exist", ",", "fileName", ")", ";", "}", "failedLookupLocation", ".", "push", "(", "fileName", ")", ";", "return", "undefined", ";", "}", "}" ]
Return the file if it exists.
[ "Return", "the", "file", "if", "it", "exists", "." ]
c0cd5250a573689a8bcd9733b958d4215b0ecfa4
https://github.com/opendigitaleducation/sijil.js/blob/c0cd5250a573689a8bcd9733b958d4215b0ecfa4/docs/libs/typescript.js#L14602-L14616
train
opendigitaleducation/sijil.js
docs/libs/typescript.js
tryAddingExtensions
function tryAddingExtensions(candidate, extensions, failedLookupLocation, onlyRecordFailures, state) { if (!onlyRecordFailures) { // check if containing folder exists - if it doesn't then just record failures for all supported extensions without disk probing var directory = ts.getDirectoryPath(candidate); if (directory) { onlyRecordFailures = !directoryProbablyExists(directory, state.host); } } return ts.forEach(extensions, function (ext) { return !(state.skipTsx && ts.isJsxOrTsxExtension(ext)) && tryFile(candidate + ext, failedLookupLocation, onlyRecordFailures, state); }); }
javascript
function tryAddingExtensions(candidate, extensions, failedLookupLocation, onlyRecordFailures, state) { if (!onlyRecordFailures) { // check if containing folder exists - if it doesn't then just record failures for all supported extensions without disk probing var directory = ts.getDirectoryPath(candidate); if (directory) { onlyRecordFailures = !directoryProbablyExists(directory, state.host); } } return ts.forEach(extensions, function (ext) { return !(state.skipTsx && ts.isJsxOrTsxExtension(ext)) && tryFile(candidate + ext, failedLookupLocation, onlyRecordFailures, state); }); }
[ "function", "tryAddingExtensions", "(", "candidate", ",", "extensions", ",", "failedLookupLocation", ",", "onlyRecordFailures", ",", "state", ")", "{", "if", "(", "!", "onlyRecordFailures", ")", "{", "var", "directory", "=", "ts", ".", "getDirectoryPath", "(", "candidate", ")", ";", "if", "(", "directory", ")", "{", "onlyRecordFailures", "=", "!", "directoryProbablyExists", "(", "directory", ",", "state", ".", "host", ")", ";", "}", "}", "return", "ts", ".", "forEach", "(", "extensions", ",", "function", "(", "ext", ")", "{", "return", "!", "(", "state", ".", "skipTsx", "&&", "ts", ".", "isJsxOrTsxExtension", "(", "ext", ")", ")", "&&", "tryFile", "(", "candidate", "+", "ext", ",", "failedLookupLocation", ",", "onlyRecordFailures", ",", "state", ")", ";", "}", ")", ";", "}" ]
Try to return an existing file that adds one of the `extensions` to `candidate`.
[ "Try", "to", "return", "an", "existing", "file", "that", "adds", "one", "of", "the", "extensions", "to", "candidate", "." ]
c0cd5250a573689a8bcd9733b958d4215b0ecfa4
https://github.com/opendigitaleducation/sijil.js/blob/c0cd5250a573689a8bcd9733b958d4215b0ecfa4/docs/libs/typescript.js#L14618-L14629
train
opendigitaleducation/sijil.js
docs/libs/typescript.js
getDeclarationName
function getDeclarationName(node) { if (node.name) { if (ts.isAmbientModule(node)) { return ts.isGlobalScopeAugmentation(node) ? "__global" : "\"" + node.name.text + "\""; } if (node.name.kind === 140 /* ComputedPropertyName */) { var nameExpression = node.name.expression; // treat computed property names where expression is string/numeric literal as just string/numeric literal if (ts.isStringOrNumericLiteral(nameExpression.kind)) { return nameExpression.text; } ts.Debug.assert(ts.isWellKnownSymbolSyntactically(nameExpression)); return ts.getPropertyNameForKnownSymbolName(nameExpression.name.text); } return node.name.text; } switch (node.kind) { case 148 /* Constructor */: return "__constructor"; case 156 /* FunctionType */: case 151 /* CallSignature */: return "__call"; case 157 /* ConstructorType */: case 152 /* ConstructSignature */: return "__new"; case 153 /* IndexSignature */: return "__index"; case 236 /* ExportDeclaration */: return "__export"; case 235 /* ExportAssignment */: return node.isExportEquals ? "export=" : "default"; case 187 /* BinaryExpression */: switch (ts.getSpecialPropertyAssignmentKind(node)) { case 2 /* ModuleExports */: // module.exports = ... return "export="; case 1 /* ExportsProperty */: case 4 /* ThisProperty */: // exports.x = ... or this.y = ... return node.left.name.text; case 3 /* PrototypeProperty */: // className.prototype.methodName = ... return node.left.expression.name.text; } ts.Debug.fail("Unknown binary declaration kind"); break; case 220 /* FunctionDeclaration */: case 221 /* ClassDeclaration */: return node.flags & 512 /* Default */ ? "default" : undefined; case 269 /* JSDocFunctionType */: return ts.isJSDocConstructSignature(node) ? "__new" : "__call"; case 142 /* Parameter */: // Parameters with names are handled at the top of this function. Parameters // without names can only come from JSDocFunctionTypes. ts.Debug.assert(node.parent.kind === 269 /* JSDocFunctionType */); var functionType = node.parent; var index = ts.indexOf(functionType.parameters, node); return "p" + index; case 279 /* JSDocTypedefTag */: var parentNode = node.parent && node.parent.parent; var nameFromParentNode = void 0; if (parentNode && parentNode.kind === 200 /* VariableStatement */) { if (parentNode.declarationList.declarations.length > 0) { var nameIdentifier = parentNode.declarationList.declarations[0].name; if (nameIdentifier.kind === 69 /* Identifier */) { nameFromParentNode = nameIdentifier.text; } } } return nameFromParentNode; } }
javascript
function getDeclarationName(node) { if (node.name) { if (ts.isAmbientModule(node)) { return ts.isGlobalScopeAugmentation(node) ? "__global" : "\"" + node.name.text + "\""; } if (node.name.kind === 140 /* ComputedPropertyName */) { var nameExpression = node.name.expression; // treat computed property names where expression is string/numeric literal as just string/numeric literal if (ts.isStringOrNumericLiteral(nameExpression.kind)) { return nameExpression.text; } ts.Debug.assert(ts.isWellKnownSymbolSyntactically(nameExpression)); return ts.getPropertyNameForKnownSymbolName(nameExpression.name.text); } return node.name.text; } switch (node.kind) { case 148 /* Constructor */: return "__constructor"; case 156 /* FunctionType */: case 151 /* CallSignature */: return "__call"; case 157 /* ConstructorType */: case 152 /* ConstructSignature */: return "__new"; case 153 /* IndexSignature */: return "__index"; case 236 /* ExportDeclaration */: return "__export"; case 235 /* ExportAssignment */: return node.isExportEquals ? "export=" : "default"; case 187 /* BinaryExpression */: switch (ts.getSpecialPropertyAssignmentKind(node)) { case 2 /* ModuleExports */: // module.exports = ... return "export="; case 1 /* ExportsProperty */: case 4 /* ThisProperty */: // exports.x = ... or this.y = ... return node.left.name.text; case 3 /* PrototypeProperty */: // className.prototype.methodName = ... return node.left.expression.name.text; } ts.Debug.fail("Unknown binary declaration kind"); break; case 220 /* FunctionDeclaration */: case 221 /* ClassDeclaration */: return node.flags & 512 /* Default */ ? "default" : undefined; case 269 /* JSDocFunctionType */: return ts.isJSDocConstructSignature(node) ? "__new" : "__call"; case 142 /* Parameter */: // Parameters with names are handled at the top of this function. Parameters // without names can only come from JSDocFunctionTypes. ts.Debug.assert(node.parent.kind === 269 /* JSDocFunctionType */); var functionType = node.parent; var index = ts.indexOf(functionType.parameters, node); return "p" + index; case 279 /* JSDocTypedefTag */: var parentNode = node.parent && node.parent.parent; var nameFromParentNode = void 0; if (parentNode && parentNode.kind === 200 /* VariableStatement */) { if (parentNode.declarationList.declarations.length > 0) { var nameIdentifier = parentNode.declarationList.declarations[0].name; if (nameIdentifier.kind === 69 /* Identifier */) { nameFromParentNode = nameIdentifier.text; } } } return nameFromParentNode; } }
[ "function", "getDeclarationName", "(", "node", ")", "{", "if", "(", "node", ".", "name", ")", "{", "if", "(", "ts", ".", "isAmbientModule", "(", "node", ")", ")", "{", "return", "ts", ".", "isGlobalScopeAugmentation", "(", "node", ")", "?", "\"__global\"", ":", "\"\\\"\"", "+", "\\\"", "+", "node", ".", "name", ".", "text", ";", "}", "\"\\\"\"", "\\\"", "}", "if", "(", "node", ".", "name", ".", "kind", "===", "140", ")", "{", "var", "nameExpression", "=", "node", ".", "name", ".", "expression", ";", "if", "(", "ts", ".", "isStringOrNumericLiteral", "(", "nameExpression", ".", "kind", ")", ")", "{", "return", "nameExpression", ".", "text", ";", "}", "ts", ".", "Debug", ".", "assert", "(", "ts", ".", "isWellKnownSymbolSyntactically", "(", "nameExpression", ")", ")", ";", "return", "ts", ".", "getPropertyNameForKnownSymbolName", "(", "nameExpression", ".", "name", ".", "text", ")", ";", "}", "}" ]
Should not be called on a declaration with a computed property name, unless it is a well known Symbol.
[ "Should", "not", "be", "called", "on", "a", "declaration", "with", "a", "computed", "property", "name", "unless", "it", "is", "a", "well", "known", "Symbol", "." ]
c0cd5250a573689a8bcd9733b958d4215b0ecfa4
https://github.com/opendigitaleducation/sijil.js/blob/c0cd5250a573689a8bcd9733b958d4215b0ecfa4/docs/libs/typescript.js#L15270-L15341
train
opendigitaleducation/sijil.js
docs/libs/typescript.js
declareSymbol
function declareSymbol(symbolTable, parent, node, includes, excludes) { ts.Debug.assert(!ts.hasDynamicName(node)); var isDefaultExport = node.flags & 512 /* Default */; // The exported symbol for an export default function/class node is always named "default" var name = isDefaultExport && parent ? "default" : getDeclarationName(node); var symbol; if (name === undefined) { symbol = createSymbol(0 /* None */, "__missing"); } else { // Check and see if the symbol table already has a symbol with this name. If not, // create a new symbol with this name and add it to the table. Note that we don't // give the new symbol any flags *yet*. This ensures that it will not conflict // with the 'excludes' flags we pass in. // // If we do get an existing symbol, see if it conflicts with the new symbol we're // creating. For example, a 'var' symbol and a 'class' symbol will conflict within // the same symbol table. If we have a conflict, report the issue on each // declaration we have for this symbol, and then create a new symbol for this // declaration. // // Note that when properties declared in Javascript constructors // (marked by isReplaceableByMethod) conflict with another symbol, the property loses. // Always. This allows the common Javascript pattern of overwriting a prototype method // with an bound instance method of the same type: `this.method = this.method.bind(this)` // // If we created a new symbol, either because we didn't have a symbol with this name // in the symbol table, or we conflicted with an existing symbol, then just add this // node as the sole declaration of the new symbol. // // Otherwise, we'll be merging into a compatible existing symbol (for example when // you have multiple 'vars' with the same name in the same container). In this case // just add this node into the declarations list of the symbol. symbol = symbolTable[name] || (symbolTable[name] = createSymbol(0 /* None */, name)); if (name && (includes & 788448 /* Classifiable */)) { classifiableNames[name] = name; } if (symbol.flags & excludes) { if (symbol.isReplaceableByMethod) { // Javascript constructor-declared symbols can be discarded in favor of // prototype symbols like methods. symbol = symbolTable[name] = createSymbol(0 /* None */, name); } else { if (node.name) { node.name.parent = node; } // Report errors every position with duplicate declaration // Report errors on previous encountered declarations var message_1 = symbol.flags & 2 /* BlockScopedVariable */ ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 : ts.Diagnostics.Duplicate_identifier_0; ts.forEach(symbol.declarations, function (declaration) { if (declaration.flags & 512 /* Default */) { message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; } }); ts.forEach(symbol.declarations, function (declaration) { file.bindDiagnostics.push(ts.createDiagnosticForNode(declaration.name || declaration, message_1, getDisplayName(declaration))); }); file.bindDiagnostics.push(ts.createDiagnosticForNode(node.name || node, message_1, getDisplayName(node))); symbol = createSymbol(0 /* None */, name); } } } addDeclarationToSymbol(symbol, node, includes); symbol.parent = parent; return symbol; }
javascript
function declareSymbol(symbolTable, parent, node, includes, excludes) { ts.Debug.assert(!ts.hasDynamicName(node)); var isDefaultExport = node.flags & 512 /* Default */; // The exported symbol for an export default function/class node is always named "default" var name = isDefaultExport && parent ? "default" : getDeclarationName(node); var symbol; if (name === undefined) { symbol = createSymbol(0 /* None */, "__missing"); } else { // Check and see if the symbol table already has a symbol with this name. If not, // create a new symbol with this name and add it to the table. Note that we don't // give the new symbol any flags *yet*. This ensures that it will not conflict // with the 'excludes' flags we pass in. // // If we do get an existing symbol, see if it conflicts with the new symbol we're // creating. For example, a 'var' symbol and a 'class' symbol will conflict within // the same symbol table. If we have a conflict, report the issue on each // declaration we have for this symbol, and then create a new symbol for this // declaration. // // Note that when properties declared in Javascript constructors // (marked by isReplaceableByMethod) conflict with another symbol, the property loses. // Always. This allows the common Javascript pattern of overwriting a prototype method // with an bound instance method of the same type: `this.method = this.method.bind(this)` // // If we created a new symbol, either because we didn't have a symbol with this name // in the symbol table, or we conflicted with an existing symbol, then just add this // node as the sole declaration of the new symbol. // // Otherwise, we'll be merging into a compatible existing symbol (for example when // you have multiple 'vars' with the same name in the same container). In this case // just add this node into the declarations list of the symbol. symbol = symbolTable[name] || (symbolTable[name] = createSymbol(0 /* None */, name)); if (name && (includes & 788448 /* Classifiable */)) { classifiableNames[name] = name; } if (symbol.flags & excludes) { if (symbol.isReplaceableByMethod) { // Javascript constructor-declared symbols can be discarded in favor of // prototype symbols like methods. symbol = symbolTable[name] = createSymbol(0 /* None */, name); } else { if (node.name) { node.name.parent = node; } // Report errors every position with duplicate declaration // Report errors on previous encountered declarations var message_1 = symbol.flags & 2 /* BlockScopedVariable */ ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 : ts.Diagnostics.Duplicate_identifier_0; ts.forEach(symbol.declarations, function (declaration) { if (declaration.flags & 512 /* Default */) { message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; } }); ts.forEach(symbol.declarations, function (declaration) { file.bindDiagnostics.push(ts.createDiagnosticForNode(declaration.name || declaration, message_1, getDisplayName(declaration))); }); file.bindDiagnostics.push(ts.createDiagnosticForNode(node.name || node, message_1, getDisplayName(node))); symbol = createSymbol(0 /* None */, name); } } } addDeclarationToSymbol(symbol, node, includes); symbol.parent = parent; return symbol; }
[ "function", "declareSymbol", "(", "symbolTable", ",", "parent", ",", "node", ",", "includes", ",", "excludes", ")", "{", "ts", ".", "Debug", ".", "assert", "(", "!", "ts", ".", "hasDynamicName", "(", "node", ")", ")", ";", "var", "isDefaultExport", "=", "node", ".", "flags", "&", "512", ";", "var", "name", "=", "isDefaultExport", "&&", "parent", "?", "\"default\"", ":", "getDeclarationName", "(", "node", ")", ";", "var", "symbol", ";", "if", "(", "name", "===", "undefined", ")", "{", "symbol", "=", "createSymbol", "(", "0", ",", "\"__missing\"", ")", ";", "}", "else", "{", "symbol", "=", "symbolTable", "[", "name", "]", "||", "(", "symbolTable", "[", "name", "]", "=", "createSymbol", "(", "0", ",", "name", ")", ")", ";", "if", "(", "name", "&&", "(", "includes", "&", "788448", ")", ")", "{", "classifiableNames", "[", "name", "]", "=", "name", ";", "}", "if", "(", "symbol", ".", "flags", "&", "excludes", ")", "{", "if", "(", "symbol", ".", "isReplaceableByMethod", ")", "{", "symbol", "=", "symbolTable", "[", "name", "]", "=", "createSymbol", "(", "0", ",", "name", ")", ";", "}", "else", "{", "if", "(", "node", ".", "name", ")", "{", "node", ".", "name", ".", "parent", "=", "node", ";", "}", "var", "message_1", "=", "symbol", ".", "flags", "&", "2", "?", "ts", ".", "Diagnostics", ".", "Cannot_redeclare_block_scoped_variable_0", ":", "ts", ".", "Diagnostics", ".", "Duplicate_identifier_0", ";", "ts", ".", "forEach", "(", "symbol", ".", "declarations", ",", "function", "(", "declaration", ")", "{", "if", "(", "declaration", ".", "flags", "&", "512", ")", "{", "message_1", "=", "ts", ".", "Diagnostics", ".", "A_module_cannot_have_multiple_default_exports", ";", "}", "}", ")", ";", "ts", ".", "forEach", "(", "symbol", ".", "declarations", ",", "function", "(", "declaration", ")", "{", "file", ".", "bindDiagnostics", ".", "push", "(", "ts", ".", "createDiagnosticForNode", "(", "declaration", ".", "name", "||", "declaration", ",", "message_1", ",", "getDisplayName", "(", "declaration", ")", ")", ")", ";", "}", ")", ";", "file", ".", "bindDiagnostics", ".", "push", "(", "ts", ".", "createDiagnosticForNode", "(", "node", ".", "name", "||", "node", ",", "message_1", ",", "getDisplayName", "(", "node", ")", ")", ")", ";", "symbol", "=", "createSymbol", "(", "0", ",", "name", ")", ";", "}", "}", "}", "addDeclarationToSymbol", "(", "symbol", ",", "node", ",", "includes", ")", ";", "symbol", ".", "parent", "=", "parent", ";", "return", "symbol", ";", "}" ]
Declares a Symbol for the node and adds it to symbols. Reports errors for conflicting identifier names. @param symbolTable - The symbol table which node will be added to. @param parent - node's parent declaration. @param node - The declaration to be added to the symbol table @param includes - The SymbolFlags that node has in addition to its declaration type (eg: export, ambient, etc.) @param excludes - The flags which node cannot be declared alongside in a symbol table. Used to report forbidden declarations.
[ "Declares", "a", "Symbol", "for", "the", "node", "and", "adds", "it", "to", "symbols", ".", "Reports", "errors", "for", "conflicting", "identifier", "names", "." ]
c0cd5250a573689a8bcd9733b958d4215b0ecfa4
https://github.com/opendigitaleducation/sijil.js/blob/c0cd5250a573689a8bcd9733b958d4215b0ecfa4/docs/libs/typescript.js#L15353-L15421
train
opendigitaleducation/sijil.js
docs/libs/typescript.js
bindContainer
function bindContainer(node, containerFlags) { // Before we recurse into a node's children, we first save the existing parent, container // and block-container. Then after we pop out of processing the children, we restore // these saved values. var saveContainer = container; var savedBlockScopeContainer = blockScopeContainer; // Depending on what kind of node this is, we may have to adjust the current container // and block-container. If the current node is a container, then it is automatically // considered the current block-container as well. Also, for containers that we know // may contain locals, we proactively initialize the .locals field. We do this because // it's highly likely that the .locals will be needed to place some child in (for example, // a parameter, or variable declaration). // // However, we do not proactively create the .locals for block-containers because it's // totally normal and common for block-containers to never actually have a block-scoped // variable in them. We don't want to end up allocating an object for every 'block' we // run into when most of them won't be necessary. // // Finally, if this is a block-container, then we clear out any existing .locals object // it may contain within it. This happens in incremental scenarios. Because we can be // reusing a node from a previous compilation, that node may have had 'locals' created // for it. We must clear this so we don't accidentally move any stale data forward from // a previous compilation. if (containerFlags & 1 /* IsContainer */) { container = blockScopeContainer = node; if (containerFlags & 32 /* HasLocals */) { container.locals = ts.createMap(); } addToContainerChain(container); } else if (containerFlags & 2 /* IsBlockScopedContainer */) { blockScopeContainer = node; blockScopeContainer.locals = undefined; } if (containerFlags & 4 /* IsControlFlowContainer */) { var saveCurrentFlow = currentFlow; var saveBreakTarget = currentBreakTarget; var saveContinueTarget = currentContinueTarget; var saveReturnTarget = currentReturnTarget; var saveActiveLabels = activeLabels; var saveHasExplicitReturn = hasExplicitReturn; var isIIFE = containerFlags & 16 /* IsFunctionExpression */ && !!ts.getImmediatelyInvokedFunctionExpression(node); // An IIFE is considered part of the containing control flow. Return statements behave // similarly to break statements that exit to a label just past the statement body. if (isIIFE) { currentReturnTarget = createBranchLabel(); } else { currentFlow = { flags: 2 /* Start */ }; if (containerFlags & 16 /* IsFunctionExpression */) { currentFlow.container = node; } currentReturnTarget = undefined; } currentBreakTarget = undefined; currentContinueTarget = undefined; activeLabels = undefined; hasExplicitReturn = false; bindChildren(node); // Reset all reachability check related flags on node (for incremental scenarios) // Reset all emit helper flags on node (for incremental scenarios) node.flags &= ~4030464 /* ReachabilityAndEmitFlags */; if (!(currentFlow.flags & 1 /* Unreachable */) && containerFlags & 8 /* IsFunctionLike */ && ts.nodeIsPresent(node.body)) { node.flags |= 32768 /* HasImplicitReturn */; if (hasExplicitReturn) node.flags |= 65536 /* HasExplicitReturn */; } if (node.kind === 256 /* SourceFile */) { node.flags |= emitFlags; } if (isIIFE) { addAntecedent(currentReturnTarget, currentFlow); currentFlow = finishFlowLabel(currentReturnTarget); } else { currentFlow = saveCurrentFlow; } currentBreakTarget = saveBreakTarget; currentContinueTarget = saveContinueTarget; currentReturnTarget = saveReturnTarget; activeLabels = saveActiveLabels; hasExplicitReturn = saveHasExplicitReturn; } else if (containerFlags & 64 /* IsInterface */) { seenThisKeyword = false; bindChildren(node); node.flags = seenThisKeyword ? node.flags | 16384 /* ContainsThis */ : node.flags & ~16384 /* ContainsThis */; } else { bindChildren(node); } container = saveContainer; blockScopeContainer = savedBlockScopeContainer; }
javascript
function bindContainer(node, containerFlags) { // Before we recurse into a node's children, we first save the existing parent, container // and block-container. Then after we pop out of processing the children, we restore // these saved values. var saveContainer = container; var savedBlockScopeContainer = blockScopeContainer; // Depending on what kind of node this is, we may have to adjust the current container // and block-container. If the current node is a container, then it is automatically // considered the current block-container as well. Also, for containers that we know // may contain locals, we proactively initialize the .locals field. We do this because // it's highly likely that the .locals will be needed to place some child in (for example, // a parameter, or variable declaration). // // However, we do not proactively create the .locals for block-containers because it's // totally normal and common for block-containers to never actually have a block-scoped // variable in them. We don't want to end up allocating an object for every 'block' we // run into when most of them won't be necessary. // // Finally, if this is a block-container, then we clear out any existing .locals object // it may contain within it. This happens in incremental scenarios. Because we can be // reusing a node from a previous compilation, that node may have had 'locals' created // for it. We must clear this so we don't accidentally move any stale data forward from // a previous compilation. if (containerFlags & 1 /* IsContainer */) { container = blockScopeContainer = node; if (containerFlags & 32 /* HasLocals */) { container.locals = ts.createMap(); } addToContainerChain(container); } else if (containerFlags & 2 /* IsBlockScopedContainer */) { blockScopeContainer = node; blockScopeContainer.locals = undefined; } if (containerFlags & 4 /* IsControlFlowContainer */) { var saveCurrentFlow = currentFlow; var saveBreakTarget = currentBreakTarget; var saveContinueTarget = currentContinueTarget; var saveReturnTarget = currentReturnTarget; var saveActiveLabels = activeLabels; var saveHasExplicitReturn = hasExplicitReturn; var isIIFE = containerFlags & 16 /* IsFunctionExpression */ && !!ts.getImmediatelyInvokedFunctionExpression(node); // An IIFE is considered part of the containing control flow. Return statements behave // similarly to break statements that exit to a label just past the statement body. if (isIIFE) { currentReturnTarget = createBranchLabel(); } else { currentFlow = { flags: 2 /* Start */ }; if (containerFlags & 16 /* IsFunctionExpression */) { currentFlow.container = node; } currentReturnTarget = undefined; } currentBreakTarget = undefined; currentContinueTarget = undefined; activeLabels = undefined; hasExplicitReturn = false; bindChildren(node); // Reset all reachability check related flags on node (for incremental scenarios) // Reset all emit helper flags on node (for incremental scenarios) node.flags &= ~4030464 /* ReachabilityAndEmitFlags */; if (!(currentFlow.flags & 1 /* Unreachable */) && containerFlags & 8 /* IsFunctionLike */ && ts.nodeIsPresent(node.body)) { node.flags |= 32768 /* HasImplicitReturn */; if (hasExplicitReturn) node.flags |= 65536 /* HasExplicitReturn */; } if (node.kind === 256 /* SourceFile */) { node.flags |= emitFlags; } if (isIIFE) { addAntecedent(currentReturnTarget, currentFlow); currentFlow = finishFlowLabel(currentReturnTarget); } else { currentFlow = saveCurrentFlow; } currentBreakTarget = saveBreakTarget; currentContinueTarget = saveContinueTarget; currentReturnTarget = saveReturnTarget; activeLabels = saveActiveLabels; hasExplicitReturn = saveHasExplicitReturn; } else if (containerFlags & 64 /* IsInterface */) { seenThisKeyword = false; bindChildren(node); node.flags = seenThisKeyword ? node.flags | 16384 /* ContainsThis */ : node.flags & ~16384 /* ContainsThis */; } else { bindChildren(node); } container = saveContainer; blockScopeContainer = savedBlockScopeContainer; }
[ "function", "bindContainer", "(", "node", ",", "containerFlags", ")", "{", "var", "saveContainer", "=", "container", ";", "var", "savedBlockScopeContainer", "=", "blockScopeContainer", ";", "if", "(", "containerFlags", "&", "1", ")", "{", "container", "=", "blockScopeContainer", "=", "node", ";", "if", "(", "containerFlags", "&", "32", ")", "{", "container", ".", "locals", "=", "ts", ".", "createMap", "(", ")", ";", "}", "addToContainerChain", "(", "container", ")", ";", "}", "else", "if", "(", "containerFlags", "&", "2", ")", "{", "blockScopeContainer", "=", "node", ";", "blockScopeContainer", ".", "locals", "=", "undefined", ";", "}", "if", "(", "containerFlags", "&", "4", ")", "{", "var", "saveCurrentFlow", "=", "currentFlow", ";", "var", "saveBreakTarget", "=", "currentBreakTarget", ";", "var", "saveContinueTarget", "=", "currentContinueTarget", ";", "var", "saveReturnTarget", "=", "currentReturnTarget", ";", "var", "saveActiveLabels", "=", "activeLabels", ";", "var", "saveHasExplicitReturn", "=", "hasExplicitReturn", ";", "var", "isIIFE", "=", "containerFlags", "&", "16", "&&", "!", "!", "ts", ".", "getImmediatelyInvokedFunctionExpression", "(", "node", ")", ";", "if", "(", "isIIFE", ")", "{", "currentReturnTarget", "=", "createBranchLabel", "(", ")", ";", "}", "else", "{", "currentFlow", "=", "{", "flags", ":", "2", "}", ";", "if", "(", "containerFlags", "&", "16", ")", "{", "currentFlow", ".", "container", "=", "node", ";", "}", "currentReturnTarget", "=", "undefined", ";", "}", "currentBreakTarget", "=", "undefined", ";", "currentContinueTarget", "=", "undefined", ";", "activeLabels", "=", "undefined", ";", "hasExplicitReturn", "=", "false", ";", "bindChildren", "(", "node", ")", ";", "node", ".", "flags", "&=", "~", "4030464", ";", "if", "(", "!", "(", "currentFlow", ".", "flags", "&", "1", ")", "&&", "containerFlags", "&", "8", "&&", "ts", ".", "nodeIsPresent", "(", "node", ".", "body", ")", ")", "{", "node", ".", "flags", "|=", "32768", ";", "if", "(", "hasExplicitReturn", ")", "node", ".", "flags", "|=", "65536", ";", "}", "if", "(", "node", ".", "kind", "===", "256", ")", "{", "node", ".", "flags", "|=", "emitFlags", ";", "}", "if", "(", "isIIFE", ")", "{", "addAntecedent", "(", "currentReturnTarget", ",", "currentFlow", ")", ";", "currentFlow", "=", "finishFlowLabel", "(", "currentReturnTarget", ")", ";", "}", "else", "{", "currentFlow", "=", "saveCurrentFlow", ";", "}", "currentBreakTarget", "=", "saveBreakTarget", ";", "currentContinueTarget", "=", "saveContinueTarget", ";", "currentReturnTarget", "=", "saveReturnTarget", ";", "activeLabels", "=", "saveActiveLabels", ";", "hasExplicitReturn", "=", "saveHasExplicitReturn", ";", "}", "else", "if", "(", "containerFlags", "&", "64", ")", "{", "seenThisKeyword", "=", "false", ";", "bindChildren", "(", "node", ")", ";", "node", ".", "flags", "=", "seenThisKeyword", "?", "node", ".", "flags", "|", "16384", ":", "node", ".", "flags", "&", "~", "16384", ";", "}", "else", "{", "bindChildren", "(", "node", ")", ";", "}", "container", "=", "saveContainer", ";", "blockScopeContainer", "=", "savedBlockScopeContainer", ";", "}" ]
All container nodes are kept on a linked list in declaration order. This list is used by the getLocalNameOfContainer function in the type checker to validate that the local name used for a container is unique.
[ "All", "container", "nodes", "are", "kept", "on", "a", "linked", "list", "in", "declaration", "order", ".", "This", "list", "is", "used", "by", "the", "getLocalNameOfContainer", "function", "in", "the", "type", "checker", "to", "validate", "that", "the", "local", "name", "used", "for", "a", "container", "is", "unique", "." ]
c0cd5250a573689a8bcd9733b958d4215b0ecfa4
https://github.com/opendigitaleducation/sijil.js/blob/c0cd5250a573689a8bcd9733b958d4215b0ecfa4/docs/libs/typescript.js#L15465-L15558
train
opendigitaleducation/sijil.js
docs/libs/typescript.js
checkStrictModeIdentifier
function checkStrictModeIdentifier(node) { if (inStrictMode && node.originalKeywordKind >= 106 /* FirstFutureReservedWord */ && node.originalKeywordKind <= 114 /* LastFutureReservedWord */ && !ts.isIdentifierName(node) && !ts.isInAmbientContext(node)) { // Report error only if there are no parse errors in file if (!file.parseDiagnostics.length) { file.bindDiagnostics.push(ts.createDiagnosticForNode(node, getStrictModeIdentifierMessage(node), ts.declarationNameToString(node))); } } }
javascript
function checkStrictModeIdentifier(node) { if (inStrictMode && node.originalKeywordKind >= 106 /* FirstFutureReservedWord */ && node.originalKeywordKind <= 114 /* LastFutureReservedWord */ && !ts.isIdentifierName(node) && !ts.isInAmbientContext(node)) { // Report error only if there are no parse errors in file if (!file.parseDiagnostics.length) { file.bindDiagnostics.push(ts.createDiagnosticForNode(node, getStrictModeIdentifierMessage(node), ts.declarationNameToString(node))); } } }
[ "function", "checkStrictModeIdentifier", "(", "node", ")", "{", "if", "(", "inStrictMode", "&&", "node", ".", "originalKeywordKind", ">=", "106", "&&", "node", ".", "originalKeywordKind", "<=", "114", "&&", "!", "ts", ".", "isIdentifierName", "(", "node", ")", "&&", "!", "ts", ".", "isInAmbientContext", "(", "node", ")", ")", "{", "if", "(", "!", "file", ".", "parseDiagnostics", ".", "length", ")", "{", "file", ".", "bindDiagnostics", ".", "push", "(", "ts", ".", "createDiagnosticForNode", "(", "node", ",", "getStrictModeIdentifierMessage", "(", "node", ")", ",", "ts", ".", "declarationNameToString", "(", "node", ")", ")", ")", ";", "}", "}", "}" ]
The binder visits every node in the syntax tree so it is a convenient place to perform a single localized check for reserved words used as identifiers in strict mode code.
[ "The", "binder", "visits", "every", "node", "in", "the", "syntax", "tree", "so", "it", "is", "a", "convenient", "place", "to", "perform", "a", "single", "localized", "check", "for", "reserved", "words", "used", "as", "identifiers", "in", "strict", "mode", "code", "." ]
c0cd5250a573689a8bcd9733b958d4215b0ecfa4
https://github.com/opendigitaleducation/sijil.js/blob/c0cd5250a573689a8bcd9733b958d4215b0ecfa4/docs/libs/typescript.js#L16458-L16469
train
opendigitaleducation/sijil.js
docs/libs/typescript.js
getSymbolsOfParameterPropertyDeclaration
function getSymbolsOfParameterPropertyDeclaration(parameter, parameterName) { var constructorDeclaration = parameter.parent; var classDeclaration = parameter.parent.parent; var parameterSymbol = getSymbol(constructorDeclaration.locals, parameterName, 107455 /* Value */); var propertySymbol = getSymbol(classDeclaration.symbol.members, parameterName, 107455 /* Value */); if (parameterSymbol && propertySymbol) { return [parameterSymbol, propertySymbol]; } ts.Debug.fail("There should exist two symbols, one as property declaration and one as parameter declaration"); }
javascript
function getSymbolsOfParameterPropertyDeclaration(parameter, parameterName) { var constructorDeclaration = parameter.parent; var classDeclaration = parameter.parent.parent; var parameterSymbol = getSymbol(constructorDeclaration.locals, parameterName, 107455 /* Value */); var propertySymbol = getSymbol(classDeclaration.symbol.members, parameterName, 107455 /* Value */); if (parameterSymbol && propertySymbol) { return [parameterSymbol, propertySymbol]; } ts.Debug.fail("There should exist two symbols, one as property declaration and one as parameter declaration"); }
[ "function", "getSymbolsOfParameterPropertyDeclaration", "(", "parameter", ",", "parameterName", ")", "{", "var", "constructorDeclaration", "=", "parameter", ".", "parent", ";", "var", "classDeclaration", "=", "parameter", ".", "parent", ".", "parent", ";", "var", "parameterSymbol", "=", "getSymbol", "(", "constructorDeclaration", ".", "locals", ",", "parameterName", ",", "107455", ")", ";", "var", "propertySymbol", "=", "getSymbol", "(", "classDeclaration", ".", "symbol", ".", "members", ",", "parameterName", ",", "107455", ")", ";", "if", "(", "parameterSymbol", "&&", "propertySymbol", ")", "{", "return", "[", "parameterSymbol", ",", "propertySymbol", "]", ";", "}", "ts", ".", "Debug", ".", "fail", "(", "\"There should exist two symbols, one as property declaration and one as parameter declaration\"", ")", ";", "}" ]
Get symbols that represent parameter-property-declaration as parameter and as property declaration @param parameter a parameterDeclaration node @param parameterName a name of the parameter to get the symbols for. @return a tuple of two symbols
[ "Get", "symbols", "that", "represent", "parameter", "-", "property", "-", "declaration", "as", "parameter", "and", "as", "property", "declaration" ]
c0cd5250a573689a8bcd9733b958d4215b0ecfa4
https://github.com/opendigitaleducation/sijil.js/blob/c0cd5250a573689a8bcd9733b958d4215b0ecfa4/docs/libs/typescript.js#L17648-L17657
train
opendigitaleducation/sijil.js
docs/libs/typescript.js
getEntityNameForExtendingInterface
function getEntityNameForExtendingInterface(node) { switch (node.kind) { case 69 /* Identifier */: case 172 /* PropertyAccessExpression */: return node.parent ? getEntityNameForExtendingInterface(node.parent) : undefined; case 194 /* ExpressionWithTypeArguments */: ts.Debug.assert(ts.isEntityNameExpression(node.expression)); return node.expression; default: return undefined; } }
javascript
function getEntityNameForExtendingInterface(node) { switch (node.kind) { case 69 /* Identifier */: case 172 /* PropertyAccessExpression */: return node.parent ? getEntityNameForExtendingInterface(node.parent) : undefined; case 194 /* ExpressionWithTypeArguments */: ts.Debug.assert(ts.isEntityNameExpression(node.expression)); return node.expression; default: return undefined; } }
[ "function", "getEntityNameForExtendingInterface", "(", "node", ")", "{", "switch", "(", "node", ".", "kind", ")", "{", "case", "69", ":", "case", "172", ":", "return", "node", ".", "parent", "?", "getEntityNameForExtendingInterface", "(", "node", ".", "parent", ")", ":", "undefined", ";", "case", "194", ":", "ts", ".", "Debug", ".", "assert", "(", "ts", ".", "isEntityNameExpression", "(", "node", ".", "expression", ")", ")", ";", "return", "node", ".", "expression", ";", "default", ":", "return", "undefined", ";", "}", "}" ]
Climbs up parents to an ExpressionWithTypeArguments, and returns its expression, but returns undefined if that expression is not an EntityNameExpression.
[ "Climbs", "up", "parents", "to", "an", "ExpressionWithTypeArguments", "and", "returns", "its", "expression", "but", "returns", "undefined", "if", "that", "expression", "is", "not", "an", "EntityNameExpression", "." ]
c0cd5250a573689a8bcd9733b958d4215b0ecfa4
https://github.com/opendigitaleducation/sijil.js/blob/c0cd5250a573689a8bcd9733b958d4215b0ecfa4/docs/libs/typescript.js#L18019-L18030
train
opendigitaleducation/sijil.js
docs/libs/typescript.js
getSymbolOfPartOfRightHandSideOfImportEquals
function getSymbolOfPartOfRightHandSideOfImportEquals(entityName, importDeclaration, dontResolveAlias) { // There are three things we might try to look for. In the following examples, // the search term is enclosed in |...|: // // import a = |b|; // Namespace // import a = |b.c|; // Value, type, namespace // import a = |b.c|.d; // Namespace if (entityName.kind === 69 /* Identifier */ && ts.isRightSideOfQualifiedNameOrPropertyAccess(entityName)) { entityName = entityName.parent; } // Check for case 1 and 3 in the above example if (entityName.kind === 69 /* Identifier */ || entityName.parent.kind === 139 /* QualifiedName */) { return resolveEntityName(entityName, 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); } else { // Case 2 in above example // entityName.kind could be a QualifiedName or a Missing identifier ts.Debug.assert(entityName.parent.kind === 229 /* ImportEqualsDeclaration */); return resolveEntityName(entityName, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); } }
javascript
function getSymbolOfPartOfRightHandSideOfImportEquals(entityName, importDeclaration, dontResolveAlias) { // There are three things we might try to look for. In the following examples, // the search term is enclosed in |...|: // // import a = |b|; // Namespace // import a = |b.c|; // Value, type, namespace // import a = |b.c|.d; // Namespace if (entityName.kind === 69 /* Identifier */ && ts.isRightSideOfQualifiedNameOrPropertyAccess(entityName)) { entityName = entityName.parent; } // Check for case 1 and 3 in the above example if (entityName.kind === 69 /* Identifier */ || entityName.parent.kind === 139 /* QualifiedName */) { return resolveEntityName(entityName, 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); } else { // Case 2 in above example // entityName.kind could be a QualifiedName or a Missing identifier ts.Debug.assert(entityName.parent.kind === 229 /* ImportEqualsDeclaration */); return resolveEntityName(entityName, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); } }
[ "function", "getSymbolOfPartOfRightHandSideOfImportEquals", "(", "entityName", ",", "importDeclaration", ",", "dontResolveAlias", ")", "{", "if", "(", "entityName", ".", "kind", "===", "69", "&&", "ts", ".", "isRightSideOfQualifiedNameOrPropertyAccess", "(", "entityName", ")", ")", "{", "entityName", "=", "entityName", ".", "parent", ";", "}", "if", "(", "entityName", ".", "kind", "===", "69", "||", "entityName", ".", "parent", ".", "kind", "===", "139", ")", "{", "return", "resolveEntityName", "(", "entityName", ",", "1920", ",", "false", ",", "dontResolveAlias", ")", ";", "}", "else", "{", "ts", ".", "Debug", ".", "assert", "(", "entityName", ".", "parent", ".", "kind", "===", "229", ")", ";", "return", "resolveEntityName", "(", "entityName", ",", "107455", "|", "793064", "|", "1920", ",", "false", ",", "dontResolveAlias", ")", ";", "}", "}" ]
This function is only for imports with entity names
[ "This", "function", "is", "only", "for", "imports", "with", "entity", "names" ]
c0cd5250a573689a8bcd9733b958d4215b0ecfa4
https://github.com/opendigitaleducation/sijil.js/blob/c0cd5250a573689a8bcd9733b958d4215b0ecfa4/docs/libs/typescript.js#L18269-L18289
train
opendigitaleducation/sijil.js
docs/libs/typescript.js
extendExportSymbols
function extendExportSymbols(target, source, lookupTable, exportNode) { for (var id in source) { if (id !== "default" && !target[id]) { target[id] = source[id]; if (lookupTable && exportNode) { lookupTable[id] = { specifierText: ts.getTextOfNode(exportNode.moduleSpecifier) }; } } else if (lookupTable && exportNode && id !== "default" && target[id] && resolveSymbol(target[id]) !== resolveSymbol(source[id])) { if (!lookupTable[id].exportsWithDuplicate) { lookupTable[id].exportsWithDuplicate = [exportNode]; } else { lookupTable[id].exportsWithDuplicate.push(exportNode); } } } }
javascript
function extendExportSymbols(target, source, lookupTable, exportNode) { for (var id in source) { if (id !== "default" && !target[id]) { target[id] = source[id]; if (lookupTable && exportNode) { lookupTable[id] = { specifierText: ts.getTextOfNode(exportNode.moduleSpecifier) }; } } else if (lookupTable && exportNode && id !== "default" && target[id] && resolveSymbol(target[id]) !== resolveSymbol(source[id])) { if (!lookupTable[id].exportsWithDuplicate) { lookupTable[id].exportsWithDuplicate = [exportNode]; } else { lookupTable[id].exportsWithDuplicate.push(exportNode); } } } }
[ "function", "extendExportSymbols", "(", "target", ",", "source", ",", "lookupTable", ",", "exportNode", ")", "{", "for", "(", "var", "id", "in", "source", ")", "{", "if", "(", "id", "!==", "\"default\"", "&&", "!", "target", "[", "id", "]", ")", "{", "target", "[", "id", "]", "=", "source", "[", "id", "]", ";", "if", "(", "lookupTable", "&&", "exportNode", ")", "{", "lookupTable", "[", "id", "]", "=", "{", "specifierText", ":", "ts", ".", "getTextOfNode", "(", "exportNode", ".", "moduleSpecifier", ")", "}", ";", "}", "}", "else", "if", "(", "lookupTable", "&&", "exportNode", "&&", "id", "!==", "\"default\"", "&&", "target", "[", "id", "]", "&&", "resolveSymbol", "(", "target", "[", "id", "]", ")", "!==", "resolveSymbol", "(", "source", "[", "id", "]", ")", ")", "{", "if", "(", "!", "lookupTable", "[", "id", "]", ".", "exportsWithDuplicate", ")", "{", "lookupTable", "[", "id", "]", ".", "exportsWithDuplicate", "=", "[", "exportNode", "]", ";", "}", "else", "{", "lookupTable", "[", "id", "]", ".", "exportsWithDuplicate", ".", "push", "(", "exportNode", ")", ";", "}", "}", "}", "}" ]
Extends one symbol table with another while collecting information on name collisions for error message generation into the `lookupTable` argument Not passing `lookupTable` and `exportNode` disables this collection, and just extends the tables
[ "Extends", "one", "symbol", "table", "with", "another", "while", "collecting", "information", "on", "name", "collisions", "for", "error", "message", "generation", "into", "the", "lookupTable", "argument", "Not", "passing", "lookupTable", "and", "exportNode", "disables", "this", "collection", "and", "just", "extends", "the", "tables" ]
c0cd5250a573689a8bcd9733b958d4215b0ecfa4
https://github.com/opendigitaleducation/sijil.js/blob/c0cd5250a573689a8bcd9733b958d4215b0ecfa4/docs/libs/typescript.js#L18417-L18436
train