_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q48900
parseNode
train
function parseNode(sourceNode, sourceFile, sourceCode, state) { // static nodes have no bindings if (isStaticNode(sourceNode)) return [nodeToString(sourceNode), []] return createDynamicNode(sourceNode, sourceFile, sourceCode, state) }
javascript
{ "resource": "" }
q48901
createAttributeExpressions
train
function createAttributeExpressions(sourceNode, sourceFile, sourceCode) { return findDynamicAttributes(sourceNode) .map(attribute => createExpression(attribute, sourceFile, sourceCode)) }
javascript
{ "resource": "" }
q48902
createTextNodeExpressions
train
function createTextNodeExpressions(sourceNode, sourceFile, sourceCode) { const childrenNodes = getChildrenNodes(sourceNode) return childrenNodes .filter(isTextNode) .filter(hasExpressions) .map(node => createExpression( node, sourceFile, sourceCode, childrenNodes.indexOf(node) )) }
javascript
{ "resource": "" }
q48903
extendTemplateProperty
train
function extendTemplateProperty(ast, sourceFile, sourceCode, sourceNode) { types.visit(ast, { visitProperty(path) { if (path.value.key.value === TAG_TEMPLATE_PROPERTY) { path.value.value = builders.functionExpression( null, [ TEMPLATE_FN, EXPRESSION_TYPES, BINDING_TYPES, GET_COMPONENT_FN ].map(builders.identifier), builders.blockStatement([ builders.returnStatement( callTemplateFunction( ...build( createRootNode(sourceNode), sourceFile, sourceCode ) ) ) ]) ) return false } this.traverse(path) } }) return ast }
javascript
{ "resource": "" }
q48904
extendTagProperty
train
function extendTagProperty(ast, exportDefaultNode) { types.visit(ast, { visitProperty(path) { if (path.value.key.value === TAG_LOGIC_PROPERTY) { path.value.value = exportDefaultNode.declaration return false } this.traverse(path) } }) return ast }
javascript
{ "resource": "" }
q48905
groupSlots
train
function groupSlots(sourceNode) { return getChildrenNodes(sourceNode).reduce((acc, node) => { const slotAttribute = findSlotAttribute(node) if (slotAttribute) { acc[slotAttribute.value] = node } else { acc.default = createRootNode({ nodes: [...getChildrenNodes(acc.default), node] }) } return acc }, { default: null }) }
javascript
{ "resource": "" }
q48906
buildSlot
train
function buildSlot(id, sourceNode, sourceFile, sourceCode) { const cloneNode = { ...sourceNode, // avoid to render the slot attribute attributes: getNodeAttributes(sourceNode).filter(attribute => attribute.name !== SLOT_ATTRIBUTE) } const [html, bindings] = build(cloneNode, sourceFile, sourceCode) return builders.objectExpression([ simplePropertyNode(BINDING_ID_KEY, builders.literal(id)), simplePropertyNode(BINDING_HTML_KEY, builders.literal(html)), simplePropertyNode(BINDING_BINDINGS_KEY, builders.arrayExpression(bindings)) ]) }
javascript
{ "resource": "" }
q48907
generateLiteralStringChunksFromNode
train
function generateLiteralStringChunksFromNode(node, sourceCode) { return node.expressions.reduce((chunks, expression, index) => { const start = index ? node.expressions[index - 1].end : node.start chunks.push(sourceCode.substring(start, expression.start)) // add the tail to the string if (index === node.expressions.length - 1) chunks.push(sourceCode.substring(expression.end, node.end)) return chunks }, []).map(str => node.unescape ? unescapeChar(str, node.unescape) : str) }
javascript
{ "resource": "" }
q48908
replacePathScope
train
function replacePathScope(path, property) { path.replace(builders.memberExpression( scope, property, false )) }
javascript
{ "resource": "" }
q48909
updateNodeScope
train
function updateNodeScope(path) { if (!isGlobal(path)) { replacePathScope(path, path.node) return false } this.traverse(path) }
javascript
{ "resource": "" }
q48910
visitMemberExpression
train
function visitMemberExpression(path) { if (!isGlobal({ node: path.node.object, scope: path.scope })) { replacePathScope(path, isThisExpression(path.node.object) ? path.node.property : path.node) } return false }
javascript
{ "resource": "" }
q48911
visitProperty
train
function visitProperty(path) { const value = path.node.value if (isIdentifier(value)) { updateNodeScope(path.get('value')) } else { this.traverse(path.get('value')) } return false }
javascript
{ "resource": "" }
q48912
createMeta
train
function createMeta(source, options) { return { tagName: null, fragments: null, options: { ...DEFAULT_OPTIONS, ...options }, source } }
javascript
{ "resource": "" }
q48913
hookGenerator
train
function hookGenerator(transformer, sourceNode, source, meta) { if ( // filter missing nodes !sourceNode || // filter nodes without children (sourceNode.nodes && !sourceNode.nodes.length) || // filter empty javascript and css nodes (!sourceNode.nodes && !sourceNode.text)) { return result => result } return curry(transformer)(sourceNode, source, meta) }
javascript
{ "resource": "" }
q48914
processHTML
train
function processHTML(cssSelectors = [], htmlDataIn = null, htmlOptionsIn = null) { //read html files if (OPTIONS.html !== '' && OPTIONS.html !== undefined && OPTIONS.special_reduce_with_html) { var htmlFiles = OPTIONS.html; tmpHTMLPaths = []; //check for file or files switch (typeof htmlFiles) { case 'object': case 'array': for (i = 0; i < htmlFiles.length; ++i) { getFilePaths(htmlFiles[i], ['.html','.htm']); } if (tmpHTMLPaths.length) { htmlFiles = tmpHTMLPaths; } break; case 'string': //formats htmlFiles = htmlFiles.replace(/ /g, ''); // comma delimited list - filename1.html, filename2.html if (htmlFiles.indexOf(',') > -1) { htmlFiles = htmlFiles.replace(/^\s+|\s+$/g,'').split(','); tmpStr = ''; for (i = 0; i < htmlFiles.length; ++i) { getFilePaths(htmlFiles[i], ['.html','.htm']); } //end of for if (tmpHTMLPaths.length) { htmlFiles = tmpHTMLPaths; } } else { //string path getFilePaths(htmlFiles, ['.html','.htm']); if (tmpHTMLPaths.length) { htmlFiles = tmpHTMLPaths; } } break; } //end of switch htmlFileLocation = (htmlFiles)?htmlFiles.toString():htmlFiles; readHTMLFile(htmlFiles); CPEVENTS.on('HTML_READ_AGAIN', function(){ //process selectors processHTMLSelectors(cssSelectors, htmlDataIn, htmlOptionsIn); //read next file dataHTMLIn = []; readHTMLFile(htmlFiles); }); CPEVENTS.on('HTML_READ_END', function(){ //process selectors processHTMLSelectors(cssSelectors, htmlDataIn, htmlOptionsIn); dataHTMLIn = []; CPEVENTS.emit('HTML_RESULTS_END', cssSelectors); }); } //end of html files check }
javascript
{ "resource": "" }
q48915
getFilePaths
train
function getFilePaths(strPath = '', exts = ['.css']) { if (validUrl.isUri(strPath)){ switch(exts[0]) { case '.css': tmpCSSPaths.push(strPath); break; case '.html': case '.htm': tmpHTMLPaths.push(strPath); break; case '.js': tmpJSPaths.push(strPath); break; } } else { try { // Query the entry fileStats = fs.lstatSync(strPath); // directory given if (fileStats.isDirectory()) { var dir = strPath; //traverse directory for .ext strPath try { fs.readdirSync(dir).forEach(filenameRead => { fileFound = false; for (m = 0, count = exts.length; m < count; ++m) { if (path.extname(filenameRead) == exts[m]) { fileFound = true; } } if (fileFound) { switch(exts[0]) { case '.css': tmpCSSPaths.push(dir + '/' + filenameRead); break; case '.html': case '.htm': tmpHTMLPaths.push(dir + '/' + filenameRead); break; case '.js': tmpJSPaths.push(dir + '/' + filenameRead); break; } } else if (path.extname(filenameRead) == '') { switch(exts[0]) { case '.css': getFilePaths(strPath+'/'+filenameRead, ['.css']); break; case '.html': case '.htm': getFilePaths(strPath+'/'+filenameRead, ['.html','.htm']); break; case '.js': getFilePaths(strPath+'/'+filenameRead, ['.js']); break; } } }); } catch (e) { console.log(error("Directory read error: Something went wrong while reading the directory, check your [html] in " + configFileLocation + " and please try again.")); console.log(e); process.exit(1); } } else if (fileStats.isFile()) { //filepath given if (exts.join(",").indexOf(strPath.substr(strPath.lastIndexOf('.') + 1)) != -1) { switch(exts[0]) { case '.css': tmpCSSPaths.push(strPath); break; case '.html': case '.htm': tmpHTMLPaths.push(strPath); break; case '.js': tmpJSPaths.push(strPath); break; } } } } catch (e) { console.log(error("CSS File read error: Something went wrong while reading the file(s), check your [html] in " + configFileLocation + " and please try again.")); console.log(e); process.exit(1); } } //end of url check }
javascript
{ "resource": "" }
q48916
processRulesReset
train
function processRulesReset() { declarationsNameCounts = null; declarationsValueCounts = null; valKey = null; key = null; declarationsValueCountsCount = null; amountRemoved = 1; duplicate_ids = null; selectorPropertiesList = null; }
javascript
{ "resource": "" }
q48917
train
function(list){ localStorage.setItem(localStorageKey, JSON.stringify(list)); // if we used a real database, we would likely do the below in a callback this.list = list; this.trigger(list); // sends the updated list to all listening components (TodoApp) }
javascript
{ "resource": "" }
q48918
train
function() { var loadedList = localStorage.getItem(localStorageKey); if (!loadedList) { // If no list is in localstorage, start out with a default one this.list = [{ key: todoCounter++, created: new Date(), isComplete: false, label: 'Rule the web' }]; } else { this.list = _.map(JSON.parse(loadedList), function(item) { // just resetting the key property for each todo item item.key = todoCounter++; return item; }); } // Subscribe to RemoteDev RemoteDev.subscribe(state => { this.updateList(state); }); RemoteDev.init(this.list); return this.list; }
javascript
{ "resource": "" }
q48919
getTargetScope
train
function getTargetScope() { var targetElement = scope.ttElement ? angular.element(scope.ttElement) : element; var targetScope = scope; if (targetElement !== element && !scope.ttSourceScope) targetScope = targetElement.scope(); return targetScope; }
javascript
{ "resource": "" }
q48920
recursiveIssuer
train
function recursiveIssuer(module) { if (module.issuer) { return recursiveIssuer(module.issuer); } else if (module.name) { return module.name; } else { return false; } }
javascript
{ "resource": "" }
q48921
readFile
train
function readFile(fileName) { try { return read(fileName); } catch (e) { print(fileName + ': ' + (e.message || e)); throw e; } }
javascript
{ "resource": "" }
q48922
parseState
train
function parseState(s) { switch (s) { case "": return Profile.CodeState.COMPILED; case "~": return Profile.CodeState.OPTIMIZABLE; case "*": return Profile.CodeState.OPTIMIZED; } throw new Error("unknown code state: " + s); }
javascript
{ "resource": "" }
q48923
train
function () { var deferred = Q.defer(); var that = this; this._innerQueryIterator.nextItem(function (error, item, responseHeaders) { if (error) { addOrMergeHeadersForError(error, responseHeaders); deferred.reject(error); } else { deferred.resolve({ resource: item, headers: responseHeaders }); } }); return deferred.promise; }
javascript
{ "resource": "" }
q48924
train
function () { var deferred = Q.defer(); var that = this; this._innerQueryIterator.executeNext(function (error, resources, responseHeaders) { if (error) { addOrMergeHeadersForError(error, responseHeaders); deferred.reject(error); } else { deferred.resolve({ feed: resources, headers: responseHeaders }); } }); return deferred.promise; }
javascript
{ "resource": "" }
q48925
train
function(sprocLink, params, options) { var deferred = Q.defer(); this._innerDocumentclient.executeStoredProcedure(sprocLink, params, options, function (error, result, responseHeaders) { if (error) { addOrMergeHeadersForError(error, responseHeaders); deferred.reject(error); } else { deferred.resolve({result: result, headers: responseHeaders}); } }); return deferred.promise; }
javascript
{ "resource": "" }
q48926
train
function() { var target; $('a[href^="#"]').not('.pldoc-tab-wrapper .pldoc-link').on('click', function(event) { event.preventDefault(); target = $(event.currentTarget).attr('href'); $('html, body').stop().animate({ scrollTop: $(target).offset().top }, 1000, 'swing', function() { Ui.sendFocus(target); }); }); }
javascript
{ "resource": "" }
q48927
range
train
function range(start, end) { return Array(end - start + 1).fill().map(function (_, index) { return start + index; }); }
javascript
{ "resource": "" }
q48928
ObjectID
train
function ObjectID(arg) { if(!(this instanceof ObjectID)) return new ObjectID(arg); if(arg && ((arg instanceof ObjectID) || arg._bsontype==="ObjectID")) return arg; var buf; if(isBuffer(arg) || (Array.isArray(arg) && arg.length===12)) { buf = Array.prototype.slice.call(arg); } else if(typeof arg === "string") { if(arg.length!==12 && !ObjectID.isValid(arg)) throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters"); buf = buffer(arg); } else if(/number|undefined/.test(typeof arg)) { buf = buffer(generate(arg)); } Object.defineProperty(this, "id", { enumerable: true, get: function() { return String.fromCharCode.apply(this, buf); } }); Object.defineProperty(this, "str", { get: function() { return buf.map(hex.bind(this, 2)).join(''); } }); }
javascript
{ "resource": "" }
q48929
apiShowTip
train
function apiShowTip(element, event) { // if we were given a mouse event then run the hover intent testing, // otherwise, simply show the tooltip asap if (isMouseEvent(event)) { trackMouse(event); session.previousX = event.pageX; session.previousY = event.pageY; $(element).data(DATA_DISPLAYCONTROLLER).show(); } else { $(element).first().data(DATA_DISPLAYCONTROLLER).show(true, true); } return element; }
javascript
{ "resource": "" }
q48930
apiCloseTip
train
function apiCloseTip(element, immediate) { var displayController; // set immediate to true when no element is specified immediate = element ? immediate : true; // find the relevant display controller if (element) { displayController = $(element).first().data(DATA_DISPLAYCONTROLLER); } else if (session.activeHover) { displayController = session.activeHover.data(DATA_DISPLAYCONTROLLER); } // if found, hide the tip if (displayController) { displayController.hide(immediate); } return element; }
javascript
{ "resource": "" }
q48931
apiToggle
train
function apiToggle(element, event) { if (session.activeHover && session.activeHover.is(element)) { // tooltip for element is active, so close it $.powerTip.hide(element, !isMouseEvent(event)); } else { // tooltip for element is not active, so open it $.powerTip.show(element, event); } return element; }
javascript
{ "resource": "" }
q48932
train
function () { var collisionEntities; var data = this.data; var el = this.el; if (!data.collisionEntities) { this.collisionEntities = []; return; } collisionEntities = [].slice.call(el.sceneEl.querySelectorAll(data.collisionEntities)); this.collisionEntities = collisionEntities; // Update entity list on attach. this.childAttachHandler = function childAttachHandler (evt) { if (!evt.detail.el.matches(data.collisionEntities)) { return; } collisionEntities.push(evt.detail.el); }; el.sceneEl.addEventListener('child-attached', this.childAttachHandler); // Update entity list on detach. this.childDetachHandler = function childDetachHandler (evt) { var index; if (!evt.detail.el.matches(data.collisionEntities)) { return; } index = collisionEntities.indexOf(evt.detail.el); if (index === -1) { return; } collisionEntities.splice(index, 1); }; el.sceneEl.addEventListener('child-detached', this.childDetachHandler); }
javascript
{ "resource": "" }
q48933
train
function (i, next) { // @todo We should add a property to define if the collisionEntity is dynamic or static // If static we should do the map just once, otherwise we're recreating the array in every // loop when aiming. var meshes; if (!this.data.collisionEntities) { meshes = this.defaultCollisionMeshes; } else { meshes = this.collisionEntities.map(function (entity) { return entity.getObject3D('mesh'); }).filter(function (n) { return n; }); meshes = meshes.length ? meshes : this.defaultCollisionMeshes; } var intersects = this.raycaster.intersectObjects(meshes, true); if (intersects.length > 0 && !this.hit && this.isValidNormalsAngle(intersects[0].face.normal)) { var point = intersects[0].point; this.line.material.color.set(this.curveHitColor); this.line.material.opacity = this.data.hitOpacity; this.line.material.transparent= this.data.hitOpacity < 1; this.hitEntity.setAttribute('position', point); this.hitEntity.setAttribute('visible', true); this.hit = true; this.hitPoint.copy(intersects[0].point); // If hit, just fill the rest of the points with the hit point and break the loop for (var j = i; j < this.line.numPoints; j++) { this.line.setPoint(j, this.hitPoint); } return true; } else { this.line.setPoint(i, next); return false; } }
javascript
{ "resource": "" }
q48934
createHitEntity
train
function createHitEntity (data) { var cylinder; var hitEntity; var torus; // Parent. hitEntity = document.createElement('a-entity'); hitEntity.className = 'hitEntity'; // Torus. torus = document.createElement('a-entity'); torus.setAttribute('geometry', { primitive: 'torus', radius: data.hitCylinderRadius, radiusTubular: 0.01 }); torus.setAttribute('rotation', {x: 90, y: 0, z: 0}); torus.setAttribute('material', { shader: 'flat', color: data.hitCylinderColor, side: 'double', depthTest: false }); hitEntity.appendChild(torus); // Cylinder. cylinder = document.createElement('a-entity'); cylinder.setAttribute('position', {x: 0, y: data.hitCylinderHeight / 2, z: 0}); cylinder.setAttribute('geometry', { primitive: 'cylinder', segmentsHeight: 1, radius: data.hitCylinderRadius, height: data.hitCylinderHeight, openEnded: true }); cylinder.setAttribute('material', { shader: 'flat', color: data.hitCylinderColor, side: 'double', src: cylinderTexture, transparent: true, depthTest: false }); hitEntity.appendChild(cylinder); return hitEntity; }
javascript
{ "resource": "" }
q48935
cloneSyntax
train
function cloneSyntax(stx) { function F(){} F.prototype = stx.__proto__; var s = new F(); extend(s, stx); s.token = extend({}, s.token); return s; }
javascript
{ "resource": "" }
q48936
attach
train
function attach(bugout, identifier, wire, addr) { debug("saw wire", wire.peerId, identifier); wire.use(extension(bugout, identifier, wire)); wire.on("close", partial(detach, bugout, identifier, wire)); }
javascript
{ "resource": "" }
q48937
processMessageNode
train
function processMessageNode (message) { if ( (message.type === 'Literal' && typeof message.value === 'string' && !pattern.test(message.value)) || (message.type === 'TemplateLiteral' && message.quasis.length === 1 && !pattern.test(message.quasis[0].value.cooked)) ) { context.report({ node: message, message: "Report message does not match the pattern '{{pattern}}'.", data: { pattern: context.options[0] || '' }, }); } }
javascript
{ "resource": "" }
q48938
isExpectedUrl
train
function isExpectedUrl (node) { return Boolean( node && node.type === 'Literal' && typeof node.value === 'string' && ( expectedUrl === undefined || node.value === expectedUrl ) ); }
javascript
{ "resource": "" }
q48939
insertProperty
train
function insertProperty (fixer, node, propertyText) { if (node.properties.length === 0) { return fixer.replaceText(node, `{\n${propertyText}\n}`); } return fixer.insertTextAfter( sourceCode.getLastToken(node.properties[node.properties.length - 1]), `,\n${propertyText}` ); }
javascript
{ "resource": "" }
q48940
isRangeAccess
train
function isRangeAccess (node) { return node.type === 'MemberExpression' && node.property.type === 'Identifier' && node.property.name === 'range'; }
javascript
{ "resource": "" }
q48941
argHashToArray
train
function argHashToArray(hash) { var keys = Object.keys(hash); var result = []; for (var i = 0; i < keys.length; i++) { result[parseInt(keys[i], 10)] = hash[keys[i]]; } return result; }
javascript
{ "resource": "" }
q48942
makeBeanstalkCommand
train
function makeBeanstalkCommand(command, expectedResponse, sendsData) { // Commands are called as client.COMMAND(arg1, arg2, ... data, callback); // They're sent to beanstalkd as: COMMAND arg1 arg2 ... // followed by data. // So we slice the callback & data from the passed-in arguments, prepend // the command, then send the arglist otherwise intact. // We then push a handler for the expected response onto our handler stack. // Some commands have no args, just a callback (stats, stats-tube, etc); // That's the case handled when args < 2. return function() { var data, buffer, args = argHashToArray(arguments), callback = args.pop(); args.unshift(command); if (sendsData) { data = args.pop(); if (!Buffer.isBuffer(data)) data = new Buffer(data); args.push(data.length); } this.handlers.push([new ResponseHandler(expectedResponse), callback]); if (data) { buffer = Buffer.concat([new Buffer(args.join(' ')), CRLF, data, CRLF]); } else { buffer = Buffer.concat([new Buffer(args.join(' ')), CRLF]); } this.stream.write(buffer); }; }
javascript
{ "resource": "" }
q48943
pushListener
train
function pushListener(event) { var jsonString = event.data && event.data.text() ? event.data.text() : null; if (!jsonString) { console.log('Leanplum: Push received without payload, skipping display.'); return; } // noinspection JSCheckFunctionSignatures var options = JSON.parse(jsonString); /** @namespace options.title The title of the push notification. **/ /** @namespace options.tag The id of the push notification **/ if (!options || !options.title || !options.tag) { console.log('Leanplum: No options, title or tag/id received, skipping ' + 'display.'); return; } // Extract open action url. We only support open url action for now. /** @namespace options.data.openAction The openAction of the push notification. **/ if (options.data && options.data.openAction && options.data.openAction.hasOwnProperty(ACTION_NAME_KEY) && options.data.openAction[ACTION_NAME_KEY] === OPEN_URL_ACTION && options.data.openAction.hasOwnProperty(ARG_URL)) { openActions[options.tag] = options.data.openAction[ARG_URL]; } // Extract title and delete from options. var title = options.title; Reflect.deleteProperty(options, 'title'); /** @namespace self.registration **/ /** @namespace self.registration.showNotification **/ event.waitUntil(self.registration.showNotification(title, options)); }
javascript
{ "resource": "" }
q48944
notificationClickListener
train
function notificationClickListener(event) { console.log('Leanplum: [Service Worker] Notification click received.'); event.notification.close(); if (!event.notification || !event.notification.tag) { console.log('Leanplum: No notification or tag/id received, skipping open action.'); return; } var notificationId = event.notification.tag; var openActionUrl = openActions[notificationId]; if (!openActionUrl) { console.log('Leanplum: [Service Worker] No action defined, doing nothing.'); return; } Reflect.deleteProperty(openActions, 'notificationId'); /** @namespace clients.openWindow **/ event.waitUntil(clients.openWindow(openActionUrl)); }
javascript
{ "resource": "" }
q48945
bitDepth
train
function bitDepth(input, original, target, output) { validateBitDepth_(original); validateBitDepth_(target); /** @type {!Function} */ let toFunction = getBitDepthFunction_(original, target); /** @type {!Object<string, number>} */ let options = { oldMin: Math.pow(2, parseInt(original, 10)) / 2, newMin: Math.pow(2, parseInt(target, 10)) / 2, oldMax: (Math.pow(2, parseInt(original, 10)) / 2) - 1, newMax: (Math.pow(2, parseInt(target, 10)) / 2) - 1, }; /** @type {number} */ const len = input.length; // sign the samples if original is 8-bit if (original == "8") { for (let i=0; i<len; i++) { output[i] = input[i] -= 128; } } // change the resolution of the samples for (let i=0; i<len; i++) { output[i] = toFunction(input[i], options); } // unsign the samples if target is 8-bit if (target == "8") { for (let i=0; i<len; i++) { output[i] = output[i] += 128; } } }
javascript
{ "resource": "" }
q48946
intToInt_
train
function intToInt_(sample, args) { if (sample > 0) { sample = parseInt((sample / args.oldMax) * args.newMax, 10); } else { sample = parseInt((sample / args.oldMin) * args.newMin, 10); } return sample; }
javascript
{ "resource": "" }
q48947
floatToInt_
train
function floatToInt_(sample, args) { return parseInt( sample > 0 ? sample * args.newMax : sample * args.newMin, 10); }
javascript
{ "resource": "" }
q48948
getBitDepthFunction_
train
function getBitDepthFunction_(original, target) { /** @type {!Function} */ let func = function(x) {return x;}; if (original != target) { if (["32f", "64"].includes(original)) { if (["32f", "64"].includes(target)) { func = floatToFloat_; } else { func = floatToInt_; } } else { if (["32f", "64"].includes(target)) { func = intToFloat_; } else { func = intToInt_; } } } return func; }
javascript
{ "resource": "" }
q48949
decode
train
function decode(adpcmSamples, blockAlign=256) { /** @type {!Int16Array} */ let samples = new Int16Array(adpcmSamples.length * 2); /** @type {!Array<number>} */ let block = []; /** @type {number} */ let fileIndex = 0; for (let i=0; i<adpcmSamples.length; i++) { if (i % blockAlign == 0 && i != 0) { samples.set(decodeBlock(block), fileIndex); fileIndex += blockAlign * 2; block = []; } block.push(adpcmSamples[i]); } return samples; }
javascript
{ "resource": "" }
q48950
encodeBlock
train
function encodeBlock(block) { /** @type {!Array<number>} */ let adpcmSamples = blockHead_(block[0]); for (let i=3; i<block.length; i+=2) { /** @type {number} */ let sample2 = encodeSample_(block[i]); /** @type {number} */ let sample = encodeSample_(block[i + 1]); adpcmSamples.push((sample << 4) | sample2); } while (adpcmSamples.length < 256) { adpcmSamples.push(0); } return adpcmSamples; }
javascript
{ "resource": "" }
q48951
decodeBlock
train
function decodeBlock(block) { decoderPredicted_ = sign_((block[1] << 8) | block[0]); decoderIndex_ = block[2]; decoderStep_ = STEP_TABLE[decoderIndex_]; /** @type {!Array<number>} */ let result = [ decoderPredicted_, sign_((block[3] << 8) | block[2]) ]; for (let i=4; i<block.length; i++) { /** @type {number} */ let original_sample = block[i]; /** @type {number} */ let second_sample = original_sample >> 4; /** @type {number} */ let first_sample = (second_sample << 4) ^ original_sample; result.push(decodeSample_(first_sample)); result.push(decodeSample_(second_sample)); } return result; }
javascript
{ "resource": "" }
q48952
encodeSample_
train
function encodeSample_(sample) { /** @type {number} */ let delta = sample - encoderPredicted_; /** @type {number} */ let value = 0; if (delta >= 0) { value = 0; } else { value = 8; delta = -delta; } /** @type {number} */ let step = STEP_TABLE[encoderIndex_]; /** @type {number} */ let diff = step >> 3; if (delta > step) { value |= 4; delta -= step; diff += step; } step >>= 1; if (delta > step) { value |= 2; delta -= step; diff += step; } step >>= 1; if (delta > step) { value |= 1; diff += step; } updateEncoder_(value, diff); return value; }
javascript
{ "resource": "" }
q48953
decodeSample_
train
function decodeSample_(nibble) { /** @type {number} */ let difference = 0; if (nibble & 4) { difference += decoderStep_; } if (nibble & 2) { difference += decoderStep_ >> 1; } if (nibble & 1) { difference += decoderStep_ >> 2; } difference += decoderStep_ >> 3; if (nibble & 8) { difference = -difference; } decoderPredicted_ += difference; if (decoderPredicted_ > 32767) { decoderPredicted_ = 32767; } else if (decoderPredicted_ < -32767) { decoderPredicted_ = -32767; } updateDecoder_(nibble); return decoderPredicted_; }
javascript
{ "resource": "" }
q48954
blockHead_
train
function blockHead_(sample) { encodeSample_(sample); /** @type {!Array<number>} */ let adpcmSamples = []; adpcmSamples.push(sample & 0xFF); adpcmSamples.push((sample >> 8) & 0xFF); adpcmSamples.push(encoderIndex_); adpcmSamples.push(0); return adpcmSamples; }
javascript
{ "resource": "" }
q48955
encodeSample
train
function encodeSample(sample) { /** @type {number} */ let compandedValue; sample = (sample ==-32768) ? -32767 : sample; /** @type {number} */ let sign = ((~sample) >> 8) & 0x80; if (!sign) { sample = sample * -1; } if (sample > 32635) { sample = 32635; } if (sample >= 256) { /** @type {number} */ let exponent = LOG_TABLE[(sample >> 8) & 0x7F]; /** @type {number} */ let mantissa = (sample >> (exponent + 3) ) & 0x0F; compandedValue = ((exponent << 4) | mantissa); } else { compandedValue = sample >> 4; } return compandedValue ^ (sign ^ 0x55); }
javascript
{ "resource": "" }
q48956
decodeSample
train
function decodeSample(aLawSample) { /** @type {number} */ let sign = 0; aLawSample ^= 0x55; if (aLawSample & 0x80) { aLawSample &= ~(1 << 7); sign = -1; } /** @type {number} */ let position = ((aLawSample & 0xF0) >> 4) + 4; /** @type {number} */ let decoded = 0; if (position != 4) { decoded = ((1 << position) | ((aLawSample & 0x0F) << (position - 4)) | (1 << (position - 5))); } else { decoded = (aLawSample << 1)|1; } decoded = (sign === 0) ? (decoded) : (-decoded); return (decoded * 8) * -1; }
javascript
{ "resource": "" }
q48957
decode$1
train
function decode$1(samples) { /** @type {!Int16Array} */ let pcmSamples = new Int16Array(samples.length); for (let i=0; i<samples.length; i++) { pcmSamples[i] = decodeSample(samples[i]); } return pcmSamples; }
javascript
{ "resource": "" }
q48958
encodeSample$1
train
function encodeSample$1(sample) { /** @type {number} */ let sign; /** @type {number} */ let exponent; /** @type {number} */ let mantissa; /** @type {number} */ let muLawSample; /** get the sample into sign-magnitude **/ sign = (sample >> 8) & 0x80; if (sign != 0) sample = -sample; if (sample > CLIP) sample = CLIP; /** convert from 16 bit linear to ulaw **/ sample = sample + BIAS; exponent = encodeTable[(sample>>7) & 0xFF]; mantissa = (sample >> (exponent+3)) & 0x0F; muLawSample = ~(sign | (exponent << 4) | mantissa); /** return the result **/ return muLawSample; }
javascript
{ "resource": "" }
q48959
decodeSample$1
train
function decodeSample$1(muLawSample) { /** @type {number} */ let sign; /** @type {number} */ let exponent; /** @type {number} */ let mantissa; /** @type {number} */ let sample; muLawSample = ~muLawSample; sign = (muLawSample & 0x80); exponent = (muLawSample >> 4) & 0x07; mantissa = muLawSample & 0x0F; sample = decodeTable[exponent] + (mantissa << (exponent+3)); if (sign != 0) sample = -sample; return sample; }
javascript
{ "resource": "" }
q48960
swap
train
function swap(bytes, offset, index) { offset--; for(let x = 0; x < offset; x++) { /** @type {*} */ let theByte = bytes[index + x]; bytes[index + x] = bytes[index + offset]; bytes[index + offset] = theByte; offset--; } }
javascript
{ "resource": "" }
q48961
pack
train
function pack(str, buffer, index=0) { for (let i = 0, len = str.length; i < len; i++) { /** @type {number} */ let codePoint = str.codePointAt(i); if (codePoint < 128) { buffer[index] = codePoint; index++; } else { /** @type {number} */ let count = 0; /** @type {number} */ let offset = 0; if (codePoint <= 0x07FF) { count = 1; offset = 0xC0; } else if(codePoint <= 0xFFFF) { count = 2; offset = 0xE0; } else if(codePoint <= 0x10FFFF) { count = 3; offset = 0xF0; i++; } buffer[index] = (codePoint >> (6 * count)) + offset; index++; while (count > 0) { buffer[index] = 0x80 | (codePoint >> (6 * (count - 1)) & 0x3F); index++; count--; } } } return index; }
javascript
{ "resource": "" }
q48962
unpackString
train
function unpackString(buffer, index=0, end=buffer.length) { return unpack(buffer, index, end); }
javascript
{ "resource": "" }
q48963
unpackArrayTo
train
function unpackArrayTo( buffer, theType, output, start=0, end=buffer.length, safe=false) { theType = theType || {}; /** @type {NumberBuffer} */ let packer = new NumberBuffer(theType.bits, theType.fp, theType.signed); /** @type {number} */ let offset = packer.offset; // getUnpackLen_ will either fix the length of the input buffer // according to the byte offset of the type (on unsafe mode) or // throw a Error if the input buffer has a bad length (on safe mode) end = getUnpackLen_(buffer, start, end, offset, safe); /** @type {number} */ let index = 0; let j = start; try { if (theType.be) { endianness(buffer, offset, start, end); } for (; j < end; j += offset, index++) { output[index] = packer.unpack(buffer, j); } if (theType.be) { endianness(buffer, offset, start, end); } } catch (e) { throwValueError_(e, buffer.slice(j, j + offset), j, theType.fp); } }
javascript
{ "resource": "" }
q48964
packTo
train
function packTo(value, theType, buffer, index=0) { return packArrayTo([value], theType, buffer, index); }
javascript
{ "resource": "" }
q48965
unpackArray
train
function unpackArray( buffer, theType, start=0, end=buffer.length, safe=false) { /** @type {!Array<number>} */ let output = []; unpackArrayTo(buffer, theType, output, start, end, safe); return output; }
javascript
{ "resource": "" }
q48966
unpack$1
train
function unpack$1(buffer, theType, index=0) { return unpackArray( buffer, theType, index, index + Math.ceil(theType.bits / 8), true)[0]; }
javascript
{ "resource": "" }
q48967
train
function(layout, fail) { if (_.isFunction(layout)) { return layout; } if (!_.isString(layout)) { fail('Layout should be specified by name or as a function'); } if (_(defaultLayouts).has(layout)) { return defaultLayouts[layout]; } fail('The following named layouts are supported: ' + _.keys(defaultLayouts).join(', ')); }
javascript
{ "resource": "" }
q48968
pathifyModel
train
function pathifyModel (model, store, prefix) { let result = [] if (prefix) result.push(prefix) if (get(model, '_internalModel.modelName') === 'uni-form') { const propPath = propertyPath('payload', prefix) if (model.get('payload') instanceof DS.Model) { return result.concat(pathifyModel(model.get('payload'), store, propPath)) } return result.concat(pathifyObject(model.get('payload'), store, propPath)) } // Pathify serializer output const payload = model.serialize() const { attributes, data } = payload if (attributes) result = result.concat(pathifyObject(attributes, store, prefix)) // JSONAPI else if (data) result = result.concat(pathifyObject(data, store, prefix)) // JSONAPI else result = result.concat(pathifyObject(payload, store, prefix)) // Not JSONAPI // Pathify model attributes and child models which will be serialized const serializer = store.serializerFor(get(model, '_internalModel.modelName')) model.eachAttribute(name => result.push(propertyPath(name, prefix))) model.eachRelationship((name, { kind, type }) => { if (kind === 'hasMany') return // not supported const childPath = propertyPath(name, prefix) const willSerialize = get(serializer, `attrs.${name}.serialize`) === 'records' || get(serializer, `attrs.${name}.embedded`) === 'always' if (!willSerialize) { result.push(childPath) } else { const instance = store.createRecord(type) result = result.concat(pathifyModel(instance, store, childPath)) store.deleteRecord(instance) } }) return result.uniq() }
javascript
{ "resource": "" }
q48969
train
function () { options.menu = !fabricator.dom.root.classList.contains('f-menu-active'); fabricator.dom.root.classList.toggle('f-menu-active'); if (fabricator.test.sessionStorage) { sessionStorage.setItem('fabricator', JSON.stringify(options)); } }
javascript
{ "resource": "" }
q48970
train
function (list) { if (!list.matches) { root.classList.remove('f-menu-active'); } else { if (fabricator.getOptions().menu) { root.classList.add('f-menu-active'); } else { root.classList.remove('f-menu-active'); } } }
javascript
{ "resource": "" }
q48971
getColors
train
function getColors(rawData) { // Regular expression matching colors variables naming pattern var REGEX = /^dc-(.*?)[0-9]+$/; var content = rawData .filter((item) => { var group = item.group[0]; return group === 'colors' && item.context.type === 'variable' && item.context.name.match(REGEX); }) .map((item) => { // extract color name (eg. `dc-magenta10 -> magenta`) item.color = item.context.name.replace(REGEX, '$1'); item.color = _.capitalize(item.color); return item; }); // transform colors array in a object, shaped as the view layer expect content = _.groupBy(content, (c) => c.color ); Object.keys(content).forEach((color) => { content[color] = content[color].reduce((acc, c) => { acc['$' + c.context.name] = c.context.value; return acc; }, {}); }); return content; }
javascript
{ "resource": "" }
q48972
getSassReference
train
function getSassReference(rawData) { // group sassdoc items (variables, mixins, functions, etc.) by @group var content = _.groupBy(rawData, (item) => item.group[0]); Object.keys(content).forEach((group) => { content[group] = content[group].map((item) => { // boolean flag for deprecated item.deprecated = typeof item.deprecated !== 'undefined' return item; }); // group every sassdoc item by type content[group] = _.groupBy(content[group], (item) => item.context.type + 's'); }); return content; }
javascript
{ "resource": "" }
q48973
getErrorMessage
train
function getErrorMessage (err, target, defaultMsg) { var errMessage; if (err) { errMessage = err.toString(); } else { errMessage = defaultMsg; } return errMessage.replace('%target%', target); }
javascript
{ "resource": "" }
q48974
merkle
train
function merkle (values, digestFn) { if (!Array.isArray(values)) throw TypeError('Expected values Array') if (typeof digestFn !== 'function') throw TypeError('Expected digest Function') if (values.length === 1) return values.concat() var levels = [values] var level = values do { level = _derive(level, digestFn) levels.push(level) } while (level.length > 1) return [].concat.apply([], levels) }
javascript
{ "resource": "" }
q48975
callOnFinish
train
function callOnFinish (original) { return function (callback) { if (concurrent === 0) { original.call(this, callback); } else { pendingFinish = original.bind(this, callback); } } }
javascript
{ "resource": "" }
q48976
findPackages
train
function findPackages(path) { return new Promise(function (resolve, reject) { (0, _glob.glob)(path, function (err, res) { if (err) { reject(err); } resolve(res.filter(function (file) { return file.endsWith('.json'); })); }); }); }
javascript
{ "resource": "" }
q48977
readPackages
train
function readPackages() { var packages = arguments.length <= 0 || arguments[0] === undefined ? [] : arguments[0]; return Promise.all(packages.map(readPackage)).then(function (labels) { return labels.reduce(function (prev, curr) { return prev.concat(curr); }); }); }
javascript
{ "resource": "" }
q48978
requestPromisfied
train
function requestPromisfied(options) { return new Promise(function (resolve, reject) { (0, _request2.default)(options, function (err, res) { if (err) { reject(err); } resolve(res.body); }); }); }
javascript
{ "resource": "" }
q48979
configure
train
function configure(_ref) { var api = _ref.api; var token = _ref.token; var repo = _ref.repo; return { api: api, repo: "repos/" + repo, token: token }; }
javascript
{ "resource": "" }
q48980
add
train
function add(server, labels) { return (0, _label.createLabels)((0, _config.configure)(server), labels).then(_handlers.createSuccessHandler).catch(_handlers.errorHandler); }
javascript
{ "resource": "" }
q48981
remove
train
function remove(server, labels) { return (0, _label.deleteLabels)((0, _config.configure)(server), labels).then(_handlers.deleteSuccessHandler).catch(_handlers.errorHandler); }
javascript
{ "resource": "" }
q48982
createLabel
train
function createLabel(_ref, name, color) { var api = _ref.api; var token = _ref.token; var repo = _ref.repo; return (0, _request2.default)({ headers: { 'User-Agent': 'request', 'Authorization': 'token ' + token }, url: api + '/' + repo + '/labels', form: JSON.stringify({ name: name, color: color }), method: 'POST', json: true }); }
javascript
{ "resource": "" }
q48983
deleteLabel
train
function deleteLabel(_ref2, name) { var api = _ref2.api; var token = _ref2.token; var repo = _ref2.repo; return (0, _request2.default)({ headers: { 'User-Agent': 'request', 'Authorization': 'token ' + token }, url: api + '/' + repo + '/labels/' + name, method: 'DELETE', json: true }); }
javascript
{ "resource": "" }
q48984
getLabels
train
function getLabels(_ref3) { var api = _ref3.api; var token = _ref3.token; var repo = _ref3.repo; return (0, _request2.default)({ headers: { 'User-Agent': 'request', 'Authorization': 'token ' + token }, url: api + '/' + repo + '/labels', method: 'GET', json: true }); }
javascript
{ "resource": "" }
q48985
formatLabel
train
function formatLabel(_ref4) { var name = _ref4.name; var color = _ref4.color; return { name: name, color: color.replace('#', '') }; }
javascript
{ "resource": "" }
q48986
createLabels
train
function createLabels(server, labels) { return Promise.all(labels.map(formatLabel).map(function (_ref5) { var name = _ref5.name; var color = _ref5.color; return createLabel(server, name, color); })); }
javascript
{ "resource": "" }
q48987
deleteLabels
train
function deleteLabels(server, labels) { return Promise.all(labels.map(formatLabel).map(function (_ref6) { var name = _ref6.name; var color = _ref6.color; return deleteLabel(server, name); })); }
javascript
{ "resource": "" }
q48988
replaceParams
train
function replaceParams(ast, keys) { Object.keys(ast) .filter(key => { const value = ast[key] return Array.isArray(value) || (typeof value === 'object' && value !== null) }) .forEach(key => { const expr = ast[key] if (!(typeof expr === 'object' && expr.type === 'param')) return replaceParams(expr, keys) if (typeof keys[expr.value] === 'undefined') throw new Error(`no value for parameter :${expr.value} found`) ast[key] = createValueExpr(keys[expr.value]) return null }) return ast }
javascript
{ "resource": "" }
q48989
Mage
train
function Mage(mageRootModule) { EventEmitter.call(this); this.workerId = require('./worker').getId(); this.MageError = require('./MageError'); this.task = null; this._runState = 'init'; this._modulesList = []; this._modulePaths = [ applicationModulesPath ]; this._setupQueue = []; this._teardownQueue = []; // Set up the core object that holds some crucial Mage libraries this.core = { modules: {} }; // Register the Mage version var magePath = path.join(path.dirname(__dirname), '..'); var magePackagePath = path.join(magePath, 'package.json'); var rootPackagePath = path.join(rootPath, 'package.json'); var magePackage = require(magePackagePath); var rootPackage; try { rootPackage = require(rootPackagePath); } catch (error) { console.warn('Could not load your project\'s "package.json"', error); } var appName = rootPackage && rootPackage.name || path.basename(rootPath); var appVersion = rootPackage && rootPackage.version; this.version = magePackage.version; this.magePackage = { name: 'mage', version: magePackage.version, path: magePath, package: magePackage }; this.rootPackage = { name: appName, version: appVersion, path: rootPath, package: rootPackage }; // test the supported node version of mage itself as soon as possible testEngineVersion(this.magePackage.package, magePackagePath, this); testEngineVersion(this.rootPackage.package, rootPackagePath, this); require('codependency').register(mageRootModule); }
javascript
{ "resource": "" }
q48990
recursiveFileList
train
function recursiveFileList(rootPath, cb) { var fileList = []; var errorList = []; var q = async.queue(function (filename, callback) { var filePath = path.join(rootPath, filename); fs.stat(filePath, function (error, stat) { if (error) { errorList.push(error); return callback(error); } // If not a directory then push onto list and continue if (!stat.isDirectory()) { fileList.push(filename); return callback(); } // Otherwise recurse fs.readdir(filePath, function (error, files) { if (error) { errorList.push(error); return callback(error); } // Append list of child file onto our file list for (var i = 0; i < files.length; i += 1) { q.push(path.join(filename, files[i])); } callback(); }); }); }, MAX_PARALLEL); q.drain = function () { if (errorList.length) { return cb(errorList); } cb(null, fileList); }; fs.readdir(rootPath, function (error, files) { if (error) { return cb(error); } if (!files.length) { return q.drain(); } for (var i = 0; i < files.length; i += 1) { q.push(files[i]); } }); }
javascript
{ "resource": "" }
q48991
purgeEmptyParentFolders
train
function purgeEmptyParentFolders(rootPath, subfolderPath, logger, cb) { var fullPath = path.join(rootPath, subfolderPath); // Don't delete if we have reached the base if (!subfolderPath || subfolderPath === '.') { return cb(); } fs.rmdir(fullPath, function (error) { if (error) { return cb(error); } logger.verbose('Purged empty subfolder:', fullPath); return purgeEmptyParentFolders(rootPath, path.dirname(subfolderPath), logger, cb); }); }
javascript
{ "resource": "" }
q48992
purgeEmptySubFolders
train
function purgeEmptySubFolders(rootPath, subfolderPath, logger, cb) { subfolderPath = subfolderPath || ''; var fullPath = path.join(rootPath, subfolderPath); fs.readdir(fullPath, function (error, files) { if (error) { return cb(); } async.eachLimit(files, MAX_PARALLEL, function (file, callback) { var filepath = path.join(fullPath, file); fs.stat(filepath, function (error, stat) { if (error || !stat.isDirectory()) { return callback(); } // Recurse inwards purgeEmptySubFolders(rootPath, path.join(subfolderPath, file), logger, callback); }); }, function () { // Do nothing if root path if (!subfolderPath) { return cb(); } // Otherwise attempt to remove directory fs.rmdir(fullPath, function (error) { if (error) { return cb(); } logger.verbose('Purged empty subfolder:', fullPath); return cb(); }); }); }); }
javascript
{ "resource": "" }
q48993
getAvailableMigrations
train
function getAvailableMigrations(vaultName, cb) { var path = configuration.getMigrationsPath(vaultName); fs.readdir(path, function (error, files) { if (error) { if (error.code === 'ENOENT') { logger.warning('No migration folder found for vault', vaultName, '(skipping).'); return cb(null, []); } return cb(error); } var result = []; for (var i = 0; i < files.length; i++) { var file = files[i]; var ext = extname(file); if (mage.isCodeFileExtension(ext)) { result.push(basename(file, ext)); } } cb(null, result); }); }
javascript
{ "resource": "" }
q48994
migrateVaultToVersion
train
function migrateVaultToVersion(vault, targetVersion, cb) { var preventMigrate = mage.core.config.get(['archivist', 'vaults', vault.name, 'config', 'preventMigrate'], false); if (preventMigrate) { logger.warning(`Vault ${vault.name} has disabled migrate operation (skipping)`); return cb(); } if (typeof vault.getMigrations !== 'function') { logger.warning('Cannot migrate on vault', vault.name, '(skipping).'); return cb(); } // load applied versions vault.getMigrations(function (error, appliedVersions) { if (error) { return cb(error); } getAvailableMigrations(vault.name, function (error, available) { if (error) { return cb(error); } logger.debug('Available versions with migration paths:', available); var migration = calculateMigration(targetVersion, available, appliedVersions); logger.debug('Calculated migration path:', migration); if (migration.versions.length === 0) { logger.notice('No migrations to apply on vault', vault.name); return cb(); } if (migration.direction === 'down') { migrateDown(vault, migration.versions, cb); } else { migrateUp(vault, migration.versions, cb); } }); }); }
javascript
{ "resource": "" }
q48995
copy
train
function copy(from, to) { var mode = fs.statSync(from).mode; var src = fs.readFileSync(from, 'utf8'); var re = /%([0-9A-Z\_]+)%/g; function replacer(_, match) { // We support the %PERIOD% variable to allow .gitignore to be created. The reason: // npm "kindly" ignores .gitignore files, so we have to use this workaround. // More info: https://github.com/isaacs/npm/issues/2958 if (match === 'PERIOD') { return '.'; } return templateRules.replace(match); } try { to = to.replace(re, replacer); src = src.replace(re, replacer); } catch (error) { pretty.warning(error + ' in: ' + from); // skip this file return; } var fd = fs.openSync(to, 'w', mode); fs.writeSync(fd, src); fs.closeSync(fd); }
javascript
{ "resource": "" }
q48996
flagsToStr
train
function flagsToStr(flags) { if (!flags) { return; } var buff = new Buffer(4); buff.writeUInt32BE(flags, 0); // return a 0-byte terminated or 4-byte string switch (0) { case buff[0]: return; case buff[1]: return buff.toString('utf8', 0, 1); case buff[2]: return buff.toString('utf8', 0, 2); case buff[3]: return buff.toString('utf8', 0, 3); default: return buff.toString(); } }
javascript
{ "resource": "" }
q48997
strToFlags
train
function strToFlags(str) { if (!str) { return; } var buff = new Buffer([0, 0, 0, 0]); buff.write(str, 0, 4, 'ascii'); return buff.readUInt32BE(0); }
javascript
{ "resource": "" }
q48998
getRawRecursive
train
function getRawRecursive(matryoshka) { if (matryoshka.type !== 'object') { return matryoshka.value; } const returnObj = {}; for (const key of Object.keys(matryoshka.value)) { returnObj[key] = getRawRecursive(matryoshka.value[key]); } return returnObj; }
javascript
{ "resource": "" }
q48999
merge
train
function merge(a, b) { // If a is not a matryoshka, then return a copy of b (override). if (!(a instanceof Matryoshka)) { return b.copy(); } // If b is not a matryoshka, then just keep a. if (!(b instanceof Matryoshka)) { return a.copy(); } // If we reached here, both a and b are matryoshkas. // Types are 'object' (not including array or null) and 'scalar' (everything else). // If a field is empty, merge with the other object // Ex: // logging: // server: // || // \/ // logging: { // server: null // } if (a.value === null) { return b.copy(); } if (b.value === null) { return a.copy(); } // Different types means that no merge is required, and we can just copy b. if (a.type !== b.type) { return b.copy(); } // Scalar types are shallow, so a merge is really just an override. if (b.type === 'scalar') { return b.copy(); } // If we reached here, then both a and b contain objects to be compared key-by-key. // First assemble a list of keys in one or both objects. const aKeys = Object.keys(a.value); const bKeys = Object.keys(b.value); const uniqueKeys = new Set(aKeys.concat(bKeys)); const merged = {}; // Merge key-by-key. for (const key of uniqueKeys) { merged[key] = merge(a.value[key], b.value[key]); } // Wrap the merged object in a Matryoshka. return new Matryoshka(merged, a.source, true); }
javascript
{ "resource": "" }