Example #1
0
File: raw.js Project: crabmc/knex
 toSQL: function toSQL() {
   if (this._cached) return this._cached;
   if (Array.isArray(this.bindings)) {
     this._cached = replaceRawArrBindings(this);
   } else if (this.bindings && isPlainObject(this.bindings)) {
     this._cached = replaceKeyBindings(this);
   } else {
     this._cached = {
       method: 'raw',
       sql: this.sql,
       bindings: this.bindings
     };
   }
   if (this._wrappedBefore) {
     this._cached.sql = this._wrappedBefore + this._cached.sql;
   }
   if (this._wrappedAfter) {
     this._cached.sql = this._cached.sql + this._wrappedAfter;
   }
   this._cached.options = reduce(this._options, assign, {});
   if (this._timeout) {
     this._cached.timeout = this._timeout;
   }
   return this._cached;
 }
Example #2
0
// will flatten a call to bulk-require to only get
// the test cases object in an array
function flattenBulkRequire(bulk) {
  return reduce(
    bulk,
    flatten,
    []
  );
}
  this.addRule('elements.move', HIGH_PRIORITY, function(context) {

    var target = context.target,
        shapes = context.shapes;

    var type;

    // do not allow mixed movements of custom / BPMN shapes
    // if any shape cannot be moved, the group cannot be moved, too
    var allowed = reduce(shapes, function(result, s) {
      if (type === undefined) {
        type = isCustom(s);
      }

      if (type !== isCustom(s) || result === false) {
        return false;
      }

      return canCreate(s, target);
    }, undefined);

    // reject, if we have at least one
    // custom element that cannot be moved
    return allowed;
  });
Example #4
0
 $apply: data => {
   reduce(data, (acc, val, key) => {
     acc[key] = removeId(val)
     return acc
   }, {})
   return data
 }
    formatNumber: function formatNumber(text, pattern) {
        if (!text || text.length === 0) {
            return '+';
        }

        // for all strings with length less than 3, just return it (1, 2 etc.)
        // also return the same text if the selected country has no fixed format
        if (text && text.length < 2 || !pattern || !this.props.autoFormat) {
            return '+' + text;
        }

        var formattedObject = reduce(pattern, function (acc, character) {
            if (acc.remainingText.length === 0) {
                return acc;
            }

            if (character !== '.') {
                return {
                    formattedText: acc.formattedText + character,
                    remainingText: acc.remainingText
                };
            }

            return {
                formattedText: acc.formattedText + first(acc.remainingText),
                remainingText: rest(acc.remainingText)
            };
        }, { formattedText: '', remainingText: text.split('') });
        return formattedObject.formattedText + formattedObject.remainingText.join('');
    },
    guessSelectedCountry: memoize(function (inputNumber) {
        var secondBestGuess = findWhere(allCountries, { iso2: this.props.defaultCountry }) || this.props.onlyCountries[0];
        if (trim(inputNumber) !== '') {
            var bestGuess = reduce(this.props.onlyCountries, function (selectedCountry, country) {
                if (startsWith(inputNumber, country.dialCode)) {
                    if (country.dialCode.length > selectedCountry.dialCode.length) {
                        return country;
                    }
                    if (country.dialCode.length === selectedCountry.dialCode.length && country.priority < selectedCountry.priority) {
                        return country;
                    }
                }

                return selectedCountry;
            }, { dialCode: '', priority: 10001 }, this);
        } else {
            return secondBestGuess;
        }

        if (!bestGuess.name) {
            return secondBestGuess;
        }

        return bestGuess;
    }),
Example #7
0
  reporter: function (errs) {
    'use strict';

    if (!errs || !errs.length) { return; }

    var str;

    if (errs.length > 1) {

      var totalFiles = Object.keys(reduce(errs, function (acc, err) {
        acc[err.file] = true;
        return acc;
      }, {})).length;

      str = '' + errs.length + ' errors across ' + totalFiles + ' files.';

    } else {

      var file = errs[0].file;
      var err = errs[0].error;
      str = file + '(' + err.line + ':' + err.character + '): ' + err.reason;

    }

    growl(str, {
      name: 'JSHint',
      title: 'JSHint',
      sticky: false,
    });
  }
 setContacts: function(contacts) {
   this.contactsById = reduce(contacts, function(result, contact) {
     result[contact.id] = contact;
     return result;
   }, {});
   this.emitChange();
 },
Example #9
0
    parseResponse: function(robo, body, cardName, urlParams, select, offset) {
        var cardDetails,
            gathererBaseUrl,
            gathererParams,
            gathererUrl,
            cardPoolSize,
            cardSample,
            cardSampleNames,
            cardSampleText,
            cards = JSON.parse(body),
            card = (isEmpty(cards) || !cardName) ? undefined : find(cards, function(card){
                return cardName.toLowerCase() === card.name.toLowerCase();
            });

        // If find() comes back with a match that means it found the exact card the user was
        // looking for. Otherwise, that means the service has found more than one match.

        if (!card && cards.length === 1) {
           card = cards[0];
        }

        if (card) {
            cardDetails = utils.getCardDetails(card);
            utils.sendDetails(robo, cardDetails);

        } else if (select != null) {
            if (select > 0 && select <= cards.length) {
                card = cards[select - 1];
                cardDetails = utils.getCardDetails(card);
                utils.sendDetails(robo, cardDetails);
            } else {
                robo.send('Please specify a number in the range 1-' + cards.length);
            }

        } else if (offset && offset > cards.length) {
            robo.send('You have specified an out of bounds page.');

        } else if (cards.length > 0) {
            // Grab the first X amount of cards, which is determined from the constant cardLimit.
            // Then print off the name of each card.
            cardSample = cards.slice(offset, offset + CARD_LIMIT);
            cardSampleNames = pluck(cardSample, 'name');
            cardSampleText = reduce(cardSampleNames, function (cardList, cardName, index) {
                var cardNum = offset + index + 1;
                return cardList + '\n' + cardNum + '. ' + cardName;
            }, '');
            cardPoolSize = getCardPoolSizeString(cardSample.length, cards.length);

            gathererBaseUrl = consts.urlMap.gathererAdvanced;
            gathererParams = utils.parseGathererUrlParams(urlParams);

            robo.send(cardPoolSize + '\n' + cardSampleText);

        } else {
            robo.send(getCardNotFoundError(cardName));
        }

        return cards.length;
    },
Example #10
0
function flatten(flattened, testCase) {
  // while we are not on a test case, go deeper
  if (testCase.testName === undefined) {
    testCase = reduce(testCase, flatten, []);
  }

  return flattened.concat(testCase);
}
Example #11
0
function combineModules( storeOptions ) {
	const modules = reduce( storeOptions, ( array, moduleOptions, moduleName ) => {
		const module = AVAILABLE_MODULES[ moduleName ]( moduleOptions );
		return array.concat( [ module ] );
	}, [] );

	return [ core(), ...modules ];
}
Example #12
0
function mdReactFactory(options={}) {
	const { onIterate, tags=DEFAULT_TAGS,
		presetName, markdownOptions,
		enableRules=[], disableRules=[], plugins=[],
		onGenerateKey=(tag, index) => `mdrct-${tag}-${index}`,
		className } = options;

		let md = markdown({html:false, linkify: true, typographer: true})
		.enable(enableRules)
		.disable(disableRules);

		const convertRules = assign({}, DEFAULT_RULES, options.convertRules);

		md = reduce(plugins, (m, plugin) =>
		plugin.plugin ?
		m.use(plugin.plugin, ...plugin.args) :
		m.use(plugin),
		md
	);

	function iterateTree(tree, level=0, index=0) {
		let tag = tree.shift();
		const key = onGenerateKey(tag, index);

		const props = (tree.length && isPlainObject(tree[0])) ?
		assign(tree.shift(), { key }) :
		{ key };

		if (level === 0 && className) {
			props.className = className;
		}

		const children = tree.map(
			(branch, idx) => Array.isArray(branch) ?
			iterateTree(branch, level + 1, idx) :
			branch
		);

		tag = tags[tag] || tag;

		if (isString(props.style)) {
			props.style = zipObject(
				props.style.split(';')
				.map(prop => prop.split(':'))
				.map(keyVal => [camelCase(keyVal[0].trim()), keyVal[1].trim()])
			);
		}

		return (typeof onIterate === 'function') ?
		onIterate(tag, props, children, level) :
		React.createElement(tag, props, children);
	}

	return function(text) {
		const tree = convertTree(md.parse(text, {}), convertRules, md.options);
		return iterateTree(tree);
	};
}
Example #13
0
 extractLeafletEvents(props) {
   return reduce(props, (res, cb, ev) => {
     if (EVENTS_RE.test(ev)) {
       const key = ev.replace(EVENTS_RE, (match, p) => p.toLowerCase());
       res[ key ] = cb;
     }
     return res;
   }, {});
 }
Example #14
0
        'get /dev/dependencies': function (req, res) {
          var dependencies = fsx.readJsonSync(path.resolve(sails.config.appPath, 'package.json')).dependencies;
          return res.json(reduce(dependencies, function (memo, semverRange, depName){
            var actualDependencyVersion = fsx.readJsonSync(path.resolve(sails.config.appPath, path.join('node_modules',depName,'package.json'))).version;
            memo[depName] = actualDependencyVersion;
            return memo;
          }, {}));

        }
Example #15
0
 getQueryParams : function getQueryParams() {
   var managedParameters = this.managedParameters;
   return reduce( this, function( memo, value, parameter, parameters ) {
     if( managedParameters.indexOf( parameter ) === -1 &&
         parameters[ parameter ] !== undefined ) {
       memo[ parameter ] = value;
     }
     return memo;
   }, {} );
 },
function reduceGraphQLTypes(models) {
    return reduce(models, function(types, model) {
        var primaryKey = getPrimaryKey(model) || {};
        var keyType = typeMap[primaryKey.type];

        if (keyType && types.indexOf(keyType) === -1) {
            types.push(keyType);
        }

        return types;
    }, []);
}
  this.style = function(traits, additionalAttrs) {

    if (!isArray(traits) && !additionalAttrs) {
      additionalAttrs = traits;
      traits = [];
    }

    var attrs = reduce(traits, function(attrs, t) {
      return assign(attrs, defaultTraits[t] || {});
    }, {});

    return additionalAttrs ? assign(attrs, additionalAttrs) : attrs;
  };
Example #18
0
/**
 * Given a defaults object and a source object, copy the value from the source
 * if it contains the same key, otherwise return the default. Skip keys that
 * only exist in the source object.
 * @param {object} defaults - Default schema
 * @param {object} source - Source object to copy properties from
 * @returns {object} - Result has identical keys to defaults
 * @static
 * @memberof helper
*/
function merge_or_apply(defaults, source) {
	var defaultKeys = keys(defaults);
	var sourceKeys = keys(source);
	return reduce(defaultKeys, function(result, key) {
		if (sourceKeys.indexOf(key) > -1) {
			result[key] = source[key];
			return result;
		} else {
			result[key] = defaults[key];
			return result;
		}
	}, {});
}
function getFilteredRefinements(results, state, attributeNames, onlyListedAttributes) {
  let refinements = getRefinements(results, state);
  let otherAttributeNames = reduce(refinements, (res, refinement) => {
    if (attributeNames.indexOf(refinement.attributeName) === -1 && res.indexOf(refinement.attributeName === -1)) {
      res.push(refinement.attributeName);
    }
    return res;
  }, []);
  refinements = refinements.sort(compareRefinements.bind(null, attributeNames, otherAttributeNames));
  if (onlyListedAttributes && !isEmpty(attributeNames)) {
    refinements = filter(refinements, refinement => attributeNames.indexOf(refinement.attributeName) !== -1);
  }
  return refinements;
}
function prepareTemplates(defaultTemplates = {}, templates = {}) {
  const allKeys = uniq([...(keys(defaultTemplates)), ...(keys(templates))]);

  return reduce(allKeys, (config, key) => {
    const defaultTemplate = defaultTemplates[key];
    const customTemplate = templates[key];
    const isCustomTemplate = customTemplate !== undefined && (customTemplate !== defaultTemplate);

    config.templates[key] = isCustomTemplate ? customTemplate : defaultTemplate;
    config.useCustomCompileOptions[key] = isCustomTemplate;

    return config;
  }, {templates: {}, useCustomCompileOptions: {}});
}
 toSQL: function toSQL(method) {
   method = method || this.method;
   var val = this[method]();
   var defaults = {
     method: method,
     options: reduce(this.options, assign, {}),
     bindings: this.formatter.bindings
   };
   if (_.isString(val)) {
     val = { sql: val };
   }
   if (method === 'select' && this.single.as) {
     defaults.as = this.single.as;
   }
   return assign(defaults, val);
 },
CopyPaste.prototype.paste = function(context) {
  var clipboard = this._clipboard,
      modeling = this._modeling,
      eventBus = this._eventBus,
      rules = this._rules;

  var tree = clipboard.get(),
      topParent = context.element,
      position = context.point,
      newTree, canPaste;

  if (clipboard.isEmpty()) {
    return;
  }

  newTree = reduce(tree, function(pasteTree, elements, depthStr) {
    var depth = parseInt(depthStr, 10);

    if (isNaN(depth)) {
      return pasteTree;
    }

    pasteTree[depth] = elements;

    return pasteTree;
  }, {}, this);


  canPaste = rules.allowed('elements.paste', {
    tree: newTree,
    target: topParent
  });

  if (!canPaste) {
    eventBus.fire('elements.paste.rejected', {
      context: {
        tree: newTree,
        position: position,
        target: topParent
      }
    });

    return;
  }

  modeling.pasteElements(newTree, topParent, position);
};
Example #23
0
ABTest.prototype.assignVariation = function() {
	var allocationsTotal, randomAllocationAmount, variationName,
		sum = 0;

	allocationsTotal = reduce( this.variationDetails, function( allocations, allocation ) {
		return allocations + allocation;
	}, 0 );

	randomAllocationAmount = Math.random() * allocationsTotal;

	for ( variationName in this.variationDetails ) {
		sum += this.variationDetails[ variationName ];
		if ( randomAllocationAmount <= sum ) {
			return variationName;
		}
	}
};
function parseNodeAttributes(node) {
  var nodeAttrs = node.attributes;

  return reduce(nodeAttrs, function(result, v, k) {
    var name, ns;

    if (!v.local) {
      name = v.prefix;
    } else {
      ns = parseNameNs(v.name, v.prefix);
      name = ns.name;
    }

    result[name] = v.value;
    return result;
  }, {});
}
  return function generate(hierarchicalFacetResult, hierarchicalFacetIndex) {
    var hierarchicalFacet = state.hierarchicalFacets[hierarchicalFacetIndex];
    var hierarchicalFacetRefinement = state.hierarchicalFacetsRefinements[hierarchicalFacet.name] &&
      state.hierarchicalFacetsRefinements[hierarchicalFacet.name][0] || '';
    var hierarchicalSeparator = state._getHierarchicalFacetSeparator(hierarchicalFacet);
    var sortBy = prepareHierarchicalFacetSortBy(state._getHierarchicalFacetSortBy(hierarchicalFacet));

    var generateTreeFn = generateHierarchicalTree(sortBy, hierarchicalSeparator, hierarchicalFacetRefinement);

    return reduce(hierarchicalFacetResult, generateTreeFn, {
      name: state.hierarchicalFacets[hierarchicalFacetIndex].name,
      count: null, // root level, no count
      isRefined: true, // root level, always refined
      path: null, // root level, no path
      data: null
    });
  };
  loadPromise_ = new Promise((resolve, reject) => {
    if (typeof window === 'undefined') {
      reject(new Error('google map cannot be loaded outside browser env'));
      return;
    }

    if (window.google && window.google.maps) {
      resolve(window.google.maps);
      return;
    }

    if (typeof window._$_google_map_initialize_$_ !== 'undefined') {
      reject(new Error('google map initialization error'));
    }

    window._$_google_map_initialize_$_ = () => {
      delete window._$_google_map_initialize_$_;
      resolve(window.google.maps);
    };

    if (process.env.NODE_ENV !== 'production') {
      if (find(Object.keys(bootstrapURLKeys), 'callback')) {
        console.error('"callback" key in bootstrapURLKeys is not allowed, ' + // eslint-disable-line
                      'use onGoogleApiLoaded property instead');
        throw new Error('"callback" key in bootstrapURLKeys is not allowed, ' +
                        'use onGoogleApiLoaded property instead');
      }
    }

    const queryString = reduce(
      Object.keys(bootstrapURLKeys),
      (r, key) => r + `&${key}=${bootstrapURLKeys[key]}`,
      ''
    );

    $script_(
      `https://maps.googleapis.com/maps/api/js?callback=_$_google_map_initialize_$_${queryString}`,
      () =>
        typeof window.google === 'undefined' &&
          reject(new Error('google map initialization error (not loaded)'))
    );
  });
Example #27
0
    _getGroupCounts: function _getGroupCounts(resultsMap) {
        var groupKeys = keys(resultsMap);
        if (1 === groupKeys.length) {
            var _ref;

            return (_ref = {}, _ref[groupKeys[0]] = {
                count: this.props.totalCount
            }, _ref);
        }
        var targetFacetData = undefined;
        forEach(this.props.resultsFacets, function (facetData) {
            if (isEqual(keys(facetData).sort(), groupKeys.sort())) {
                targetFacetData = facetData;
                return false;
            }
        });
        return reduce(targetFacetData, function (result, data, key) {
            result[key] = data.count;
            return result;
        }, {});
    },
  _getHitsHierarchicalFacetsAttributes: function(state) {
    var out = [];

    return reduce(
      state.hierarchicalFacets,
      // ask for as much levels as there's hierarchical refinements
      function getHitsAttributesForHierarchicalFacet(allAttributes, hierarchicalFacet) {
        var hierarchicalRefinement = state.getHierarchicalRefinement(hierarchicalFacet.name)[0];

        // if no refinement, ask for root level
        if (!hierarchicalRefinement) {
          allAttributes.push(hierarchicalFacet.attributes[0]);
          return allAttributes;
        }

        var level = hierarchicalRefinement.split(state._getHierarchicalFacetSeparator(hierarchicalFacet)).length;
        var newAttributes = hierarchicalFacet.attributes.slice(0, level + 1);

        return allAttributes.concat(newAttributes);
      }, out);
  },
Example #29
0
Flux.prototype.addAction = function() {
  if (arguments.length < 2) {
    throw new Error("addAction requires at least two arguments, a string (or array of strings) and a function");
  }

  var args = Array.prototype.slice.call(arguments);

  if (!_isFunction(args[args.length - 1])) {
    throw new Error("The last argument to addAction must be a function");
  }

  var func = args.pop().bind(this.dispatchBinder);

  if (!_isString(args[0])) {
    args = args[0];
  }

  var leadingPaths = _reduce(args, function(acc, next) {
    if (acc) {
      var nextPath = acc[acc.length - 1].concat([next]);
      return acc.concat([nextPath]);
    } else {
      return [[next]];
    }
  }, null);

  // Detect trying to replace a function at any point in the path
  _each(leadingPaths, function(path) {
    if (_isFunction(objectPath.get(this.actions, path))) {
      throw new Error("An action named " + args.join(".") + " already exists");
    }
  }, this);

  // Detect trying to replace a namespace at the final point in the path
  if (objectPath.get(this.actions, args)) {
    throw new Error("A namespace named " + args.join(".") + " already exists");
  }

  objectPath.set(this.actions, args, func, true);
};
Example #30
0
 toSQL: function() {
   if (this._cached) return this._cached
   if (Array.isArray(this.bindings)) {
     this._cached = replaceRawArrBindings(this) 
   } else if (this.bindings && typeof this.bindings === 'object') {
     this._cached = replaceKeyBindings(this)
   } else {
     this._cached = {
       method: 'raw',
       sql: this.sql,
       bindings: this.bindings
     }
   }
   if (this._wrappedBefore) {
     this._cached.sql = this._wrappedBefore + this._cached.sql
   }
   if (this._wrappedAfter) {
     this._cached.sql = this._cached.sql + this._wrappedAfter
   }
   this._cached.options = reduce(this._options, assign, {})
   return this._cached
 }