Input: drilldown Safely accesses deep properties of objects . [CODESPLIT] function dd ( object , _context , _key , _root , _rootPath ) { _root = _root || object ; _rootPath = _rootPath || [ ] ; var drill = function ( key ) { var nextObject = ( object && object . hasOwnProperty ( key ) && object [ key ] || undefined ) ; return dd ( nextObject , object , key , _root , _rootPath . concat ( key ) ) ; } ; drill . val = object ; drill . exists = object !== undefined ; drill . set = function ( value ) { if ( _rootPath . length === 0 ) { return ; } var contextIterator = _root ; for ( var depth = 0 ; depth < _rootPath . length ; depth ++ ) { var key = _rootPath [ depth ] ; var isFinalDepth = ( depth === _rootPath . length - 1 ) ; if ( ! isFinalDepth ) { contextIterator [ key ] = ( contextIterator . hasOwnProperty ( key ) && typeof contextIterator [ key ] === 'object' ? contextIterator [ key ] : { } ) ; contextIterator = contextIterator [ key ] ; } else { _context = contextIterator ; _key = key ; } } _context [ _key ] = value ; drill . val = value ; drill . exists = value !== undefined ; return value ; } ; drill . update = function ( value ) { if ( drill . exists ) { _context [ _key ] = value ; drill . val = value ; return value ; } } ; drill . invoke = isFunction ( object ) ? Function . prototype . bind . call ( object , _context ) : function ( ) { } ; return drill ; }


Input: feature flag控制类，提供接口给模板调用，判断某个feature是否开启 [CODESPLIT] function ( option , req , res ) { this . params = { 'req' : req , 'res' : res } ; this . option = option ; this . features = { } ; //feature实例配置列表 this . logger = Logger . getLogger ( ) ; }


Input: Render output from tasks [CODESPLIT] function printTasks ( tasks , verbose ) { tasks = tasks . filterHidden ( verbose ) . sort ( ) ; var results = [ 'Usage: gulp [task] [task2] ...' , '' , 'Tasks: ' ] ; var fieldTaskLen = tasks . getLongestNameLength ( ) ; tasks . forEach ( function ( task ) { var comment = task . comment || { } ; var lines = comment . lines || [ ] ; results . push ( formatColumn ( task . name , fieldTaskLen ) + ( lines [ 0 ] || '' ) ) ; for ( var i = 1 ; i < lines . length ; i ++ ) { results . push ( formatColumn ( '' , fieldTaskLen ) + '  ' + lines [ i ] ) ; } } ) ; return results . join ( '\n' ) ; }


Input: Return a text surrounded by space [CODESPLIT] function formatColumn ( text , width , offsetLeft , offsetRight ) { offsetLeft = undefined !== offsetLeft ? offsetLeft : 3 ; offsetRight = undefined !== offsetRight ? offsetRight : 3 ; return new Array ( offsetLeft + 1 ) . join ( ' ' ) + text + new Array ( Math . max ( width - text . length , 0 ) + 1 ) . join ( ' ' ) + new Array ( offsetRight + 1 ) . join ( ' ' ) ; }


Input: Return a new instance that is inherited from Gulp [CODESPLIT] function inheritGulp ( ) { function TaskDoc ( ) { this . taskList = new TaskList ( ) ; gulp . Gulp . call ( this ) ; } TaskDoc . prototype = gulp ; return new TaskDoc ( ) ; }


Input:
////////////////////////////////////////////////////////////////////////////////////// main api method defined on the jazz environment in imitation of the jasmine lib src . where () accepts only a function with a commented data - table and an expectation . parses the function into data array passing each array row into a new Function () that contains the original function body s expectation statements . entire data - table with pass / fail messages is passed to the jasmine report only if an expectation fails . returns the data table values array for further use in other expectations . ////////////////////////////////////////////////////////////////////////////////////// [CODESPLIT] function where ( fn ) { if ( typeof fn != 'function' ) { throw new Error ( 'where(param) expected param should be a function' ) ; } var fnBody = fn . toString ( ) . replace ( / \s*function[^\(]*[\(][^\)]*[\)][^\{]*{ / , '' ) . replace ( / [\}]$ / , '' ) ; var values = parseFnBody ( fnBody ) ; var labels = values [ 0 ] ; /**
     * {labels} array is toString'd so the values became param symbols in the new Function.
     * {fnBody} is what's left of the original function, mainly the expectation.
     */ var fnTest = new Function ( labels . toString ( ) , fnBody ) ; var failedCount = 0 ; var trace = '\n [' + labels . join ( PAD ) + '] : ' ; /*
     * 1.x.x - jasmine.getEnv().currentSpec
     * 2.x.x - .currentSpec is no longer exposed (leaking state) so use a shim for it with
     *          the v2 .result property
     */ var currentSpec = jasmine . getEnv ( ) . currentSpec || { result : { } } ; var result = /* jasmine 2.x.x. */ currentSpec . result || /* jasmine 1.x.x. */ currentSpec . results_ ; var item , message ; for ( var i = 1 ; i < values . length ; ++ i ) { message = MESSAGE ; fnTest . apply ( currentSpec , values [ i ] ) ; // TODO - extract method, perhaps... // collect any failed expectations  if ( result . failedExpectations && result . failedExpectations . length ) { /*
         * jasmine 2.x.x.
         */ if ( failedCount < result . failedExpectations . length ) { failedCount += 1 ; item = result . failedExpectations [ failedCount - 1 ] ; message = item . message ; item . message = trace + '\n [' + values [ i ] . join ( PAD ) + '] (' + message + ')' ; } } else if ( result . items_ ) { /*
         * jasmine 1.x.x.
         */ item = result . items_ [ result . items_ . length - 1 ] ; if ( item && ! item . passed_ ) { failedCount += 1 ; message = item . message ; item . message = trace + '\n [' + values [ i ] . join ( PAD ) + '] (' + message + ')' ; } } } // use these in further assertions  return values ; }


Input: private method parseFn () takes a function or string and extracts the data table labels and values . returns a result object with { body } the function as a string and { table } data array . [CODESPLIT] function parseFnBody ( fnBody ) { var fs = fnBody . toString ( ) ; var table = fs . match ( / \/(\*){3,3}[^\*]+(\*){3,3}\/ / ) ; var data = table [ 0 ] . replace ( / [\/\*]*[\r]*[\*\/]* / g , '' ) . split ( '\n' ) ; var rows = [ ] ; var row , size ; for ( var i = 0 ; i < data . length ; i ++ ) { row = data [ i ] . replace ( / \b[\s*] / , '' ) . replace ( / (\s)*\b / , '' ) ; if ( row . match ( / \S+ / ) ) { row = row . replace ( / \s+ / g , '' ) ; // empty column if ( row . match ( / [\|][\|] / g ) ) { throw new Error ( 'where() data table has unbalanced columns: ' + row ) ; } row = balanceRowData ( row ) ; // visiting label row if ( typeof size != 'number' ) { shouldNotHaveDuplicateLabels ( row ) ; size = row . length ; } // data row length if ( size !== row . length ) { throw new Error ( 'where-data table has unbalanced row; expected ' + size + ' columns but has ' + row . length + ': [' + row . join ( ', ' ) + ']' ) ; } convertNumerics ( row ) ; rows . push ( row ) ; } } // num rows if ( rows . length < 2 ) { throw new Error ( 'where() data table should contain at least 2 rows but has ' + rows . length ) ; } return rows ; }


Input: / * [CODESPLIT] function shouldNotHaveDuplicateLabels ( row ) { for ( var label , visited = { } , j = 0 ; j < row . length ; j += 1 ) { label = row [ j ] ; if ( visited [ label ] ) { throw new Error ( 'where-data table contains duplicate label \'' + label + '\' in [' + row . join ( ', ' ) + ']' ) ; } visited [ label ] = 1 ; } }


Input: / * [CODESPLIT] function convertNumerics ( row ) { for ( var t , i = 0 ; i < row . length ; i += 1 ) { t = parseFloat ( row [ i ] . replace ( / \'|\"|\, / g , '' ) ) ; isNaN ( t ) || ( row [ i ] = t ) ; } }


Input: We are creating one generic version of logger . [CODESPLIT] function _log ( level ) { return function ( ) { var meta = null ; var args = arguments ; if ( arguments . length === 0 ) { // we only check here current level, but we also should more but restify uses it only for trace checks return this . _winston . level === level ; } else if ( arguments [ 0 ] instanceof Error ) { // winston supports Error in meta, so pass it as last meta = arguments [ 0 ] . toString ( ) ; args = Array . prototype . slice . call ( arguments , 1 ) ; args . push ( meta ) ; } else if ( typeof ( args [ 0 ] ) === 'string' ) { // just arrayize for level args = Array . prototype . slice . call ( arguments ) ; } else { // push provided object as meta meta = arguments [ 0 ] ; args = Array . prototype . slice . call ( arguments , 1 ) ; args . push ( meta ) ; } args . unshift ( level ) ; this . _winston . log . apply ( this . _winston , args ) ; } }


Input: Utility functions {{{ Try and return a value from a deeply nested object by a dotted path This is functionally the same as lodash s own _ . get () function [CODESPLIT] function getPath ( obj , path , defaultValue ) { var pointer = obj ; path . split ( '.' ) . every ( function ( slice ) { if ( pointer [ slice ] ) { pointer = pointer [ slice ] ; return true ; } else { pointer = defaultValue ; return false ; } } ) ; return pointer ; }


Input: Try and idenfity if the given item is a promise or is promise like [CODESPLIT] function isPromise ( item ) { if ( ! item ) return false ; return ( ( util . types && util . types . isPromise && util . types . isPromise ( item ) ) || ( item . constructor && item . constructor . name == 'Promise' ) || ( ! item instanceof objectInstance && item . then && typeof item . then == 'function' ) ) ; }


Input: Figure out if a function declaration looks like it takes a callback Really this just checks the setup of a function for an argument - it cannot check if that argument is a function [CODESPLIT] function hasCallback ( fn ) { var fnString = fn . toString ( ) ; // console.log('---'); // console.log('GIVEN', '>>> ' + fnString + ' <<<'); var bits , fnArgs ; if ( / ^async  / . test ( fnString ) ) { // console.log('IS ASYNC'); return false ; // Its an async function and should only ever return a promise } else if ( bits = / ^function\s*(?:.*?)\s*\((.*?)\) / . exec ( fnString ) ) { // console.log('> FUNC', bits[1]); fnArgs = bits [ 1 ] ; } else if ( / ^\(\s*\)\s*=> / . test ( fnString ) ) { // console.log('ARROW (no args)'); return false ; } else if ( bits = / ^\s\((.*?)\)\s*?=> / . exec ( fnString ) ) { // console.log('> ARROW (braces)', bits[1]); fnArgs = bits [ 1 ] ; } else if ( bits = / ^(.*?)\s*=> / . exec ( fnString ) ) { // console.log('> ARROW (no braces)', bits[1]); fnArgs = bits [ 1 ] ; } else { // console.log('> EMPTY'); return false ; } fnArgs = fnArgs . replace ( / ^\s+ / , '' ) . replace ( / \s+$ / , '' ) ; // Clean up args by trimming whitespace // console.log('ARGS:', fnArgs); return ! ! fnArgs ; }


Input: Queue up a function ( s ) to execute in parallel [CODESPLIT] function parallel ( ) { var self = this ; argy ( arguments ) . ifForm ( '' , function ( ) { } ) . ifForm ( 'function' , function ( callback ) { self . _struct . push ( { type : 'parallelArray' , payload : [ callback ] } ) ; } ) . ifForm ( 'string function' , function ( id , callback ) { var payload = { } ; payload [ id ] = callback ; self . _struct . push ( { type : 'parallelArray' , payload : payload } ) ; } ) . ifForm ( 'array' , function ( tasks ) { self . _struct . push ( { type : 'parallelArray' , payload : tasks } ) ; } ) . ifForm ( 'object' , function ( tasks ) { self . _struct . push ( { type : 'parallelObject' , payload : tasks } ) ; } ) // Async library compatibility {{{ . ifForm ( 'array function' , function ( tasks , callback ) { self . _struct . push ( { type : 'parallelArray' , payload : tasks } ) ; self . end ( callback ) ; } ) . ifForm ( 'object function' , function ( tasks , callback ) { self . _struct . push ( { type : 'parallelObject' , payload : tasks } ) ; self . end ( callback ) ; } ) // }}} . ifFormElse ( function ( form ) { throw new Error ( 'Unknown call style for .parallel(): ' + form ) ; } ) return self ; }


Input: Like parallel but only return the first non - undefined non - null result [CODESPLIT] function race ( ) { var self = this ; argy ( arguments ) . ifForm ( '' , function ( ) { } ) . ifForm ( 'array' , function ( tasks ) { self . _struct . push ( { type : 'race' , payload : tasks } ) ; } ) . ifForm ( 'string array' , function ( id , tasks ) { self . _struct . push ( { type : 'race' , id : arguments [ 0 ] , payload : arguments [ 1 ] } ) ; } ) . ifFormElse ( function ( form ) { throw new Error ( 'Unknown call style for .parallel(): ' + form ) ; } ) return self ; }


Input: Run an array / object though a function This is similar to the async native . each () function but chainable [CODESPLIT] function forEach ( ) { var self = this ; argy ( arguments ) . ifForm ( '' , function ( ) { } ) . ifForm ( 'array function' , function ( tasks , callback ) { self . _struct . push ( { type : 'forEachArray' , payload : tasks , callback : callback } ) ; } ) . ifForm ( 'object function' , function ( tasks , callback ) { self . _struct . push ( { type : 'forEachObject' , payload : tasks , callback : callback } ) ; } ) . ifForm ( 'string function' , function ( tasks , callback ) { self . _struct . push ( { type : 'forEachLateBound' , payload : tasks , callback : callback } ) ; } ) . ifForm ( 'number function' , function ( max , callback ) { self . _struct . push ( { type : 'forEachRange' , min : 1 , max : max , callback : callback } ) ; } ) . ifForm ( 'number number function' , function ( min , max , callback ) { self . _struct . push ( { type : 'forEachRange' , min : min , max : max , callback : callback } ) ; } ) . ifForm ( 'string array function' , function ( output , tasks , callback ) { self . _struct . push ( { type : 'mapArray' , output : output , payload : tasks , callback : callback } ) ; } ) . ifForm ( 'string object function' , function ( output , tasks , callback ) { self . _struct . push ( { type : 'mapObject' , output : output , payload : tasks , callback : callback } ) ; } ) . ifForm ( 'string string function' , function ( output , tasks , callback ) { self . _struct . push ( { type : 'mapLateBound' , output : output , payload : tasks , callback : callback } ) ; } ) . ifFormElse ( function ( form ) { throw new Error ( 'Unknown call style for .forEach(): ' + form ) ; } ) ; return self ; }


Input: Collection of items that have been deferred [CODESPLIT] function deferAdd ( id , task , parentChain ) { var self = this ; parentChain . waitingOn = ( parentChain . waitingOn || 0 ) + 1 ; if ( ! parentChain . waitingOnIds ) parentChain . waitingOnIds = [ ] ; parentChain . waitingOnIds . push ( id ) ; self . _deferred . push ( { id : id || null , prereq : parentChain . prereq || [ ] , payload : function ( next ) { self . _context . _id = id ; run ( self . _options . context , task , function ( err , value ) { // Glue callback function to first arg if ( id ) self . _context [ id ] = value ; self . _deferredRunning -- ; if ( -- parentChain . waitingOn == 0 ) { parentChain . completed = true ; if ( self . _struct . length && self . _struct [ self . _structPointer ] . type == 'await' ) self . _execute ( err ) ; } self . _execute ( err ) ; } , ( parentChain . prereq || [ ] ) . map ( function ( pre ) { return self . _context [ pre ] ; } ) ) ; } } ) ; }


Input: }}} Queue up a function ( s ) to execute as deferred - i . e . dont stop to wait for it [CODESPLIT] function defer ( ) { var self = this ; argy ( arguments ) . ifForm ( '' , function ( ) { } ) . ifForm ( 'function' , function ( callback ) { self . _struct . push ( { type : 'deferArray' , payload : [ callback ] } ) ; } ) . ifForm ( 'string function' , function ( id , callback ) { var payload = { } ; payload [ id ] = callback ; self . _struct . push ( { type : 'deferObject' , payload : payload } ) ; } ) . ifForm ( 'array' , function ( tasks ) { self . _struct . push ( { type : 'deferArray' , payload : tasks } ) ; } ) . ifForm ( 'object' , function ( tasks ) { self . _struct . push ( { type : 'deferObject' , payload : tasks } ) ; } ) . ifForm ( 'array function' , function ( preReqs , callback ) { self . _struct . push ( { type : 'deferArray' , prereq : preReqs , payload : [ callback ] } ) ; } ) . ifForm ( 'string string function' , function ( preReq , id , callback ) { var payload = { } ; payload [ id ] = callback ; self . _struct . push ( { type : 'deferObject' , prereq : [ preReq ] , payload : payload } ) ; } ) . ifForm ( 'array string function' , function ( preReqs , id , callback ) { var payload = { } ; payload [ id ] = callback ; self . _struct . push ( { type : 'deferObject' , prereq : preReqs , payload : payload } ) ; } ) . ifForm ( 'string array function' , function ( id , preReqs , callback ) { var payload = { } ; payload [ id ] = callback ; self . _struct . push ( { type : 'deferObject' , prereq : preReqs , payload : payload } ) ; } ) . ifFormElse ( function ( form ) { throw new Error ( 'Unknown call style for .defer():' + form ) ; } ) ; return self ; }


Input: Queue up an await point This stops the execution queue until its satisfied that dependencies have been resolved [CODESPLIT] function await ( ) { var payload = [ ] ; // Slurp all args into payload argy ( arguments ) . getForm ( ) . split ( ',' ) . forEach ( function ( type , offset ) { switch ( type ) { case '' : // Blank arguments - do nothing // Pass break ; case 'string' : payload . push ( args [ offset ] ) ; break ; case 'array' : payload . concat ( args [ offset ] ) ; break ; default : throw new Error ( 'Unknown argument type passed to .await(): ' + type ) ; } } ) ; this . _struct . push ( { type : 'await' , payload : payload } ) ; return this ; }


Input: Queue up a timeout setter [CODESPLIT] function timeout ( newTimeout ) { var self = this ; argy ( arguments ) . ifForm ( '' , function ( ) { self . _struct . push ( { type : 'timeout' , delay : false } ) ; } ) . ifForm ( 'boolean' , function ( setTimeout ) { if ( setTimeout ) throw new Error ( 'When calling .timeout(Boolean) only False is accepted to disable the timeout' ) ; self . _struct . push ( { type : 'timeout' , delay : false } ) ; } ) . ifForm ( 'number' , function ( delay ) { self . _struct . push ( { type : 'timeout' , delay : delay } ) ; } ) . ifForm ( 'function' , function ( callback ) { self . _struct . push ( { type : 'timeout' , callback : callback } ) ; } ) . ifForm ( 'number function' , function ( delay , callback ) { self . _struct . push ( { type : 'timeout' , delay : delay , callback : callback } ) ; } ) . ifForm ( 'function number' , function ( delay , callback ) { self . _struct . push ( { type : 'timeout' , delay : delay , callback : callback } ) ; } ) . ifFormElse ( function ( form ) { throw new Error ( 'Unknown call style for .timeout():' + form ) ; } ) ; return self ; }


Input: The default timeout handler This function displays a simple error message and also fires the timeout hook [CODESPLIT] function _timeoutHandler ( ) { var currentTaskIndex = this . _struct . findIndex ( function ( task ) { return ! task . completed } ) ; if ( ! currentTaskIndex < 0 ) { console . log ( 'Async-Chainable timeout on unknown task' ) ; console . log ( 'Full structure:' , this . _struct ) ; } else { console . log ( 'Async-Chainable timeout: Task #' , currentTaskIndex + 1 , '(' + this . _struct [ currentTaskIndex ] . type + ')' , 'elapsed timeout of' , this . _options . timeout + 'ms' ) ; } this . fire ( 'timeout' ) ; }


Input: Queue up a varable setter ( i . e . set a hash of variables in context ) [CODESPLIT] function set ( ) { var self = this ; argy ( arguments ) . ifForm ( '' , function ( ) { } ) . ifForm ( 'string scalar|array|object|date|regexp|null' , function ( id , value ) { var payload = { } ; payload [ id ] = value ; self . _struct . push ( { type : 'set' , payload : payload } ) ; } ) . ifForm ( 'object' , function ( obj ) { self . _struct . push ( { type : 'set' , payload : obj } ) ; } ) . ifForm ( 'function' , function ( callback ) { self . _struct . push ( { type : 'seriesArray' , payload : [ callback ] } ) ; } ) . ifForm ( 'string function' , function ( id , callback ) { var payload = { } ; payload [ id ] = callback ; self . _struct . push ( { type : 'seriesObject' , payload : payload } ) ; } ) . ifForm ( [ 'string' , 'string undefined' ] , function ( id ) { var payload = { } ; payload [ id ] = undefined ; self . _struct . push ( { type : 'set' , payload : payload } ) ; } ) . ifFormElse ( function ( form ) { throw new Error ( 'Unknown call style for .set():' + form ) ; } ) ; return self ; }


Input: Set a context items value Not to be confused with set () which is the chainable external visible version of this Unlike set () this function sets an item of _context immediately [CODESPLIT] function _set ( ) { var self = this ; argy ( arguments ) . ifForm ( '' , function ( ) { } ) . ifForm ( 'string scalar|array|object|date|regexp|null' , function ( id , value ) { self . _setRaw ( id , value ) ; } ) . ifForm ( 'object' , function ( obj ) { for ( var key in obj ) self . _setRaw ( key , obj [ key ] ) ; } ) . ifForm ( 'string function' , function ( id , callback ) { self . _setRaw ( id , callback . call ( this ) ) ; } ) . ifForm ( 'function' , function ( callback ) { // Expect func to return something which is then processed via _set self . _set ( callback . call ( this ) ) ; } ) . ifForm ( [ 'string' , 'string undefined' ] , function ( id ) { self . _setRaw ( id , undefined ) ; } ) . ifFormElse ( function ( form ) { throw new Error ( 'Unknown call style for .set():' + form ) ; } ) ; return self ; }


Input: Internal function executed at the end of the chain This can occur either in sequence ( i . e . no errors ) or a jump to this position ( i . e . an error happened somewhere ) [CODESPLIT] function _finalize ( err ) { // Sanity checks {{{ if ( this . _struct . length == 0 ) return ; // Finalize called on dead object - probably a defer() fired without an await() if ( this . _struct [ this . _struct . length - 1 ] . type != 'end' ) { throw new Error ( 'While trying to find an end point in the async-chainable structure the last item in the this._struct does not have type==end!' ) ; return ; } // }}} var self = this ; this . fire ( 'end' , function ( hookErr ) { self . _struct [ self . _struct . length - 1 ] . payload . call ( self . _options . context , err || hookErr ) ; if ( self . _options . autoReset ) self . reset ( ) ; } ) ; }


Input: Internal function to execute the next pending queue item This is usually called after the completion of every asyncChainable . run call [CODESPLIT] function _execute ( err ) { var self = this ; if ( err ) return this . _finalize ( err ) ; // An error has been raised - stop exec and call finalize now if ( ! self . _executing ) { // Never before run this object - run fire('start') and defer until it finishes self . _executing = true ; return self . fire . call ( self , 'start' , self . _execute . bind ( self ) ) ; } do { var redo = false ; if ( self . _structPointer >= self . _struct . length ) return this . _finalize ( err ) ; // Nothing more to execute in struct self . _deferCheck ( ) ; // Kick off any pending deferred items var currentExec = self . _struct [ self . _structPointer ] ; // Sanity checks {{{ if ( ! currentExec . type ) { throw new Error ( 'No type is specified for async-chainable structure at offset ' + self . _structPointer ) ; return self ; } // }}} self . _structPointer ++ ; // Skip step when function supports skipping if the argument is empty {{{ if ( [ 'parallelArray' , 'parallelObject' , 'forEachArray' , 'forEachObject' , 'seriesArray' , 'seriesObject' , 'deferArray' , 'deferObject' , 'set' ] . indexOf ( currentExec . type ) > - 1 && ( ! currentExec . payload || // Not set OR ( argy . isType ( currentExec . payload , 'array' ) && ! currentExec . payload . length ) || // An empty array ( argy . isType ( currentExec . payload , 'object' ) && ! Object . keys ( currentExec . payload ) . length ) // An empty object ) ) { currentExec . completed = true ; redo = true ; continue ; } // }}} switch ( currentExec . type ) { case 'forEachRange' : var iterArray = Array ( currentExec . max - currentExec . min + 1 ) . fill ( false ) ; self . runArray ( iterArray . map ( function ( v , i ) { var val = self . _context . _item = currentExec . min + i ; var index = self . _context . _key = i ; return function ( next ) { if ( currentExec . translate ) val = currentExec . translate ( val , index , iterArray . length ) ; run ( self . _options . context , currentExec . callback , next , [ val , index , iterArray . length ] ) ; } ; } ) , self . _options . limit , function ( err ) { currentExec . completed = true ; self . _execute ( err ) ; } ) ; break ; case 'forEachArray' : self . runArray ( currentExec . payload . map ( function ( item , iter ) { self . _context . _item = item ; self . _context . _key = iter ; return function ( next ) { run ( self . _options . context , currentExec . callback , next , [ item , iter ] ) ; } ; } ) , self . _options . limit , function ( err ) { currentExec . completed = true ; self . _execute ( err ) ; } ) ; break ; case 'forEachObject' : self . runArray ( Object . keys ( currentExec . payload ) . map ( function ( key ) { return function ( next ) { self . _context . _item = currentExec . payload [ key ] ; self . _context . _key = key ; run ( self . _options . context , currentExec . callback , function ( err , value ) { self . _set ( key , value ) ; // Allocate returned value to context next ( err ) ; } , [ currentExec . payload [ key ] , key ] ) ; } ; } ) , self . _options . limit , function ( err ) { currentExec . completed = true ; self . _execute ( err ) ; } ) ; break ; case 'forEachLateBound' : if ( ! currentExec . payload || ! currentExec . payload . length ) { // Payload is blank // Goto next chain currentExec . completed = true ; redo = true ; break ; } var resolvedPayload = self . getPath ( self . _context , currentExec . payload ) ; if ( ! resolvedPayload ) { // Resolved payload is blank // Goto next chain currentExec . completed = true ; redo = true ; break ; } // Replace own exec array with actual type of payload now we know what it is {{{ if ( argy . isType ( resolvedPayload , 'array' ) ) { currentExec . type = 'forEachArray' ; } else if ( argy . isType ( resolvedPayload , 'object' ) ) { currentExec . type = 'forEachObject' ; } else { throw new Error ( 'Cannot perform forEach over unknown object type: ' + argy . getType ( resolvedPayload ) ) ; } currentExec . payload = resolvedPayload ; self . _structPointer -- ; // Force re-eval of this chain item now its been replace with its real (late-bound) type redo = true ; // }}} break ; case 'mapArray' : var output = new Array ( currentExec . payload . length ) ; self . runArray ( currentExec . payload . map ( function ( item , iter ) { self . _context . _item = item ; self . _context . _key = iter ; return function ( next ) { run ( self . _options . context , currentExec . callback , function ( err , value ) { if ( err ) return next ( err ) ; output [ iter ] = value ; next ( ) ; } , [ item , iter ] ) ; } ; } ) , self . _options . limit , function ( err ) { currentExec . completed = true ; self . _set ( currentExec . output , output ) ; self . _execute ( err ) ; } ) ; break ; case 'mapObject' : var output = { } ; self . runArray ( Object . keys ( currentExec . payload ) . map ( function ( key ) { return function ( next ) { self . _context . _item = currentExec . payload [ key ] ; self . _context . _key = key ; run ( self . _options . context , currentExec . callback , function ( err , value , outputKey ) { output [ outputKey || key ] = value ; next ( err ) ; } , [ currentExec . payload [ key ] , key ] ) ; } ; } ) , self . _options . limit , function ( err ) { currentExec . completed = true ; self . _set ( currentExec . output , output ) ; self . _execute ( err ) ; } ) ; break ; case 'mapLateBound' : if ( ! currentExec . payload || ! currentExec . payload . length ) { // Payload is blank // Goto next chain currentExec . completed = true ; redo = true ; break ; } var resolvedPayload = self . getPath ( self . _context , currentExec . payload ) ; if ( ! resolvedPayload ) { // Resolved payload is blank // Goto next chain currentExec . completed = true ; redo = true ; break ; } // Replace own exec array with actual type of payload now we know what it is {{{ if ( argy . isType ( resolvedPayload , 'array' ) ) { currentExec . type = 'mapArray' ; } else if ( argy . isType ( resolvedPayload , 'object' ) ) { currentExec . type = 'mapObject' ; } else { throw new Error ( 'Cannot perform map over unknown object type: ' + argy . getType ( resolvedPayload ) ) ; } currentExec . payload = resolvedPayload ; self . _structPointer -- ; // Force re-eval of this chain item now its been replace with its real (late-bound) type redo = true ; // }}} break ; case 'parallelArray' : case 'seriesArray' : self . runArray ( currentExec . payload . map ( function ( task ) { return function ( next ) { run ( self . _options . context , task , next ) ; } ; } ) , currentExec . type == 'parallelArray' ? self . _options . limit : 1 , function ( err ) { currentExec . completed = true ; self . _execute ( err ) ; } ) ; break ; case 'seriesObject' : case 'parallelObject' : self . runArray ( Object . keys ( currentExec . payload ) . map ( function ( key ) { return function ( next ) { run ( self . _options . context , currentExec . payload [ key ] , function ( err , value ) { self . _set ( key , value ) ; // Allocate returned value to context next ( err ) ; } ) ; } ; } ) , currentExec . type == 'parallelObject' ? self . _options . limit : 1 , function ( err ) { currentExec . completed = true ; self . _execute ( err ) ; } ) ; break ; case 'race' : var hasResult = false ; var hasError = false ; self . runArray ( currentExec . payload . map ( function ( task ) { return function ( next ) { run ( self . _options . context , task , function ( err , taskResult ) { if ( err ) { hasError = true next ( err , taskResult ) ; } else if ( ! hasResult && ! hasError && taskResult !== null && typeof taskResult !== 'undefined' ) { self . _set ( currentExec . id , taskResult ) ; // Allocate returned value to context hasResult = true ; next ( '!RACEDONE!' , taskResult ) ; // Force an error to stop the run() function } else { next ( err , taskResult ) ; } } ) ; } ; } ) , self . _options . limit , function ( err , val ) { currentExec . completed = true ; // Override race finish error as it was just to stop the race and not a real one if ( err == '!RACEDONE!' ) return self . _execute ( ) ; self . _execute ( err ) ; } ) ; break ; case 'deferArray' : currentExec . payload . forEach ( function ( task ) { self . _deferAdd ( null , task , currentExec ) ; } ) ; redo = true ; break ; case 'deferObject' : Object . keys ( currentExec . payload ) . forEach ( function ( key ) { self . _deferAdd ( key , currentExec . payload [ key ] , currentExec ) ; } ) ; redo = true ; break ; case 'await' : // Await can operate in two modes, either payload=[] (examine all) else (examine specific keys) if ( ! currentExec . payload . length ) { // Check all tasks are complete if ( self . _struct . slice ( 0 , self . _structPointer - 1 ) . every ( function ( stage ) { // Examine all items UP TO self one and check they are complete return stage . completed ; } ) ) { // All tasks up to self point are marked as completed if ( _deferTimeoutHandle ) clearTimeout ( _deferTimeoutHandle ) ; currentExec . completed = true ; redo = true ; } else { self . _structPointer -- ; // At least one task is outstanding - rewind to self stage so we repeat on next resolution } } else { // Check certain tasks are complete by key if ( currentExec . payload . every ( function ( dep ) { // Examine all named dependencies return ! ! self . _context [ dep ] ; } ) ) { // All are present if ( _deferTimeoutHandle ) clearTimeout ( _deferTimeoutHandle ) ; currentExec . completed = true ; redo = true ; } else { self . _structPointer -- ; // At least one dependency is outstanding - rewind to self stage so we repeat on next resolution } } break ; case 'limit' : // Set the options.limit variable self . _options . limit = currentExec . payload ; currentExec . completed = true ; redo = true ; // Move on to next action break ; case 'timeout' : // Set the timeout function or its timeout value if ( currentExec . delay === false ) { // Disable self . _options . timeout = false ; } else { // Set the callback if one was passed if ( currentExec . callback ) self . _options . timeoutHandler = currentExec . callback ; // Set the delay if one was passed if ( currentExec . delay ) self . _options . timeout = currentExec . delay ; } currentExec . completed = true ; redo = true ; // Move to next action break ; case 'context' : // Change the self._options.context object self . _options . context = currentExec . payload ? currentExec . payload : self . _context ; // Set context (if null use internal context) currentExec . completed = true ; redo = true ; // Move on to next action break ; case 'set' : // Set a hash of variables within context Object . keys ( currentExec . payload ) . forEach ( function ( key ) { self . _set ( key , currentExec . payload [ key ] ) ; } ) ; currentExec . completed = true ; redo = true ; // Move on to next action break ; case 'end' : // self should ALWAYS be the last item in the structure and indicates the final function call this . _finalize ( ) ; break ; default : if ( this . _plugins [ currentExec . type ] ) { // Is there a plugin that should manage this? this . _plugins [ currentExec . type ] . call ( this , currentExec ) ; } else { throw new Error ( 'Unknown async-chainable exec type: ' + currentExec . type ) ; } return ; } } while ( redo ) ; }


Input: runArray () - dispatch an array of callbacks ( with a parallel run limit ) and run a callback when complete {{{ Internal function to run an array of functions ( usually in parallel ) Functions can be run in series by passing limit = 1 NOTE : Since this function is the central bottle - neck of the application code here is designed to run as efficiently as possible . This can make it rather messy and unpleasent to read in order to maximize thoughput . Series execution can be obtained by setting limit = 1 [CODESPLIT] function runArray ( tasks , limit , callback ) { var self = this ; var nextTaskOffset = 0 ; var running = 0 ; var err ; // Empty if ( ! tasks || ! tasks . length ) return callback ( ) ; // Timeout functionality {{{ var _timeoutTimer ; var resetTimeout = function ( setAgain ) { if ( _timeoutTimer ) clearTimeout ( _timeoutTimer ) ; if ( setAgain ) _timeoutTimer = self . _options . timeout ? setTimeout ( self . _options . timeoutHandler . bind ( self ) , self . _options . timeout ) : null ; } ; // }}} var taskFinish = function ( taskErr , taskResult ) { if ( taskErr ) err = taskErr ; -- running ; if ( err && ! running ) { resetTimeout ( false ) ; callback ( err ) ; } else if ( err ) { // Has an err - stop allocating until we empty resetTimeout ( false ) ; // Pass } else if ( ! running && nextTaskOffset > tasks . length - 1 ) { // Finished everything resetTimeout ( false ) ; callback ( err ) ; } else if ( nextTaskOffset < tasks . length ) { // Still more to alloc running ++ ; resetTimeout ( true ) ; setTimeout ( tasks [ nextTaskOffset ++ ] . bind ( this . _context , taskFinish ) ) ; } } ; var maxTasks = limit && limit <= tasks . length ? limit : tasks . length ; for ( var i = 0 ; i < maxTasks ; i ++ ) { running ++ ; setTimeout ( tasks [ i ] . bind ( this , taskFinish ) ) ; } resetTimeout ( true ) ; // Start initial timeout nextTaskOffset = maxTasks ; return this ; }


Input: }}} [CODESPLIT] function ( taskErr , taskResult ) { if ( taskErr ) err = taskErr ; -- running ; if ( err && ! running ) { resetTimeout ( false ) ; callback ( err ) ; } else if ( err ) { // Has an err - stop allocating until we empty resetTimeout ( false ) ; // Pass } else if ( ! running && nextTaskOffset > tasks . length - 1 ) { // Finished everything resetTimeout ( false ) ; callback ( err ) ; } else if ( nextTaskOffset < tasks . length ) { // Still more to alloc running ++ ; resetTimeout ( true ) ; setTimeout ( tasks [ nextTaskOffset ++ ] . bind ( this . _context , taskFinish ) ) ; } }


Input: Run a single function promise return promise factory or any other combination - then a callback when finished Take a function reference and treat it as a callback style function If the function returns a promise this behaviour is transformed into a callback style function [CODESPLIT] function run ( context , fn , finish , args ) { // Argument mangling {{{ if ( typeof context == 'function' ) { // called as run(fn, finish, args); args = finish ; finish = fn ; fn = context ; context = this ; } // }}} if ( isPromise ( fn ) ) { // Given a promise that has already resolved? fn . then ( function ( value ) { finish . apply ( context , [ null , value ] ) ; } ) . catch ( function ( err ) { finish . call ( context , err || 'An error occured' ) ; } ) ; } else if ( hasCallback ( fn ) ) { // Callback w/ (err, result) pattern var result = fn . apply ( context , args ? [ finish ] . concat ( args ) : [ finish ] ) ; if ( isPromise ( result ) ) { result . then ( function ( value ) { // Remap result from (val) => (err, val) finish . apply ( context , [ null , value ] ) ; } ) . catch ( function ( err ) { finish . call ( context , err || 'An error occured' ) ; } ) ; } } else { // Maybe either a promise or sync function? var result ; try { result = fn . apply ( context , args || [ ] ) ; // Run the function and see what it gives us } catch ( e ) { finish . call ( context , e ) ; } if ( isPromise ( result ) ) { // Got back a promise - attach to the .then() function result . then ( function ( value ) { // Remap result from (val) => (err, val) finish . apply ( context , [ null , value ] ) ; } ) . catch ( function ( err ) { finish . call ( context , err || 'An error occured' ) ; } ) ; } else { // Didn't provide back a promise - assume it was a sync function finish . apply ( context , [ null , result ] ) ; } } }


Input: Internal function to run a callback until it returns a falsy value [CODESPLIT] function runWhile ( iter , limit , callback ) { var index = 0 ; var hasExited = false ; var err ; var running = 0 ; if ( ! Number . isFinite ( limit ) ) limit = 10 ; var invoke = function ( ) { iter . call ( this . _context , function ( taskErr , taskResult ) { if ( taskErr ) err = taskErr ; if ( taskErr || ! taskResult ) hasExited = true ; -- running ; if ( err && ! running ) { callback ( err , res ) ; } else if ( running <= 0 && hasExited ) { callback ( err ) ; } else if ( ! hasExited ) { setTimeout ( invoke ) ; } } , index ++ ) ; } ; for ( var i = 0 ; i < limit ; i ++ ) { running ++ ; setTimeout ( invoke ) ; } return this ; }


Input: }}} Reset all state variables and return the object into a pristine condition [CODESPLIT] function reset ( ) { this . _struct = [ ] ; this . _structPointer = 0 ; var reAttachContext = ( this . _options . context == this . _context ) ; // Reattach the context pointer after reset? this . _context = { _struct : this . _struct , _structPointer : this . _structPointer , _options : this . _options , _deferredRunning : this . _deferredRunning , hook : this . hook . bind ( this ) , fire : this . fire . bind ( this ) , } ; if ( reAttachContext ) this . _options . context = this . _context ; }


Input: Hooks {{{ Set up a hook [CODESPLIT] function hook ( ) { var self = this ; argy ( arguments ) . ifForm ( '' , function ( ) { } ) . ifForm ( 'string function' , function ( hook , callback ) { // Attach to one hook if ( ! self . _hooks [ hook ] ) self . _hooks [ hook ] = [ ] ; self . _hooks [ hook ] . push ( { cb : callback } ) ; } ) . ifForm ( 'string string function' , function ( hook , id , callback ) { // Attach a named hook if ( ! self . _hooks [ hook ] ) self . _hooks [ hook ] = [ ] ; self . _hooks [ hook ] . push ( { id : id , cb : callback } ) ; } ) . ifForm ( 'string array function' , function ( hook , prereqs , callback ) { // Attach to a hook with prerequisites if ( ! self . _hooks [ hook ] ) self . _hooks [ hook ] = [ ] ; self . _hooks [ hook ] . push ( { prereqs : prereqs , cb : callback } ) ; } ) . ifForm ( 'string string array function' , function ( hook , id , prereqs , callback ) { // Attach a named hook with prerequisites if ( ! self . _hooks [ hook ] ) self . _hooks [ hook ] = [ ] ; self . _hooks [ hook ] . push ( { id : id , prereqs : prereqs , cb : callback } ) ; } ) . ifForm ( 'array function' , function ( hooks , callback ) { // Attach to many hooks hooks . forEach ( function ( hook ) { if ( ! self . _hooks [ hook ] ) self . _hooks [ hook ] = [ ] ; self . _hooks [ hook ] . push ( { cb : callback } ) ; } ) ; } ) . ifFormElse ( function ( form ) { throw new Error ( 'Unknown call style for .on(): ' + form ) ; } ) ; return self ; }


Input: Take a callback style function and return a hybrid ( callback OR promise ) wrapper @param { function } fn The function to transform @param { function } [ finish ] The callback to optionally call when done @return { function } The hybrid function which runs as a callback but could accept promises [CODESPLIT] function hybrid ( fn , cb ) { if ( typeof cb === 'function' ) { // Already in callback style - wrap the function so that cb gets called when it completes return function ( ) { var args = Array . prototype . slice . call ( arguments , 0 ) ; fn . apply ( this , [ cb ] . concat ( args ) ) ; } ; } else { // Wrap the function in a promise return function ( ) { var args = Array . prototype . slice . call ( arguments , 0 ) ; return new Promise ( function ( resolve , reject ) { fn . apply ( this , [ function ( err , res ) { if ( err ) { reject ( err ) ; } else { resolve ( res ) ; } } ] . concat ( args ) ) ; } ) ; } ; } }


Input: Return the first tag with a name = name [CODESPLIT] function tag ( name ) { if ( ! this . comment || ! this . comment . tags ) { return null ; } for ( var i = 0 ; i < this . comment . tags . length ; i ++ ) { var tagObj = this . comment . tags [ i ] ; if ( tagObj . name === name ) { return tagObj . value ; } } return null ; }


Input: A fixed - length storage mechanism for a value ( ideally a number ) with some statistics methods . Expires oldest values to Input is not type checked but non - numeric input will be considered NULL WRT the statistical methods . [CODESPLIT] function FixedValueHistory ( maxLength , initial ) { if ( ! ( this instanceof FixedValueHistory ) ) return new FixedValueHistory ( maxLength , initial ) if ( ! isNumber ( maxLength ) || maxLength == 0 ) { throw new Error ( "maxLength must be a positive number." ) } this . maxLength = Math . floor ( + maxLength ) if ( initial != null ) { this . push ( initial ) } }


Input: Constructor function takes the following paramters : [CODESPLIT] function ( path , maxAge , cronTime , options ) { this . job = null ; this . path = path ; this . maxAge = maxAge ; this . cronTime = cronTime ; this . options = util . _extend ( { } , defaultOptions ) ; if ( typeof options === 'object' && options !== null ) { this . options = util . _extend ( this . options , options ) ; } if ( this . options . start === true ) { this . start ( ) ; } }


Input: Helper functions Checks blackList - and whitList - regex against the given file name and returns if this file can be deleted . [CODESPLIT] function checkPattern ( file , blackList , whiteList ) { if ( util . isRegExp ( blackList ) && blackList . test ( file ) ) { return false ; } if ( util . isRegExp ( whiteList ) ) { if ( whiteList . test ( file ) ) { return true ; } return false ; } return true ; }


Input: / * internal helper functions [CODESPLIT] function createGetterSetter ( propName ) { function gs ( element , value ) { // if we have a value update if ( typeof value != 'undefined' ) { element . style [ propName ] = value ; } return window . getComputedStyle ( element ) [ propName ] ; } // attach the property name to the getter and setter gs . property = propName ; return gs ; }


Input: Construct a new Seven object . Optionally pass a SevenConfig object to set properties . Each property of the SevenConfig object is optional . If the passed in config contains bad values an exception will be thrown . [CODESPLIT] function Seven ( _a ) { var _b = _a === void 0 ? { } : _a , height = _b . height , width = _b . width , _c = _b . angle , angle = _c === void 0 ? 10 : _c , _d = _b . ratioLtoW , ratioLtoW = _d === void 0 ? 4 : _d , _e = _b . ratioLtoS , ratioLtoS = _e === void 0 ? 32 : _e , _f = _b . digit , digit = _f === void 0 ? Digit . BLANK : _f ; /** The cononical points for a horizontal segment for the given configuration. */ this . _horizontalSegmentGeometry = [ { x : 0 , y : 0 } , { x : 0 , y : 0 } , { x : 0 , y : 0 } , { x : 0 , y : 0 } , { x : 0 , y : 0 } , { x : 0 , y : 0 } ] ; /** The cononical points for a vertical segment for the given configuration. */ this . _verticalSegmentGeometry = [ { x : 0 , y : 0 } , { x : 0 , y : 0 } , { x : 0 , y : 0 } , { x : 0 , y : 0 } , { x : 0 , y : 0 } , { x : 0 , y : 0 } ] ; /** The x and y shifts that must be applied to each segment. */ this . _translations = [ { x : 0 , y : 0 , a : this . _horizontalSegmentGeometry } , { x : 0 , y : 0 , a : this . _verticalSegmentGeometry } , { x : 0 , y : 0 , a : this . _verticalSegmentGeometry } , { x : 0 , y : 0 , a : this . _horizontalSegmentGeometry } , { x : 0 , y : 0 , a : this . _verticalSegmentGeometry } , { x : 0 , y : 0 , a : this . _verticalSegmentGeometry } , { x : 0 , y : 0 , a : this . _horizontalSegmentGeometry } ] ; /** The segments, A-G of the digit. */ this . segments = [ new Segment ( ) , new Segment ( ) , new Segment ( ) , new Segment ( ) , new Segment ( ) , new Segment ( ) , new Segment ( ) ] ; this . _angleDegree = angle ; this . digit = digit ; this . _ratioLtoW = ratioLtoW ; this . _ratioLtoS = ratioLtoS ; this . _height = this . _width = 100 ; //initialize so checkConfig passes, and for default case this . _isHeightFixed = true ; if ( height !== undefined ) { this . _height = height ; } else if ( width !== undefined ) { this . _width = width ; this . _isHeightFixed = false ; } //else - neither specified, default to height=100 this . _positionSegments ( ) ; }


Input:
Create a new FriendsOfFriends Object with or without new javascript // mongoose is required var mongoose = require ( mongoose ) ; [CODESPLIT] function FriendsOfFriends ( mongoose , options ) { debug ( 'mongoose' , mongoose ) ; debug ( 'options' , options ) ; if ( ! ( this instanceof FriendsOfFriends ) ) { return new FriendsOfFriends ( mongoose , options ) ; } var friendship = require ( './friendship' ) , plugin = require ( './plugin' ) ; var defaults = { personModelName : 'Person' , friendshipModelName : 'Friendship' , friendshipCollectionName : undefined , } ; /**
     * The options defined for the module instance
     * @member      {Object} options
     * @memberOf    FriendsOfFriends
     * @property    {String} personModelName            - The modelName of the Person Schema. Default: `'Person'`
     * @property    {String} friendshipModelName        - The name to call the model to be compiled from the Friendship Schema. Default: `'Friendship'`
     * @property    {String|undefined} friendshipCollectionName   - The name to use for the Friendship Collection. Default: `undefined`.
     */ this . options = utils . extend ( defaults , options ) ; /**
     * The Friendship model
     * @member      {Model}     friendship
     * @memberOf    FriendsOfFriends
     * @see         {@link FriendshipModel}
     * @see         [moongoose models]{@link http://mongoosejs.com/docs/models.html}
     */ this . Friendship = friendship ( mongoose , this . options ) ; /**
     * Adds friends-of-friends functionality to an existing Schema
     * @function    FriendsOfFriends.plugin
     * @param       {Schema} schema     - The mongoose Schema that gets plugged
     * @param       {Object} options    - Options passed to the plugin
     * @see         {@link AccountModel}
     */ this . plugin = plugin ( mongoose ) ; }


Input: / * PUBLIC [CODESPLIT] function totalRx ( opts ) { if ( opts ) { opts . iface = opts . iface || 'lo' ; opts . units = opts . units || 'bytes' ; } else { opts = { iface : 'lo' , units : 'bytes' , } ; } var total = parseInt ( _parseProcNetDev ( ) [ opts . iface ] . bytes . receive ) ; var converted = _bytesTo ( total , opts . units ) ; return converted ; }


Input: NOTE : borrowed / modifed from https : // github . com / soldair / node - procfs - stats / blob / feca2a940805b31f9e7d5c0bd07c4e3f8d3d5303 / index . js#L343 TODO : more cleaning rename the one char variables to something more expressive [CODESPLIT] function _parseProcNetDev ( ) { var buf = fs . readFileSync ( '/proc/net/dev' ) ; var lines = buf . toString ( ) . trim ( ) . split ( '\n' ) ; var sections = lines . shift ( ) . split ( '|' ) ; var columns = lines . shift ( ) . trim ( ) . split ( '|' ) ; var s ; var l ; var c ; var p = 0 ; var map = { } ; var keys = [ ] ; for ( var i = 0 ; i < sections . length ; ++ i ) { s = sections [ i ] . trim ( ) ; l = sections [ i ] . length ; c = columns [ i ] . trim ( ) . split ( / \s+ / g ) ; while ( c . length ) { map [ keys . length ] = s ; keys . push ( c . shift ( ) ) ; } p += s . length + 1 ; } var retObj = { } ; lines . forEach ( function ( l ) { l = l . trim ( ) . split ( / \s+ / g ) ; var o = { } ; var iface ; for ( var i = 0 ; i < l . length ; ++ i ) { var s = map [ i ] ; //case for the Interface if ( s . indexOf ( '-' ) === s . length - 1 ) { iface = l [ i ] . substr ( 0 , l [ i ] . length - 1 ) ; //case for everything else } else { if ( ! o [ keys [ i ] ] ) { o [ keys [ i ] . toLowerCase ( ) ] = { } ; } o [ keys [ i ] . toLowerCase ( ) ] [ s . toLowerCase ( ) ] = l [ i ] ; } } retObj [ iface ] = o ; } ) ; return retObj ; }


Input: after dialog close wait for change [CODESPLIT] function onChange ( event ) { try { if ( remove ( ) ) { return ; } resolve ( Array . from ( input . files ) ) ; // actually got file(s) } catch ( error ) { reject ( error ) ; } }


Input: there are no properties on a RemoveObserver every object that went as ref through this function can be used as this in any of the RemoveObserver methods [CODESPLIT] function RemoveObserver_init ( ref , node ) { let self = Self . get ( node ) ; if ( ! self ) { self = new RemoveObserverPrivate ( node ) ; Self . set ( node , self ) ; } Self . set ( ref , self ) ; }


Input: jsdoc [CODESPLIT] function ( done ) { async . series ( [ function ( next ) { var child = child_process . exec ( 'jsdoc -c jsdoc.conf.json lib/' ) ; child . stdout . on ( 'data' , function ( data ) { console . log ( data ) ; } ) ; child . stderr . on ( 'data' , function ( data ) { console . log ( 'stderr: ' + data ) ; var err = new Error ( 'error spawning: ' , cmd ) ; console . log ( err ) ; next ( err ) ; } ) ; child . on ( 'close' , function ( code ) { if ( code === 0 ) { next ( ) ; } else { next ( new Error ( 'error spawning:' , cmd ) ) ; } } ) ; } , function ( next ) { var cmd = util . format ( 'cp -r doc/%s/%s/* doc/' , package . name , package . version ) ; var child = child_process . exec ( cmd ) ; child . stdout . on ( 'data' , function ( data ) { console . log ( data ) ; } ) ; child . stderr . on ( 'data' , function ( data ) { console . log ( 'stderr: ' + data ) ; var err = new Error ( 'error spawning: ' , cmd ) ; console . log ( err ) ; next ( err ) ; } ) ; child . on ( 'close' , function ( code ) { if ( code === 0 ) { next ( ) ; } else { next ( new Error ( 'error spawning jsdoc' ) ) ; } } ) ; } , function ( next ) { var cmd = 'rm -rf doc/' + package . name + '/' ; var child = child_process . exec ( cmd ) ; child . stdout . on ( 'data' , function ( data ) { console . log ( data ) ; } ) ; child . stderr . on ( 'data' , function ( data ) { console . log ( 'stderr: ' + data ) ; var err = new Error ( 'error spawning: ' , cmd ) ; console . log ( err ) ; next ( err ) ; } ) ; child . on ( 'close' , function ( code ) { console . log ( 'child process exited with code ' + code ) ; if ( code === 0 ) { next ( ) ; } else { next ( new Error ( 'error spawning jsdoc' ) ) ; } } ) ; } ] , function ( err , results ) { if ( err ) done ( err ) ; else done ( ) ; } ) ; }


Input: jsdoc2md [CODESPLIT] function ( done ) { console . log ( 'generating markdown docs...' ) ; var tasks = { } , taskNames = [ 'index' , 'friendship' , 'plugin' , 'relationships' ] ; // go through each task name taskNames . forEach ( function ( name ) { // add this task function to the object tasks [ name ] = function ( done ) { var sourceFilename = 'lib/' + name + '.js' ; var targetFilename = 'doc/' + name + '.md' ; console . log ( sourceFilename + ' -> ' + targetFilename ) ; var reader = fs . createReadStream ( sourceFilename ) ; // create a write stream to the new markdown file whose name is the task name var writer = fs . createWriteStream ( targetFilename , { flags : 'w+' } ) . on ( 'finish' , done ) ; // now pipe each file to jsdoc2md then pipe its output to  // the write stream reader . pipe ( jsdoc2md ( ) ) . pipe ( writer ) ; } ; } ) ; // now run our named tasks in parallel with async async . parallel ( tasks , function ( err , results ) { if ( err ) done ( err ) ; else { console . log ( 'finished generating markdown docs.' ) ; done ( ) ; } } ) ; }


Input: Finds and parses the property chains in an expression . [CODESPLIT] function parsePropertyChains ( expr ) { var parsedExpr = '' , chain ; // allow recursion (e.g. into function args) by resetting propertyRegex // This is more efficient than creating a new regex for each chain, I assume var prevCurrentIndex = currentIndex ; var prevLastIndex = propertyRegex . lastIndex ; currentIndex = 0 ; propertyRegex . lastIndex = 0 ; while ( ( chain = nextChain ( expr ) ) !== false ) { parsedExpr += chain ; } // Reset indexes currentIndex = prevCurrentIndex ; propertyRegex . lastIndex = prevLastIndex ; return parsedExpr ; }


Input: Handles a function to be called in its correct scope Finds the end of the function and processes the arguments [CODESPLIT] function parseFunction ( link , index , expr ) { var call = getFunctionCall ( expr ) ; // Always call functions in the scope of the object they're a member of if ( index === 0 ) { link = addThisOrGlobal ( link ) ; } else { link = '_ref' + currentReference + link ; } var calledLink = link + '(~~insideParens~~)' ; link = 'typeof ' + link + ' !== \'function\' ? void 0 : ' + calledLink ; var insideParens = call . slice ( 1 , - 1 ) ; if ( expr . charAt ( propertyRegex . lastIndex ) === '.' ) { currentReference = ++ referenceCount ; var ref = '_ref' + currentReference ; link = '(' + ref + ' = (' + link + ')) == null ? void 0 : ' ; } var ref = currentReference ; link = link . replace ( '~~insideParens~~' , parsePropertyChains ( insideParens ) ) ; currentReference = ref ; return link ; }


Input: Handles a bracketed expression to be parsed [CODESPLIT] function parseBrackets ( link , index , expr ) { var call = getFunctionCall ( expr ) ; var insideBrackets = call . slice ( 1 , - 1 ) ; var evaledLink = parsePart ( link , index ) ; index += 1 ; link = '[~~insideBrackets~~]' ; if ( expr . charAt ( propertyRegex . lastIndex ) === '.' ) { link = parsePart ( link , index ) ; } else { link = '_ref' + currentReference + link ; } link = evaledLink + link ; var ref = currentReference ; link = link . replace ( '~~insideBrackets~~' , parsePropertyChains ( insideBrackets ) ) ; currentReference = ref ; return link ; }


Input: returns the call part of a function ( e . g . test ( 123 ) would return ( 123 ) ) [CODESPLIT] function getFunctionCall ( expr ) { var startIndex = propertyRegex . lastIndex ; var open = expr . charAt ( startIndex - 1 ) ; var close = parens [ open ] ; var endIndex = startIndex - 1 ; var parenCount = 1 ; while ( endIndex ++ < expr . length ) { var ch = expr . charAt ( endIndex ) ; if ( ch === open ) parenCount ++ ; else if ( ch === close ) parenCount -- ; if ( parenCount === 0 ) break ; } currentIndex = propertyRegex . lastIndex = endIndex + 1 ; return open + expr . slice ( startIndex , endIndex ) + close ; }


Input: Prepends reference variable definitions [CODESPLIT] function addReferences ( expr ) { if ( referenceCount ) { var refs = [ ] ; for ( var i = 1 ; i <= referenceCount ; i ++ ) { refs . push ( '_ref' + i ) ; } expr = 'var ' + refs . join ( ', ' ) + ';\n' + expr ; } return expr ; }


Input: Run once and lastest one [CODESPLIT] function ( fn ) { var pending var hasNext function next ( ) { setTimeout ( function ( ) { if ( pending === false ) return pending = false if ( hasNext ) { hasNext = false fn ( next ) } } , 50 ) // call after gulp ending handler done } return function ( ) { if ( pending ) return ( hasNext = true ) pending = true fn ( next ) } }


Input: Minimal assert function [CODESPLIT] function assert ( t , m ) { if ( ! t ) { var err = new AssertionError ( m ) if ( Error . captureStackTrace ) Error . captureStackTrace ( err , assert ) throw err } }


Input: a custom bind function to bind arguments to a function without binding the context [CODESPLIT] function bindArguments ( func ) { function binder ( ) { return func . apply ( this , args . concat ( slice . call ( arguments ) ) ) ; } var args = slice . call ( arguments , 1 ) ; return binder ; }


Input: function to convert pattern ID to route ID [CODESPLIT] function getRouteIndexFromPatternId ( pattern : string | number ) : number { const pat = transitiveNetwork . patterns . find ( p => p . pattern_id === String ( pattern ) ) if ( ! pat ) return - 1 return transitiveNetwork . routes . findIndex ( r => r . route_id === pat . route_id ) }


Input: Get the most common paths [CODESPLIT] function getCommonPaths ( { getRouteIndexFromPatternId , log , origin , paths } : { getRouteIndexFromPatternId : ( string | number ) => number , log : Function , origin : Origin , paths : Array < PathDescriptor > } ) : Array < StopPatternStops > { paths . sort ( byStopIdAndPathIndex ) const pathCounts = paths . reduce ( countCommonPaths , [ ] ) pathCounts . sort ( byCount ) log ( ` ${ pathCounts . length } ` ) if ( pathCounts . length > MAX_TRANSITIVE_PATHS ) { log ( ` ${ pathCounts . length - MAX_TRANSITIVE_PATHS } ${ pathCounts [ MAX_TRANSITIVE_PATHS ] . count } ${ paths . length } ` ) } let allStopPatternStopSets = pathCounts . slice ( 0 , MAX_TRANSITIVE_PATHS ) . map ( ( p ) => p . path ) . filter ( uniquePathIds ) // uniquify the paths . map ( ( p ) => getStopPatternStopSets ( { log , pathDescriptor : p , origin } ) ) const inPathCount = allStopPatternStopSets . length // Sort paths by the sequence of routes they use, and choose an example, // eliminating the multiple-board/transfer-stops problem allStopPatternStopSets . sort ( ( p1 , p2 ) => { if ( p1 . length < p2 . length ) return - 1 else if ( p1 . length > p2 . length ) return 1 else { for ( let i = 0 ; i < p1 . length ; i ++ ) { const r1 = getRouteIndexFromPatternId ( p1 [ i ] [ 1 ] ) const r2 = getRouteIndexFromPatternId ( p2 [ i ] [ 1 ] ) if ( r1 < r2 ) return - 1 if ( r1 > r2 ) return 1 } // identical patterns return 0 } } ) allStopPatternStopSets = allStopPatternStopSets . filter ( ( p , i , a ) => { if ( i === 0 ) return true const prev = a [ i - 1 ] if ( p . length !== prev . length ) return true for ( let s = 0 ; s < p . length ; s ++ ) { const r1 = getRouteIndexFromPatternId ( p [ s ] [ 1 ] ) const r2 = getRouteIndexFromPatternId ( prev [ s ] [ 1 ] ) if ( r1 !== r2 ) { return true } } return false } ) const pathCountAfterMultiTransfer = allStopPatternStopSets . length // eliminate longer paths if there is a shorter path that is a subset // (eliminate the short access/egress/transfer leg problem) allStopPatternStopSets = allStopPatternStopSets . filter ( ( path , i , rest ) => { for ( const otherPath of rest ) { // longer paths cannot be subsets. Also don't evaluate the same path. if ( otherPath . length >= path . length ) continue let otherPathIsSubset = true const routes = path . map ( seg => getRouteIndexFromPatternId ( seg [ 1 ] ) ) for ( const seg of otherPath ) { if ( routes . indexOf ( getRouteIndexFromPatternId ( seg [ 1 ] ) ) === - 1 ) { otherPathIsSubset = false break } } if ( otherPathIsSubset ) { return false } } return true } ) log ( ` ${ inPathCount } ${ pathCountAfterMultiTransfer } ${ allStopPatternStopSets . length } ` ) return allStopPatternStopSets }


Input: Bundle similar journeys in transitive data together . Works by computing a score for each segment based on where the endpoints are relative to each other . It might also make sense to use a metric based on speed so that a very slow bus isn t bundled with a fast train but we don t currently do this . [CODESPLIT] function clusterJourneys ( { journeys , log , patterns , stops } : { journeys : Array < Journey > , log : Function , patterns : Array < Pattern > , stops : Array < Stop > } ) { // perform hierarchical clustering on journeys // see e.g. James et al., _An Introduction to Statistical Learning, with Applications in R_. New York: Springer, 2013, pg. 395. // convert to arrays const clusters = journeys . map ( ( j ) => [ j ] ) const inputSize = journeys . length // prevent infinite loop, makes sense only to loop until there's just one cluster left while ( clusters . length > 1 ) { // find the minimum dissimilarity let minDis = Infinity let minI = 0 let minJ = 0 for ( let i = 1 ; i < clusters . length ; i ++ ) { for ( let j = 0 ; j < i ; j ++ ) { const d = getClusterDissimilarity ( clusters [ i ] , clusters [ j ] , { patterns , stops } ) if ( d < minDis ) { minDis = d minI = i minJ = j } } } log ( ` ${ minDis } ` ) if ( minDis > MAX_DISSIMILARITY ) break // cluster the least dissimilar clusters clusters [ minI ] = clusters [ minI ] . concat ( clusters [ minJ ] ) clusters . splice ( minJ , 1 ) // remove clusters[j] } log ( ` ${ inputSize } ${ clusters . length } ` ) // merge journeys together return clusters . map ( ( c ) => { return c . reduce ( ( j1 , j2 ) => { for ( let i = 0 ; i < j1 . segments . length ; i ++ ) { if ( j1 . segments [ i ] . type !== 'TRANSIT' ) continue // convert to pattern groups if ( ! j1 . segments [ i ] . patterns ) { j1 . segments [ i ] . patterns = [ { ... j1 . segments [ i ] } ] j1 . segments [ i ] . pattern_id = j1 . segments [ i ] . from_stop_index = j1 . segments [ i ] . to_stop_index = undefined } // don't modify from and to indices, Transitive will use the stops from the first pattern // TODO replace with "places" (e.g. "Farragut Square Area") j1 . segments [ i ] . patterns . push ( { ... j2 . segments [ i ] } ) } return j1 } ) } ) }


Input: Get the dissimilarity between two clusters using complete linkages ( see James et al . _An Introduction to Statistical Learning with Applications in R_ . New York : Springer 2013 pg . 395 . ) [CODESPLIT] function getClusterDissimilarity ( c1 : Array < Journey > , c2 : Array < Journey > , { patterns , stops } : { patterns : Array < Pattern > , stops : Array < Stop > } ) : number { let dissimilarity = 0 for ( const j1 of c1 ) { for ( const j2 of c2 ) { // if they are not the same length, don't cluster them if ( j1 . segments . length !== j2 . segments . length ) return Infinity // otherwise compute maximum dissimilarity of stops at either start or end for ( let segment = 0 ; segment < j1 . segments . length ; segment ++ ) { const s1 = j1 . segments [ segment ] const s2 = j2 . segments [ segment ] // if one has a walk segment where the other has a transit segment these // are not comparable if ( s1 . type !== s2 . type ) return Infinity // Only cluster  on the stop positions which we get from transit segments if ( s1 . type !== 'WALK' ) { dissimilarity = Math . max ( dissimilarity , segmentDissimilarity ( s1 , s2 , { patterns , stops } ) ) // no point in continuing, these won't be merged if ( dissimilarity > MAX_DISSIMILARITY ) return Infinity } } } } return dissimilarity }


Input: return the dissimilarity between two individual transit segments ( each with only a single pattern not yet merged ) [CODESPLIT] function segmentDissimilarity ( s1 : Segment , s2 : Segment , { patterns , stops } : { patterns : Array < Pattern > , stops : Array < Stop > } ) : number { const pat1 = patterns . find ( ( p ) => p . pattern_id === s1 . pattern_id ) const pat2 = patterns . find ( ( p ) => p . pattern_id === s2 . pattern_id ) if ( ! pat1 || ! pat2 ) return Infinity const s1f = s1 . from_stop_index const s1t = s1 . to_stop_index const s2f = s2 . from_stop_index const s2t = s2 . to_stop_index if ( s1f == null || s1t == null || s2f == null || s2t == null ) return Infinity function findStop ( id : string ) : ? Stop { return stops . find ( ( stop ) => stop . stop_id === id ) } const from1 = findStop ( pat1 . stops [ s1f ] . stop_id ) const to1 = findStop ( pat1 . stops [ s1t ] . stop_id ) const from2 = findStop ( pat2 . stops [ s2f ] . stop_id ) const to2 = findStop ( pat2 . stops [ s2t ] . stop_id ) if ( ! from1 || ! from2 || ! to1 || ! to2 ) return Infinity const d1 = stopDistance ( from1 , from2 ) const d2 = stopDistance ( to1 , to2 ) return Math . max ( d1 , d2 ) }


Input: return the Ersatz ( squared ) distance between two stops in undefined units [CODESPLIT] function stopDistance ( s1 : Stop , s2 : Stop ) : number { const cosLat = Math . cos ( s1 . stop_lat * Math . PI / 180 ) return Math . pow ( s1 . stop_lat - s2 . stop_lat , 2 ) + Math . pow ( s1 . stop_lon * cosLat - s2 . stop_lon * cosLat , 2 ) }


Input: Produces an object with the opener and closer exception values [CODESPLIT] function getExceptions ( ) { const openers = [ ] ; const closers = [ ] ; if ( options . braceException ) { openers . push ( '{' ) ; closers . push ( '}' ) ; } if ( options . bracketException ) { openers . push ( '[' ) ; closers . push ( ']' ) ; } if ( options . parenException ) { openers . push ( '(' ) ; closers . push ( ')' ) ; } if ( options . empty ) { openers . push ( ')' ) ; closers . push ( '(' ) ; } return { openers , closers } ; }


Input: Determines if an opener paren should have a missing space after it [CODESPLIT] function shouldOpenerHaveSpace ( left , right ) { if ( sourceCode . isSpaceBetweenTokens ( left , right ) ) { return false ; } if ( ALWAYS ) { if ( astUtils . isClosingParenToken ( right ) ) { return false ; } return ! isOpenerException ( right ) ; } return isOpenerException ( right ) ; }


Input: Determines if an closer paren should have a missing space after it [CODESPLIT] function shouldCloserHaveSpace ( left , right ) { if ( astUtils . isOpeningParenToken ( left ) ) { return false ; } if ( sourceCode . isSpaceBetweenTokens ( left , right ) ) { return false ; } if ( ALWAYS ) { return ! isCloserException ( left ) ; } return isCloserException ( left ) ; }


Input: Determines if an opener paren should not have an existing space after it [CODESPLIT] function shouldOpenerRejectSpace ( left , right ) { if ( right . type === 'Line' ) { return false ; } if ( ! astUtils . isTokenOnSameLine ( left , right ) ) { return false ; } if ( ! sourceCode . isSpaceBetweenTokens ( left , right ) ) { return false ; } if ( ALWAYS ) { return isOpenerException ( right ) ; } return ! isOpenerException ( right ) ; }


Input: Determines if an closer paren should not have an existing space after it [CODESPLIT] function shouldCloserRejectSpace ( left , right ) { if ( astUtils . isOpeningParenToken ( left ) ) { return false ; } if ( ! astUtils . isTokenOnSameLine ( left , right ) ) { return false ; } if ( ! sourceCode . isSpaceBetweenTokens ( left , right ) ) { return false ; } if ( ALWAYS ) { return isCloserException ( left ) ; } return ! isCloserException ( left ) ; }


Input: set a value as configurable and non - enumerable [CODESPLIT] function defineConfigurable ( obj , key , val ) { Object . defineProperty ( obj , key , { configurable : true , enumerable : false , writable : true , value : val } ) ; }


Input: 7 . 1 . 4 ToInteger [CODESPLIT] function ToInteger ( argument ) { var number = + argument ; if ( number !== number ) { return 0 ; } if ( number === 0 || number === Infinity || number === - Infinity ) { return number ; } return ( number >= 0 ? 1 : - 1 ) * Math . floor ( Math . abs ( number ) ) ; }


Input: 7 . 1 . 15 ToLength [CODESPLIT] function ToLength ( argument ) { var len = ToInteger ( argument ) ; return len <= 0 ? 0 : Math . min ( len , Math . pow ( 2 , 53 ) - 1 ) ; }


Input: 7 . 2 . 3 SameValue ( x y ) [CODESPLIT] function SameValue ( x , y ) { if ( typeof x !== typeof y ) { return false ; } if ( Type ( x ) === 'undefined' ) { return true ; } if ( Type ( x ) === 'number' ) { if ( x !== x && y !== y ) { return true ; } if ( x === 0 ) { return 1 / x === 1 / y ; } } return x === y ; }


Input: 7 . 4 . 2 IteratorNext ( iterator value ) [CODESPLIT] function IteratorNext ( iterator , value ) { var result = iterator . next ( value ) ; if ( Type ( result ) !== 'object' ) { throw TypeError ( ) ; } return result ; }


Input: 7 . 4 . 5 IteratorStep ( iterator ) [CODESPLIT] function IteratorStep ( iterator ) { var result = IteratorNext ( iterator ) ; return IteratorComplete ( result ) === true ? false : result ; }


Input: 7 . 4 . 6 CreateIterResultObject ( value done ) [CODESPLIT] function CreateIterResultObject ( value , done ) { if ( Type ( done ) !== 'boolean' ) { throw TypeError ( ) ; } return { value : value , done : done } ; }


Input: 8 . 4 . 1 EnqueueTask ( queueName task arguments ) not a real shim but good enough [CODESPLIT] function EnqueueTask ( task , args ) { if ( typeof setImmediate === 'function' ) { setImmediate ( function ( ) { task . apply ( null , args ) ; } ) ; } else { setTimeout ( function ( ) { task . apply ( null , args ) ; } , 0 ) ; } }


Input: 22 . 1 . 5 . 1 CreateArrayIterator Abstract Operation [CODESPLIT] function CreateArrayIterator ( array , kind ) { var O = ToObject ( array ) , iterator = Object . create ( ArrayIteratorPrototype ) ; defineInternal ( iterator , '[[IteratedObject]]' , O ) ; defineInternal ( iterator , '[[ArrayIteratorNextIndex]]' , 0 ) ; defineInternal ( iterator , '[[ArrayIteratorKind]]' , kind ) ; return iterator ; }


Input: 25 . 4 . 1 . 1 . 1 IfAbruptRejectPromise ( value capability ) [CODESPLIT] function IfAbruptRejectPromise ( value , capability ) { try { capability [ '[[Reject]]' ] . call ( undefined , [ value ] ) ; } catch ( e ) { return e ; } return capability ; }


Input: 25 . 4 . 1 . 4 . 1 Promise Resolve Functions [CODESPLIT] function PromiseResolve ( ) { return function F ( resolution ) { var promise = F [ '[[Promise]]' ] , reactions ; if ( Type ( promise ) !== 'object' ) { throw TypeError ( ) ; } if ( promise [ '[[PromiseStatus]]' ] !== 'unresolved' ) { return undefined ; } reactions = promise [ '[[PromiseResolveReactions]]' ] ; defineInternal ( promise , '[[PromiseResult]]' , resolution ) ; defineInternal ( promise , '[[PromiseResolveReactions]]' , undefined ) ; defineInternal ( promise , '[[PromiseRejectReactions]]' , undefined ) ; defineInternal ( promise , '[[PromiseStatus]]' , 'has-resolution' ) ; return TriggerPromiseReactions ( reactions , resolution ) ; } ; }


Input: 25 . 4 . 1 . 5 NewPromiseCapability ( C ) [CODESPLIT] function NewPromiseCapability ( C ) { var promise ; if ( ! IsConstructor ( C ) ) { throw TypeError ( ) ; } try { promise = Object . create ( C . prototype ) ; } catch ( e ) { return e ; } return CreatePromiseCapabilityRecord ( promise , C ) ; }


Input: 25 . 4 . 1 . 5 . 1 CreatePromiseCapabilityRecord ( promise constructor ) [CODESPLIT] function CreatePromiseCapabilityRecord ( promise , constructor ) { var promiseCapability = { } , executor , constructorResult ; defineInternal ( promiseCapability , '[[Promise]]' , promise ) ; defineInternal ( promiseCapability , '[[Resolve]]' , undefined ) ; defineInternal ( promiseCapability , '[[Reject]]' , undefined ) ; executor = new GetCapabilitiesExecutor ( ) ; defineInternal ( executor , '[[Capability]]' , promiseCapability ) ; try { constructorResult = constructor . call ( promise , executor ) ; } catch ( e ) { return e ; } if ( ! IsCallable ( promiseCapability [ '[[Resolve]]' ] ) ) { throw TypeError ( ) ; } if ( ! IsCallable ( promiseCapability [ '[[Reject]]' ] ) ) { throw TypeError ( ) ; } if ( typeof constructorResult === 'object' && ! SameValue ( promise , constructorResult ) ) { throw TypeError ( ) ; } return promiseCapability ; }


Input: 25 . 4 . 1 . 5 . 2 GetCapabilitiesExecutor Functions [CODESPLIT] function GetCapabilitiesExecutor ( ) { return function F ( resolve , reject ) { var promiseCapability = F [ '[[Capability]]' ] ; if ( Type ( promiseCapability [ '[[Resolve]]' ] ) !== 'undefined' ) { throw TypeError ( ) ; } if ( Type ( promiseCapability [ '[[Reject]]' ] ) !== 'undefined' ) { throw TypeError ( ) ; } defineInternal ( promiseCapability , '[[Resolve]]' , resolve ) ; defineInternal ( promiseCapability , '[[Reject]]' , reject ) ; } ; }


Input: 25 . 4 . 1 . 7 TriggerPromiseReactions ( reactions argument ) [CODESPLIT] function TriggerPromiseReactions ( reactions , argument ) { reactions . forEach ( function ( reaction ) { EnqueueTask ( PromiseReactionTask , [ reaction , argument ] ) ; } ) ; }


Input: 25 . 4 . 1 . 8 UpdatePromiseFromPotentialThenable ( x promiseCapability ) [CODESPLIT] function UpdatePromiseFromPotentialThenable ( x , promiseCapability ) { var then , rejectResult , thenCallResult ; if ( Type ( x ) !== 'object' ) { return 'not a thenable' ; } try { then = x . then ; } catch ( e ) { rejectResult = promiseCapability [ '[[Reject]]' ] . call ( undefined , e ) ; return null ; } if ( ! IsCallable ( then ) ) { return 'not a thenable' ; } try { thenCallResult = then . call ( x , promiseCapability [ '[[Resolve]]' ] , promiseCapability [ '[[Reject]]' ] ) ; } catch ( e ) { rejectResult = promiseCapability [ '[[Reject]]' ] . call ( undefined , e ) ; return null ; } return null ; }


Input: 25 . 4 . 2 . 1 PromiseReactionTask ( reaction argument ) [CODESPLIT] function PromiseReactionTask ( reaction , argument ) { var promiseCapability = reaction [ '[[Capabilities]]' ] , handler = reaction [ '[[Handler]]' ] , handlerResult , selfResolutionError , updateResult ; try { handlerResult = handler . call ( undefined , argument ) ; } catch ( e ) { return promiseCapability [ '[[Reject]]' ] . call ( undefined , e ) ; } if ( SameValue ( handlerResult , promiseCapability [ '[[Promise]]' ] ) ) { selfResolutionError = TypeError ( ) ; return promiseCapability [ '[[Reject]]' ] . call ( undefined , selfResolutionError ) ; } updateResult = UpdatePromiseFromPotentialThenable ( handlerResult , promiseCapability ) ; if ( updateResult === 'not a thenable' ) { return promiseCapability [ '[[Resolve]]' ] . call ( undefined , handlerResult ) ; } return undefined ; }


Input: 25 . 4 . 3 . 1 Promise ( executor ) [CODESPLIT] function Promise ( executor ) { var promise = this ; if ( ! IsCallable ( executor ) ) { throw TypeError ( 'Invalid executor' ) ; } if ( Type ( promise ) !== 'object' ) { throw TypeError ( 'Invalid promise' ) ; } if ( Type ( promise [ '[[PromiseStatus]]' ] ) !== 'undefined' ) { throw TypeError ( ) ; } defineInternal ( this , '[[PromiseConstructor]]' , Promise ) ; return InitializePromise ( promise , executor ) ; }


Input: 25 . 4 . 3 . 1 . 1 InitializePromise ( promise executor ) [CODESPLIT] function InitializePromise ( promise , executor ) { var resolve , reject , completion , status ; if ( Type ( promise [ '[[PromiseStatus]]' ] ) !== 'undefined' ) { throw TypeError ( ) ; } if ( ! IsCallable ( executor ) ) { throw TypeError ( ) ; } defineInternal ( promise , '[[PromiseStatus]]' , 'unresolved' ) ; defineInternal ( promise , '[[PromiseResolveReactions]]' , [ ] ) ; defineInternal ( promise , '[[PromiseRejectReactions]]' , [ ] ) ; resolve = CreateResolveFunction ( promise ) ; reject = CreateRejectFunction ( promise ) ; try { completion = executor . call ( undefined , resolve , reject ) ; } catch ( e ) { try { status = reject . call ( undefined , e ) ; } catch ( e ) { return e ; } } return promise ; }


Input: 25 . 4 . 5 . 3 . 2 PromiseResolutionHandlerFunctions [CODESPLIT] function PromiseResolutionHandlerFunction ( ) { return function F ( x ) { var promise = F [ '[[Promise]]' ] , fulfillmentHandler = F [ '[[FulfillmentHandler]]' ] , rejectionHandler = F [ '[[RejectionHandler]]' ] , selfResolutionError , C , promiseCapability , updateResult ; if ( SameValue ( x , promise ) ) { selfResolutionError = TypeError ( ) ; return rejectionHandler . call ( undefined , selfResolutionError ) ; } C = promise [ '[[PromiseConstructor]]' ] ; try { promiseCapability = NewPromiseCapability ( C ) ; } catch ( e ) { return e ; } try { updateResult = UpdatePromiseFromPotentialThenable ( x , promiseCapability ) ; } catch ( e ) { return e ; } if ( updateResult !== 'not a thenable' ) { return promiseCapability [ '[[Promise]]' ] . then ( fulfillmentHandler , rejectionHandler ) ; } return fulfillmentHandler . call ( undefined , x ) ; } ; }


Input: custom event stuff [CODESPLIT] function ( target , sequence , t ) { //t==trigger (usually a 'click'ish event) sequence = sequence . split ( _ . splitRE ) ; for ( var i = 0 , e , props ; i < sequence . length && ( ! e || ! e . isSequenceStopped ( ) ) ; i ++ ) { props = _ . parse ( sequence [ i ] ) ; if ( props ) { props . sequence = sequence ; if ( e ) { props . previousEvent = e ; } if ( t ) { props . trigger = t ; } _ . controls ( props , target , sequence , i ) ; e = _ . event ( target , props ) ; } } return e ; }


Input: native DOM and event stuff [CODESPLIT] function ( e ) { var el = e . target , attr , type = e . type , key = type . indexOf ( 'key' ) === 0 ? e . which || e . keyCode || '' : '' , special = _ . special [ type + key ] ; if ( el && special ) { type = special ( e , el , el . nodeName . toLowerCase ( ) ) ; if ( ! type ) { return ; } // special said to ignore it! } el = _ . find ( el , type ) , attr = _ . attr ( el , type ) ; if ( attr ) { _ . all ( el , attr , e ) ; if ( type === 'click' && ! _ . boxRE . test ( el . type ) ) { e . preventDefault ( ) ; } } }


Input: extension hooks [CODESPLIT] function ( el , sequence ) { if ( typeof el === "string" ) { sequence = el ; el = document ; } return _ . all ( el , sequence || _ . attr ( el , 'click' ) ) ; }


Input: -------------------------------------------------------------------------- Helpers -------------------------------------------------------------------------- Reports that there shouldn t be a space after the first token [CODESPLIT] function reportNoBeginningSpace ( node , token , tokenAfter ) { context . report ( { node : node , loc : token . loc . start , message : 'There should be no space after \'' + token . value + '\'' , fix : function ( fixer ) { return fixer . removeRange ( [ token . range [ 1 ] , tokenAfter . range [ 0 ] ] ) ; } } ) ; }


Input: Reports that there shouldn t be a space before the last token [CODESPLIT] function reportNoEndingSpace ( node , token , tokenBefore ) { context . report ( { node : node , loc : token . loc . start , message : 'There should be no space before \'' + token . value + '\'' , fix : function ( fixer ) { return fixer . removeRange ( [ tokenBefore . range [ 1 ] , token . range [ 0 ] ] ) ; } } ) ; }


Input: Reports that there should be a space after the first token [CODESPLIT] function reportRequiredBeginningSpace ( node , token ) { context . report ( { node : node , loc : token . loc . start , message : 'A space is required after \'' + token . value + '\'' , fix : function ( fixer ) { return fixer . insertTextAfter ( token , ' ' ) ; } } ) ; }


Input: Reports that there should be a space before the last token [CODESPLIT] function reportRequiredEndingSpace ( node , token ) { context . report ( { node : node , loc : token . loc . start , message : 'A space is required before \'' + token . value + '\'' , fix : function ( fixer ) { return fixer . insertTextBefore ( token , ' ' ) ; } } ) ; }


Input: Get a random point offset from the origin [CODESPLIT] function generateDestinationLonLat ( { lat , lon } ) { const latOffset = ( getDistance ( ) / LAT_DEGREE ) * getSign ( ) const lonOffset = ( getDistance ( ) / ( LAT_DEGREE * Math . cos ( lat ) ) ) * getSign ( ) return { lat : lat + latOffset , lon : lon + lonOffset } }


Input: Get a nested value from the specified object . Returns undefined if not found . [CODESPLIT] function ( keyParts , hash ) { for ( var i = 0 ; i < keyParts . length - 1 ; ++ i ) { hash = getValue ( keyParts [ i ] , hash ) ; if ( typeof ( hash ) === 'undefined' ) { return undefined ; } } var lastKeyPartIndex = keyParts . length - 1 ; return getValue ( keyParts [ lastKeyPartIndex ] , hash ) }


Input: returns array of strings like firstname lastname <email [CODESPLIT] function gitAuthors ( cb ) { return exec ( 'git log --pretty="%an <%ae>"' , function ( er , stdout , stderr ) { if ( er || stderr ) throw new Error ( er || stderr ) return cb ( null , stdout . split ( '\n' ) . reverse ( ) ) } ) }


Input: look for the email first . if no results look for the name . [CODESPLIT] function lookupGithubLogin ( p , print , callback ) { var apiURI = 'https://api.github.com/search/users?q=' var options = { json : true , headers : { 'user-agent' : pkg . name + '/' + pkg . version } } if ( process . env . OAUTH_TOKEN ) { options . headers [ 'Authorization' ] = 'token ' + process . env . OAUTH_TOKEN . trim ( ) } function cb ( err , p ) { callback ( err , p ) } if ( print ) process . stdout . write ( '.' ) request ( apiURI + encodeURIComponent ( p . email + ' in:email type:user' ) , options , onEmail ) function onEmail ( err , data ) { rateLimitExceeded = rateLimitExceeded || data . body . message if ( ! err && data . body . items && data . body . items [ 0 ] ) { p . login = data . body . items [ 0 ] . login return cb ( err , p ) } request ( apiURI + encodeURIComponent ( p . name + ' in:fullname type:user' ) , options , onName ) } function onName ( err , data ) { rateLimitExceeded = rateLimitExceeded || data . body . message if ( ! err && data . body . items && data . body . items [ 0 ] ) { p . login = data . body . items [ 0 ] . login return cb ( err , p ) } cb ( err , p ) } }


Input: Unpacks Keyczar s output format [CODESPLIT] function _unpackOutput ( message ) { if ( message . charAt ( 0 ) != keyczar_util . VERSION_BYTE ) { throw new Error ( 'Unsupported version byte: ' + message . charCodeAt ( 0 ) ) ; } var keyhash = message . substr ( 1 , keyczar_util . KEYHASH_LENGTH ) ; message = message . substr ( 1 + keyczar_util . KEYHASH_LENGTH ) ; return { keyhash : keyhash , message : message } ; }


Input: Returns the keyhash for an RSA public key . [CODESPLIT] function _rsaHash ( publicKey ) { var md = forge . md . sha1 . create ( ) ; // hash: // 4-byte big endian length // "magnitude" of the public modulus (trim all leading zero bytes) // same for the exponent _hashBigNumber ( md , publicKey . n ) ; _hashBigNumber ( md , publicKey . e ) ; var digest = md . digest ( ) ; return digest . getBytes ( keyczar_util . KEYHASH_LENGTH ) ; }


Input: Returns a key object for an RSA key . [CODESPLIT] function _makeRsaKey ( rsaKey ) { var key = { keyhash : _rsaHash ( rsaKey ) , size : rsaKey . n . bitLength ( ) } ; key . encrypt = function ( plaintext ) { // needed to make this work with private keys var tempKey = forge . pki . setRsaPublicKey ( rsaKey . n , rsaKey . e ) ; var ciphertext = tempKey . encrypt ( plaintext , 'RSA-OAEP' ) ; return _packOutput ( key . keyhash , ciphertext ) ; } ; key . verify = function ( message , signature ) { signature = _unpackOutput ( signature ) ; _checkKeyHash ( key . keyhash , signature ) ; var digest = _mdForSignature ( message ) . digest ( ) . getBytes ( ) ; // needed to make this work with private keys var tempKey = forge . pki . setRsaPublicKey ( rsaKey . n , rsaKey . e ) ; return tempKey . verify ( digest , signature . message ) ; } ; return key ; }


Input: Extend grunt - exec [CODESPLIT] function ( ) { if ( ! result ) { var exec = grunt . config . get ( 'exec' ) ; for ( var key in exec ) { exec [ key ] . cmd = nvmUse + ' && ' + exec [ key ] . cmd ; } grunt . config . set ( 'exec' , exec ) ; } }


Input: Check for NVM [CODESPLIT] function ( callback ) { var command = '. ' + nvmPath ; childProcess . exec ( command , cmdOpts , function ( err , stdout , stderr ) { if ( stderr . indexOf ( 'No such file or directory' ) !== - 1 ) { if ( nvmPath === home + '/.nvm/nvm.sh' ) { nvmPath = home + '/nvm/nvm.sh' ; nvmInit = '. ' + nvmPath + ' && ' ; checkNVM ( callback ) ; } else { grunt [ options . errorLevel ] ( 'Expected node ' + expected + ', but found v' + actual + '\nNVM does not appear to be installed.\nPlease install (https://github.com/creationix/nvm#installation), or update the NVM path.' ) ; } } else { callback ( ) ; } } ) ; }


Input: Check for globally required packages [CODESPLIT] function ( packages ) { var thisPackage ; if ( packages . length ) { thisPackage = packages . pop ( ) ; var command = nvmUse + ' && npm ls -g ' + thisPackage ; childProcess . exec ( command , cmdOpts , function ( err , stdout , stderr ) { if ( err ) { throw err ; } if ( stdout . indexOf ( 'â”€ (empty)') !==   1)      npmInstall ( thisPackage , function ( ) { checkPackages ( packages ) ; } ) ; } else { checkPackages ( packages ) ; } } ) ; } else { done ( ) ; } }


Input: Install missing packages [CODESPLIT] function ( thisPackage , callback ) { var command = nvmUse + ' && npm install -g ' + thisPackage ; childProcess . exec ( command , cmdOpts , function ( err , stdout , stderr ) { if ( err ) { throw err ; } grunt . verbose . writeln ( stdout ) ; grunt . log . oklns ( 'Installed ' + thisPackage ) ; callback ( ) ; } ) ; }


Input: Prompt to install [CODESPLIT] function ( ) { prompt . start ( ) ; var prop = { name : 'yesno' , message : 'You do not have any node versions installed that satisfy this project\'s requirements (' . white + expected . yellow + '). Would you like to install the latest compatible version? (y/n)' . white , validator : / y[es]*|n[o]? / , required : true , warning : 'Must respond yes or no' } ; prompt . get ( prop , function ( err , result ) { result = result . yesno . toLowerCase ( ) ; if ( result === 'yes' || result === 'y' ) { nvmInstall ( ) ; } else { grunt [ options . errorLevel ] ( 'Expected node v' + expected + ', but found ' + actual ) ; } } ) ; }


Input: Install latest compatible node version [CODESPLIT] function ( ) { nvmLs ( 'remote' , function ( ) { bestMatch = semver . maxSatisfying ( remotes , expected ) ; nvmUse = nvmInit + 'nvm use ' + bestMatch ; var command = nvmInit + 'nvm install ' + bestMatch ; childProcess . exec ( command , cmdOpts , function ( err , stdout , stderr ) { if ( err ) { throw err ; } var nodeVersion = stdout . split ( ' ' ) [ 3 ] ; grunt . log . ok ( 'Installed node v' + bestMatch ) ; printVersion ( nodeVersion ) ; extendExec ( ) ; checkPackages ( options . globals ) ; } ) ; } ) ; }


Input: Check for available node versions [CODESPLIT] function ( loc , callback ) { var command = nvmInit + 'nvm ls' ; if ( loc === 'remote' ) { command += '-remote' ; } childProcess . exec ( command , cmdOpts , function ( err , stdout , stderr ) { var data = stripColorCodes ( stdout . toString ( ) ) . replace ( / \s+ / g , '|' ) , available = data . split ( '|' ) ; for ( var i = 0 ; i < available . length ; i ++ ) { // Trim whitespace available [ i ] = available [ i ] . replace ( / \s / g , '' ) ; // Validate var ver = semver . valid ( available [ i ] ) ; if ( ver ) { if ( loc === 'remote' ) { remotes . push ( ver ) ; } else if ( loc === 'local' ) { locals . push ( ver ) ; } } } callback ( ) ; } ) ; }


Input: Check for compatible node version [CODESPLIT] function ( ) { // Make sure a node version is intalled that satisfies // the projects required engine. If not, prompt to install. nvmLs ( 'local' , function ( ) { var matches = semver . maxSatisfying ( locals , expected ) ; if ( matches ) { bestMatch = matches ; nvmUse = nvmInit + 'nvm use ' + bestMatch ; childProcess . exec ( nvmUse , cmdOpts , function ( err , stdout , stderr ) { printVersion ( stdout . split ( ' ' ) [ 3 ] ) ; extendExec ( ) ; checkPackages ( options . globals ) ; } ) ; } else { if ( options . alwaysInstall ) { nvmInstall ( ) ; } else { askInstall ( ) ; } } } ) ; }


Input: A subject which executes its assertions on each element of an iterable . [CODESPLIT] function EachSubject ( subject , elements , elementName , opt_noIndex ) { ProxyBase . call ( this ) ; this . elementSubjects = [ ] ; for ( var i = 0 ; i < elements . length ; ++ i ) { var es = subjectFactory . newSubject ( subject . failureStrategy , elements [ i ] ) ; es . named ( elementName + ( opt_noIndex ? '' : ( ' ' + i ) ) + ' of ' + subject . describe ( ) ) ; es . failureMessage = subject . failureMessage ; this . elementSubjects . push ( es ) ; } }


Input: A class which functions as a subject but doesn t actually execute any assertions until the promise has resolved . Once the promise succeeds any method calls will be played back on the result value of the promise . [CODESPLIT] function EventualSubject ( subject , promise ) { DeferredSubject . call ( this ) ; this . subject = subject ; var self = this ; this . promise = promise . then ( function ( value ) { // Play back the recorded calls on a new subject which is created based on the resolved // value of the promise. var valueSubject = subjectFactory . newSubject ( subject . failureStrategy , value ) ; valueSubject . failureMessage = subject . failureMessage ; self . run ( valueSubject ) ; return value ; } , function ( reason ) { subject . fail ( 'Expected promise ' + subject . describe ( ) + ' to succeed, but failed with ' + this . format ( reason ) + '.' ) ; return reason ; } ) ; // Make this object a thenable this . then = this . promise . then . bind ( this . promise ) ; this . catch = this . promise . catch . bind ( this . promise ) ; }


Input: Subject subclass which provides assertion methods for promise types . [CODESPLIT] function PromiseSubject ( failureStrategy , value ) { Subject . call ( this , failureStrategy , value ) ; // Make this object a thenable this . then = this . value . then . bind ( this . value ) ; this . catch = this . value . catch . bind ( this . value ) ; }


Input: Given two arrays or strings return the first element where they differ ( shallow ) . [CODESPLIT] function firstDiff ( exp , act ) { var i ; for ( i = 0 ; i < exp . length && i < act . length ; ++ i ) { if ( exp [ i ] != act [ i ] ) { break ; } } return i ; }


Input: Function to compute the difference between two values . Note that unlike many other object diff implementations this one tries to humanize the results summarizing them for improved readability . [CODESPLIT] function compare ( exp , act , opt_path , opt_deep , opt_results ) { var path = opt_path || '' ; var i , j , strExp , strAct ; if ( sameValue ( exp , act ) ) { return true ; } var et = type ( exp ) ; var at = type ( act ) ; if ( et !== at || et === 'number' || at === 'boolean' || et === 'undefined' || exp === null || act === null ) { if ( opt_results ) { opt_results . push ( inequality ( exp , act , path ) ) ; } return false ; } else if ( et === 'object' ) { // Shallow comparison if ( ! opt_deep ) { if ( opt_results ) { opt_results . push ( inequality ( exp , act , path ) ) ; } return false ; } // Compare prototypes var eProto = Object . getPrototypeOf ( exp ) ; var aProto = Object . getPrototypeOf ( act ) ; if ( eProto != aProto ) { if ( opt_results ) { var eName = protoName ( exp ) ; var aName = protoName ( act ) ; opt_results . push ( { diff : 'type' , path : path , expected : eName , actual : aName , } ) ; } return false ; } if ( Array . isArray ( exp ) && Array . isArray ( act ) ) { if ( ! opt_results && exp . length !== act . length ) { return false ; } for ( i = 0 ; i < exp . length && i < act . length ; i += 1 ) { if ( ! compare ( exp [ i ] , act [ i ] , path + '[' + i + ']' , opt_deep , opt_results , true ) ) { if ( ! opt_results ) { return false ; } } } var strEl ; if ( i < exp . length ) { for ( j = i ; j < exp . length && j < i + 3 ; j += 1 ) { strEl = format ( exp [ j ] , { clip : 128 } ) ; opt_results . push ( { diff : 'element' , path : path + '[' + j + ']' , // expected: eName, actual : strEl , } ) ; } if ( j < exp . length ) { opt_results . push ( { diff : 'more' , more : ( exp . length - j ) } ) ; } } if ( i < act . length ) { strEl = format ( act [ i ] , { clip : 128 } ) ; for ( j = i ; j < act . length && j < i + 3 ; j += 1 ) { strEl = format ( act [ j ] , { clip : 128 } ) ; opt_results . push ( { diff : 'element' , path : path + '[' + j + ']' , expected : strEl , } ) ; } if ( j < act . length ) { opt_results . push ( { diff : 'more' , more : ( act . length - j ) } ) ; } } return false ; } // Handle regular expression objects. if ( exp instanceof RegExp ) { if ( opt_deep && ( exp + '' ) === ( act + '' ) ) { return true ; } if ( opt_results ) { opt_results . push ( inequality ( exp , act , path ) ) ; } return false ; } // Handle 'date' objects. if ( exp instanceof Date ) { if ( opt_deep && exp . getTime ( ) === act . getTime ( ) ) { return true ; } if ( opt_results ) { opt_results . push ( inequality ( exp , act , path ) ) ; } return false ; } // Compare individual properties. var same = true ; var eKeys = propertyKeys ( exp ) ; var aKeys = propertyKeys ( act ) ; eKeys . sort ( ) ; aKeys . sort ( ) ; // Check all keys in exp for ( i = 0 ; i < eKeys . length ; ++ i ) { var k = eKeys [ i ] ; if ( act . hasOwnProperty ( k ) ) { if ( ! compare ( exp [ k ] , act [ k ] , path + '.' + k , opt_deep , opt_results , true ) ) { if ( ! opt_results ) { return false ; } same = false ; } } else { same = false ; if ( opt_results ) { // opt_results.push(propertyAbsent(exp[k], null, path + '.' + k)); strExp = format ( exp [ k ] , { clip : 128 } ) ; var keyExp = path + '.' + k ; opt_results . push ( { diff : 'property' , path : keyExp , expected : strExp , // actual: aName, } ) ; } } } // Check all keys in act for ( i = 0 ; i < aKeys . length ; ++ i ) { var k2 = aKeys [ i ] ; if ( ! exp . hasOwnProperty ( k2 ) ) { if ( ! opt_results ) { return false ; } same = false ; strAct = format ( act [ k2 ] , { clip : 128 } ) ; var keyAct = path + '.' + k2 ; opt_results . push ( { diff : 'property' , path : keyAct , // expected: eName, actual : strAct , } ) ; } } return same ; } else if ( et === 'string' ) { if ( opt_results ) { // See if the values have line breaks var eLines = exp . split ( '\n' ) ; var aLines = act . split ( '\n' ) ; var col = 0 ; var start ; if ( eLines . length > 2 || aLines . length > 2 ) { // find the first line where they differ var line = firstDiff ( eLines , aLines ) ; // find the first character where the lines differ var expLine = line < eLines . length ? eLines [ line ] : '' ; var actLine = line < aLines . length ? aLines [ line ] : '' ; col = firstDiff ( expLine , actLine ) ; start = Math . max ( col - 16 , 0 ) ; strExp = sliceWithEllipsis ( expLine , start , Math . min ( col + 40 , expLine . length ) ) ; strAct = sliceWithEllipsis ( actLine , start , Math . min ( col + 40 , actLine . length ) ) ; opt_results . push ( { diff : 'string' , path : path , line : line , col : col , expected : strExp , actual : strAct } ) ; } else { // find the first character where they differ col = firstDiff ( exp , act ) ; // if that index < 16 or strings are short, then show the whole thing: if ( col < 16 || ( exp . length < 30 && act . length < 30 ) ) { opt_results . push ( inequality ( exp , act , path ) ) ; return false ; } // Only show the part of the string that differs. start = Math . max ( col - 16 , 0 ) ; strExp = sliceWithEllipsis ( exp , start , Math . min ( col + 40 , exp . length ) ) ; strAct = sliceWithEllipsis ( act , start , Math . min ( col + 40 , act . length ) ) ; opt_results . push ( { diff : 'string' , path : path , index : col , expected : strExp , actual : strAct } ) ; } // opt_results.push(msg); return false ; } return false ; } else { // buffer // arguments throw new Error ( 'Type not handled: ' + et ) ; } }


Input: / * Return path to write file to inside outputDir . [CODESPLIT] function defaultDestRewriter ( pathObj : Object , innerPath : string , options : Object ) { let fileName = pathObj . base ; if ( options . fileSuffix ) { fileName . replace ( options . fileSuffix , '.svg' ) ; } else { fileName = fileName . replace ( '.svg' , '.js' ) ; } fileName = fileName . replace ( / (^.)|(_)(.) / g , ( match , p1 , p2 , p3 ) => ( p1 || p3 ) . toUpperCase ( ) ) ; return path . join ( innerPath , fileName ) ; }


Input: Retrieve value stored at key Empty / null / undefined key returns all data [CODESPLIT] function get ( store , key , options ) { if ( key === '' || key == null ) { return store . _data ; } return doGet ( store , key , options ) ; }


Input: Retrieve value stored at key [CODESPLIT] function doGet ( store , key , options = { } ) { // Resolve back to original key if referenced key = store . _resolveRefKey ( key ) ; const { referenceDepth = 1 } = options ; const cacheKey = ` ${ key } ${ referenceDepth } ` ; const shouldCache = ! store . _isWritable ; if ( shouldCache ) { if ( store . _getCache [ cacheKey ] ) { return store . _getCache [ cacheKey ] ; } } let value = property . get ( store . _data , key ) ; if ( referenceDepth > 0 ) { value = resolveReferences ( store , value , referenceDepth ) ; } if ( shouldCache ) { store . _getCache [ cacheKey ] = value ; } return value ; }


Input: Resolve all references in value up to max depth [CODESPLIT] function resolveReferences ( store , value , depth ) { if ( -- depth < 0 ) { return value ; } if ( Array . isArray ( value ) ) { const n = value . length ; const v = new Array ( n ) ; let item ; for ( let i = n - 1 ; i >= 0 ; i -- ) { item = value [ i ] ; v [ i ] = resolveReferences ( store , store . _isRefValue ( item ) ? property . get ( store . _data , store . _parseRefKey ( item ) ) : item , depth ) ; } value = v ; } else if ( isPlainObject ( value ) ) { const v = { } ; let item ; for ( const prop in value ) { item = value [ prop ] ; v [ prop ] = resolveReferences ( store , store . _isRefValue ( item ) ? property . get ( store . _data , store . _parseRefKey ( item ) ) : item , depth ) ; } value = v ; } return value ; }


Input: Convert a string value to a printable string representation . [CODESPLIT] function formatString ( value , options ) { var opts = options || { } ; var result = value . replace ( / [\0-\37] / g , function ( ch ) { switch ( ch ) { case '\n' : return '\\n' ; case '\r' : return '\\r' ; case '\t' : return '\\t' ; case '\b' : return '\\b' ; case '\v' : return '\\v' ; case '\f' : return '\\f' ; default : return '\\' + ch . charCodeAt ( 0 ) . toString ( 8 ) ; } } ) ; if ( opts . clip && result . length > opts . clip ) { result = result . slice ( 0 , Math . max ( 0 , opts . clip - 3 ) ) + '...' ; } return '"' + result + '"' ; }


Input: ------------------------------------ Utilities ------------------------------------ [CODESPLIT] function base ( ) { const args = [ config . path_base ] . concat ( [ ] . slice . call ( arguments ) ) ; return path . resolve . apply ( path , args ) ; }


Input: A fluent context object containing the value of the field that was just tested . Used for additional assertions about a field . [CODESPLIT] function KeyValue ( subject , key ) { this . subject = subject ; this . key = key ; this . format = subject . format ; this . value = subject . value . get ( key ) ; }