<commit_before>var sops_assets=new Array();
var models_assets=new Array();
var assays=new Array();
var data_files_assets=new Array();
var organisms = new Array();

function postInvestigationData() {
    request = new Ajax.Request(CREATE_INVESTIGATION_LINK,
    {
        method: 'post',
        parameters: {
            id: $('study_investigation_id').value,  // empty ID will be submitted on "create" action, but it doesn't make a difference
            title: $('title').value,
            project_id: $('project_id').value
        },
        onSuccess: function(transport){
            var data = transport.responseText.evalJSON(true);

            if (data.status==200){
                addNewInvestigation(data.new_investigation);
                RedBox.close();
            }
            if (data.status==406) {
                $('errorExplanation').innerHTML=data.error_messages;
                $('errorExplanation').show();
            }

            return (true);
        },
        onFailure: function(transport){
            alert('Something went wrong, please try again...');
            return(false);
        }
    });

}

function addNewInvestigation(new_investigation) {
    selectObj=$('study_investigation_id');
    selectObj.options[select.options.length]=new Option(new_investigation[1],new_investigation[0],false,true);
    selectObj.disabled=false;
}

function addSop(title,id) {
    sops_assets.push([title,id]);
}

function addSelectedSop() {
    selected_option_index=$("possible_sops").selectedIndex;
    selected_option=$("possible_sops").options[selected_option_index];
    title=selected_option.text;
    id=selected_option.value;

    if(checkNotInList(id,sops_assets)) {
        addSop(title,id);
        updateSops();
    }
    else {
        alert('The following Sop had already been added:\n\n' +
            title);
    }
}

function removeSop(id) {
    // remove the actual record for the attribution
    for(var i = 0; i < sops_assets.length; i++)
        if(sops_assets[i][1] == id) {
            sops_assets.splice(i, 1);
            break;
        }

    // update the page
    updateSops();
}

function updateSops() {
    sop_text='
';

    sop_ids=new Array();

    for (var i=0;i<sops_assets.length;i++) {
        sop=sops_assets[i];
        title=sop[0];
        id=sop[1];
        titleText = '' + title.truncate(100) + '';
        sop_text += '
' + titleText +
          '   ' +
          '[remove]
';
        sop_ids.push(id);
    }

    sop_text += '
';

    // update the page
    if(sops_assets.length == 0) {
        $('sop_to_list').innerHTML = 'No sops';
    }
    else {
        $('sop_to_list').innerHTML = sop_text;
    }

    clearList('assay_sop_asset_ids');

    select=$('assay_sop_asset_ids')
    for (i=0;i<sop_ids.length;i++) {
        id=sop_ids[i];
        o=document.createElement('option');
        o.value=id;
        o.text=id;
        o.selected=true;
        try {
            select.add(o); //for older IE version
        }
        catch (ex) {
            select.add(o,null);
        }
    }
}

//Data files
function addDataFile(title,id,relationshipType) {
    data_files_assets.push([title,id,relationshipType]);
}

function addSelectedDataFile() {
    selected_option_index=$("possible_data_files").selectedIndex;
    selected_option=$("possible_data_files").options[selected_option_index];
    title=selected_option.text;
    id=selected_option.value;
    if ($("data_file_relationship_type")) {
        relationshipType = $("data_file_relationship_type").options[$("data_file_relationship_type").selectedIndex].text;
    }
    else
    {
        relationshipType="None"
    }

    if(checkNotInList(id,data_files_assets)) {
        addDataFile(title,id,relationshipType);
        updateDataFiles();
    }
    else {
        alert('The following Data file had already been added:\n\n' +
            title);
    }
}

function removeDataFile(id) {
    // remove the actual record for the attribution
    for(var i = 0; i < data_files_assets.length; i++)
        if(data_files_assets[i][1] == id) {
            data_files_assets.splice(i, 1);
            break;
        }

    // update the page
    updateDataFiles();
}

function updateDataFiles() {
    data_file_text='
'

    for (var i=0;i<data_files_assets.length;i++) {
        data_file=data_files_assets[i];
        title=data_file[0];
        id=data_file[1];
        relationshipType = data_file[2];
        relationshipText = (relationshipType == 'None') ? '' : ' (' + relationshipType + ')';
        titleText = '' + title.truncate(100) + '';
        data_file_text += '
' + titleText + relationshipText +
        '   '
        + '[remove]
';
    }

    data_file_text += '
';

    // update the page
    if(data_files_assets.length == 0) {
        $('data_file_to_list').innerHTML = 'No data files';
    }
    else {
        $('data_file_to_list').innerHTML = data_file_text;
    }

    clearList('assay_data_file_asset_ids');

    select=$('assay_data_file_asset_ids');
    for (i=0;i<data_files_assets.length;i++) {
        id=data_files_assets[i][1];
        relationshipType=data_files_assets[i][2];
        o=document.createElement('option');
        o.value=id + "," + relationshipType;
        o.text=id;
        o.selected=true;
        try {
            select.add(o); //for older IE version
        }
        catch (ex) {
            select.add(o,null);
        }
    }
}

//Models
function addModel(title,id) {
    models_assets.push([title,id]);
}

function addSelectedModel() {
    selected_option_index=$("possible_models").selectedIndex;
    selected_option=$("possible_models").options[selected_option_index];
    title=selected_option.text;
    id=selected_option.value;

    if(checkNotInList(id,models_assets)) {
        addModel(title,id);
        updateModels();
    }
    else {
        alert('The following Model had already been added:\n\n' +
            title);
    }
}

function removeModel(id) {
    // remove the actual record for the attribution
    for(var i = 0; i < models_assets.length; i++)
        if(models_assets[i][1] == id) {
            models_assets.splice(i, 1);
            break;
        }

    // update the page
    updateModels();
}

function updateModels() {
    model_text='
';
    type="Model";
    model_ids=new Array();

    for (var i=0;i<models_assets.length;i++) {
        model=models_assets[i];
        title=model[0];
        id=model[1];
        titleText = '' + title.truncate(100) + '';
        model_text += '
' + titleText
        //+ "  (" + contributor + ")"
        + '   '
        + '[remove]
';
        model_ids.push(id);
    }

    model_text += '
';

    // update the page
    if(models_assets.length == 0) {
        $('model_to_list').innerHTML = 'No models';
    }
    else {
        $('model_to_list').innerHTML = model_text;
    }

    clearList('assay_model_asset_ids');

    select=$('assay_model_asset_ids');
    for (i=0;i<model_ids.length;i++) {
        id=model_ids[i];
        o=document.createElement('option');
        o.value=id;
        o.text=id;
        o.selected=true;
        try {
            select.add(o); //for older IE version
        }
        catch (ex) {
            select.add(o,null);
        }
    }

    if (models_assets.length>=1) {
        Effect.Fade("add_model_elements");
    }
    else {
        Effect.Appear("add_model_elements");
    }
}

//Assays
function addSelectedAssay() {
    selected_option_index=$("possible_assays").selectedIndex;
    selected_option=$("possible_assays").options[selected_option_index];
    title=selected_option.text;
    id=selected_option.value;

    if(checkNotInList(id,assays)) {
        addAssay(title,id);
        updateAssays();
    }
    else {
        alert('The following Assay had already been added:\n\n' +
            title);
    }
}

function removeAssay(id) {
    // remove the actual record for the attribution
    for(var i = 0; i < assays.length; i++)
        if(assays[i][1] == id) {
            assays.splice(i, 1);
            break;
        }

    // update the page
    updateAssays();
}

function updateAssays() {
    assay_text='';
    type="Assay";
    assay_ids=new Array();

    for (var i=0;i<assays.length;i++) {
        assay=assays[i];
        title=assay[0];
        id=assay[1];
        assay_text += '' + type + ': ' + title
        //+ "  (" + contributor + ")"
        + '   '
        + '[remove]
';
        assay_ids.push(id);
    }

    // remove the last line break
    if(assay_text.length > 0) {
        assay_text = assay_text.slice(0,-5);
    }

    // update the page
    if(assay_text.length == 0) {
        $('assay_to_list').innerHTML = 'No assays';
    }
    else {
        $('assay_to_list').innerHTML = assay_text;
    }

    clearList('study_assay_ids');

    select=$('study_assay_ids');
    for (i=0;i<assay_ids.length;i++) {
        id=assay_ids[i];
        o=document.createElement('option');
        o.value=id;
        o.text=id;
        o.selected=true;
        try {
            select.add(o); //for older IE version
        }
        catch (ex) {
            select.add(o,null);
        }
    }
}

function addAssay(title,id) {
    assays.push([title,id]);
}

function addOrganism(title,id,strain,culture_growth) {
    organisms.push([title,id,strain,culture_growth]);
}

function addSelectedOrganism() {
    selected_option_index=$("possible_organisms").selectedIndex;
    selected_option=$("possible_organisms").options[selected_option_index];
    title=selected_option.text;
    id=selected_option.value;
    strain=$('strain').value

    selected_option_index=$('culture_growth').selectedIndex;
    selected_option=$('culture_growth').options[selected_option_index];
    culture_growth=selected_option.text

    addOrganism(title,id,strain,culture_growth);
    updateOrganisms();

}

function removeOrganism(id) {
    // remove the actual record for the attribution
    for(var i = 0; i < organisms.length; i++)
        if(organisms[i][1] == id) {
            organisms.splice(i, 1);
            break;
        }

    // update the page
    updateOrganisms();
}

function updateOrganisms() {
    organism_text='
';

    for (var i=0;i<organisms.length;i++) {
        organism=organisms[i];
        title=organism[0];
        id=organism[1];
        strain=organism[2]
        culture_growth=organism[3]
        titleText = '' + title.truncate(100);
        if (strain.length>0) {
            titleText += ":"+strain
        }
        titleText += " ("+culture_growth+")";
        titleText +=  '';
        organism_text += '
' + titleText +
          '   ' +
          '[remove]
';
    }

    organism_text += '
';

    // update the page
    if(organisms.length == 0) {
        $('organism_to_list').innerHTML = 'No organisms';
    }
    else {
        $('organism_to_list').innerHTML = organism_text;
    }

    clearList('assay_organism_ids');

    select=$('assay_organism_ids')
    for (i=0;i<organisms.length;i++) {
        organism=organisms[i];
        id=organism[1];
        strain=organism[2]
        culture_growth=organism[3]
        o=document.createElement('option');
        o.value=id;
        o.text=id;
        o.selected=true;
        o.value=id + "," + strain + "," + culture_growth;
        try {
            select.add(o); //for older IE version
        }
        catch (ex) {
            select.add(o,null);
        }
    }
}<commit_msg>hide empty brackets if culture_grwoth not defined<commit_after>var sops_assets=new Array();
var models_assets=new Array();
var assays=new Array();
var data_files_assets=new Array();
var organisms = new Array();

function postInvestigationData() {
    request = new Ajax.Request(CREATE_INVESTIGATION_LINK,
    {
        method: 'post',
        parameters: {
            id: $('study_investigation_id').value,  // empty ID will be submitted on "create" action, but it doesn't make a difference
            title: $('title').value,
            project_id: $('project_id').value
        },
        onSuccess: function(transport){
            var data = transport.responseText.evalJSON(true);

            if (data.status==200){
                addNewInvestigation(data.new_investigation);
                RedBox.close();
            }
            if (data.status==406) {
                $('errorExplanation').innerHTML=data.error_messages;
                $('errorExplanation').show();
            }

            return (true);
        },
        onFailure: function(transport){
            alert('Something went wrong, please try again...');
            return(false);
        }
    });

}

function addNewInvestigation(new_investigation) {
    selectObj=$('study_investigation_id');
    selectObj.options[select.options.length]=new Option(new_investigation[1],new_investigation[0],false,true);
    selectObj.disabled=false;
}

function addSop(title,id) {
    sops_assets.push([title,id]);
}

function addSelectedSop() {
    selected_option_index=$("possible_sops").selectedIndex;
    selected_option=$("possible_sops").options[selected_option_index];
    title=selected_option.text;
    id=selected_option.value;

    if(checkNotInList(id,sops_assets)) {
        addSop(title,id);
        updateSops();
    }
    else {
        alert('The following Sop had already been added:\n\n' +
            title);
    }
}

function removeSop(id) {
    // remove the actual record for the attribution
    for(var i = 0; i < sops_assets.length; i++)
        if(sops_assets[i][1] == id) {
            sops_assets.splice(i, 1);
            break;
        }

    // update the page
    updateSops();
}

function updateSops() {
    sop_text='
';

    sop_ids=new Array();

    for (var i=0;i<sops_assets.length;i++) {
        sop=sops_assets[i];
        title=sop[0];
        id=sop[1];
        titleText = '' + title.truncate(100) + '';
        sop_text += '
' + titleText +
          '   ' +
          '[remove]
';
        sop_ids.push(id);
    }

    sop_text += '
';

    // update the page
    if(sops_assets.length == 0) {
        $('sop_to_list').innerHTML = 'No sops';
    }
    else {
        $('sop_to_list').innerHTML = sop_text;
    }

    clearList('assay_sop_asset_ids');

    select=$('assay_sop_asset_ids')
    for (i=0;i<sop_ids.length;i++) {
        id=sop_ids[i];
        o=document.createElement('option');
        o.value=id;
        o.text=id;
        o.selected=true;
        try {
            select.add(o); //for older IE version
        }
        catch (ex) {
            select.add(o,null);
        }
    }
}

//Data files
function addDataFile(title,id,relationshipType) {
    data_files_assets.push([title,id,relationshipType]);
}

function addSelectedDataFile() {
    selected_option_index=$("possible_data_files").selectedIndex;
    selected_option=$("possible_data_files").options[selected_option_index];
    title=selected_option.text;
    id=selected_option.value;
    if ($("data_file_relationship_type")) {
        relationshipType = $("data_file_relationship_type").options[$("data_file_relationship_type").selectedIndex].text;
    }
    else
    {
        relationshipType="None"
    }

    if(checkNotInList(id,data_files_assets)) {
        addDataFile(title,id,relationshipType);
        updateDataFiles();
    }
    else {
        alert('The following Data file had already been added:\n\n' +
            title);
    }
}

function removeDataFile(id) {
    // remove the actual record for the attribution
    for(var i = 0; i < data_files_assets.length; i++)
        if(data_files_assets[i][1] == id) {
            data_files_assets.splice(i, 1);
            break;
        }

    // update the page
    updateDataFiles();
}

function updateDataFiles() {
    data_file_text='
'

    for (var i=0;i<data_files_assets.length;i++) {
        data_file=data_files_assets[i];
        title=data_file[0];
        id=data_file[1];
        relationshipType = data_file[2];
        relationshipText = (relationshipType == 'None') ? '' : ' (' + relationshipType + ')';
        titleText = '' + title.truncate(100) + '';
        data_file_text += '
' + titleText + relationshipText +
        '   '
        + '[remove]
';
    }

    data_file_text += '
';

    // update the page
    if(data_files_assets.length == 0) {
        $('data_file_to_list').innerHTML = 'No data files';
    }
    else {
        $('data_file_to_list').innerHTML = data_file_text;
    }

    clearList('assay_data_file_asset_ids');

    select=$('assay_data_file_asset_ids');
    for (i=0;i<data_files_assets.length;i++) {
        id=data_files_assets[i][1];
        relationshipType=data_files_assets[i][2];
        o=document.createElement('option');
        o.value=id + "," + relationshipType;
        o.text=id;
        o.selected=true;
        try {
            select.add(o); //for older IE version
        }
        catch (ex) {
            select.add(o,null);
        }
    }
}

//Models
function addModel(title,id) {
    models_assets.push([title,id]);
}

function addSelectedModel() {
    selected_option_index=$("possible_models").selectedIndex;
    selected_option=$("possible_models").options[selected_option_index];
    title=selected_option.text;
    id=selected_option.value;

    if(checkNotInList(id,models_assets)) {
        addModel(title,id);
        updateModels();
    }
    else {
        alert('The following Model had already been added:\n\n' +
            title);
    }
}

function removeModel(id) {
    // remove the actual record for the attribution
    for(var i = 0; i < models_assets.length; i++)
        if(models_assets[i][1] == id) {
            models_assets.splice(i, 1);
            break;
        }

    // update the page
    updateModels();
}

function updateModels() {
    model_text='
';
    type="Model";
    model_ids=new Array();

    for (var i=0;i<models_assets.length;i++) {
        model=models_assets[i];
        title=model[0];
        id=model[1];
        titleText = '' + title.truncate(100) + '';
        model_text += '
' + titleText
        //+ "  (" + contributor + ")"
        + '   '
        + '[remove]
';
        model_ids.push(id);
    }

    model_text += '
';

    // update the page
    if(models_assets.length == 0) {
        $('model_to_list').innerHTML = 'No models';
    }
    else {
        $('model_to_list').innerHTML = model_text;
    }

    clearList('assay_model_asset_ids');

    select=$('assay_model_asset_ids');
    for (i=0;i<model_ids.length;i++) {
        id=model_ids[i];
        o=document.createElement('option');
        o.value=id;
        o.text=id;
        o.selected=true;
        try {
            select.add(o); //for older IE version
        }
        catch (ex) {
            select.add(o,null);
        }
    }

    if (models_assets.length>=1) {
        Effect.Fade("add_model_elements");
    }
    else {
        Effect.Appear("add_model_elements");
    }
}

//Assays
function addSelectedAssay() {
    selected_option_index=$("possible_assays").selectedIndex;
    selected_option=$("possible_assays").options[selected_option_index];
    title=selected_option.text;
    id=selected_option.value;

    if(checkNotInList(id,assays)) {
        addAssay(title,id);
        updateAssays();
    }
    else {
        alert('The following Assay had already been added:\n\n' +
            title);
    }
}

function removeAssay(id) {
    // remove the actual record for the attribution
    for(var i = 0; i < assays.length; i++)
        if(assays[i][1] == id) {
            assays.splice(i, 1);
            break;
        }

    // update the page
    updateAssays();
}

function updateAssays() {
    assay_text='';
    type="Assay";
    assay_ids=new Array();

    for (var i=0;i<assays.length;i++) {
        assay=assays[i];
        title=assay[0];
        id=assay[1];
        assay_text += '' + type + ': ' + title
        //+ "  (" + contributor + ")"
        + '   '
        + '[remove]
';
        assay_ids.push(id);
    }

    // remove the last line break
    if(assay_text.length > 0) {
        assay_text = assay_text.slice(0,-5);
    }

    // update the page
    if(assay_text.length == 0) {
        $('assay_to_list').innerHTML = 'No assays';
    }
    else {
        $('assay_to_list').innerHTML = assay_text;
    }

    clearList('study_assay_ids');

    select=$('study_assay_ids');
    for (i=0;i<assay_ids.length;i++) {
        id=assay_ids[i];
        o=document.createElement('option');
        o.value=id;
        o.text=id;
        o.selected=true;
        try {
            select.add(o); //for older IE version
        }
        catch (ex) {
            select.add(o,null);
        }
    }
}

function addAssay(title,id) {
    assays.push([title,id]);
}

function addOrganism(title,id,strain,culture_growth) {
    organisms.push([title,id,strain,culture_growth]);
}

function addSelectedOrganism() {
    selected_option_index=$("possible_organisms").selectedIndex;
    selected_option=$("possible_organisms").options[selected_option_index];
    title=selected_option.text;
    id=selected_option.value;
    strain=$('strain').value

    selected_option_index=$('culture_growth').selectedIndex;
    selected_option=$('culture_growth').options[selected_option_index];
    culture_growth=selected_option.text

    addOrganism(title,id,strain,culture_growth);
    updateOrganisms();

}

function removeOrganism(id) {
    // remove the actual record for the attribution
    for(var i = 0; i < organisms.length; i++)
        if(organisms[i][1] == id) {
            organisms.splice(i, 1);
            break;
        }

    // update the page
    updateOrganisms();
}

function updateOrganisms() {
    organism_text='
';

    for (var i=0;i<organisms.length;i++) {
        organism=organisms[i];
        title=organism[0];
        id=organism[1];
        strain=organism[2]
        culture_growth=organism[3]
        titleText = '' + title.truncate(100);
        if (strain.length>0) {
            titleText += ":"+strain
        }
        if (culture_growth.length>0) {
            titleText += " ("+culture_growth+")";
        }
        titleText +=  '';
        organism_text += '
' + titleText +
          '   ' +
          '[remove]
';
    }

    organism_text += '
';

    // update the page
    if(organisms.length == 0) {
        $('organism_to_list').innerHTML = 'No organisms';
    }
    else {
        $('organism_to_list').innerHTML = organism_text;
    }

    clearList('assay_organism_ids');

    select=$('assay_organism_ids')
    for (i=0;i<organisms.length;i++) {
        organism=organisms[i];
        id=organism[1];
        strain=organism[2]
        culture_growth=organism[3]
        o=document.createElement('option');
        o.value=id;
        o.text=id;
        o.selected=true;
        o.value=id + "," + strain + "," + culture_growth;
        try {
            select.add(o); //for older IE version
        }
        catch (ex) {
            select.add(o,null);
        }
    }
}<|endoftext|>


<commit_before>import React from "react"
import * as common from "../../../utils/common"
import * as converter from "../../../utils/converter"
import { connect } from "react-redux"
import * as limitOrderActions from "../../../actions/limitOrderActions"
import { ProcessingModal, SortableComponent } from "../../../components/CommonElement"
import limitOrderServices from "../../../services/limit_order";
import { QuoteList, Search } from "../QuoteMarket"

@connect((store, props) => {
  const tokens = store.tokens.tokens
  const favorite_pairs_anonymous = store.limitOrder.favorite_pairs_anonymous
  const currentQuote = store.limitOrder.currentQuote
  return {
    tokens, favorite_pairs_anonymous, currentQuote
  }
})
export default class QuoteMarket extends React.Component{
  constructor() {
    super()
    this.state = {
      quotes: {},
      pairs: {},
      favorite_pairs: [],
      current_search: "",
      current_sort_index: "base",
      current_sort_dsc: true
    }
  }

  componentDidMount() {
    let i = 1
    this.intervalId = setInterval(() => {
      this.updateVolume()
    }, 2000);
    if (common.isUserLogin()) {
      limitOrderServices.getFavoritePairs().then(
        (res) => {
          this.setState({favorite_pairs: res.map(obj => `${obj.base.toUpperCase()}_${obj.quote.toUpperCase()}`)})
        }
      )
    }
  }

  componentWillUnmount() {
    clearInterval(this.intervalId);
  }

  updateVolume = () => {
    limitOrderServices.getVolumeAndChange()
    .then((res) => {
      this.setState((state, props) => ({pairs: res}))
    })
  }

  onQuoteClick = (quote) => {
    this.props.dispatch(limitOrderActions.updateCurrentQuote(quote))
  }

  onSearch = (text) => {
    this.setState((state, props) => ({current_search: text}))
  }

  onFavoriteClick = (base, quote, to_fav) => {
    if (common.isUserLogin()) {
      const {favorite_pairs} = this.state
      const index = favorite_pairs.indexOf(base+"_"+quote)
      if (index == -1){
        favorite_pairs.push(base+"_"+quote)
      }else {
        favorite_pairs.splice(index, 1)
      }
      this.setState({favorite_pairs: favorite_pairs})
      limitOrderServices.updateFavoritePairs(base, quote, to_fav)
    }else {
      this.props.dispatch(limitOrderActions.updateFavoriteAnonymous(base, quote, to_fav))
    }
  }

  onSort = (i, isDsc) => {
    this.setState((state, props)=>({current_sort_index: i, current_sort_dsc: isDsc}))
  }

  search(quotes){
    const { current_search, current_sort_index, current_sort_dsc, pairs } = this.state
    const { currentQuote } = this.props

    return (
      currentQuote === "FAV" ?
        Object.keys(quotes).reduce((res, key) => res.concat(quotes[key]),[]).filter((pair) => pair["is_favorite"]) :
        quotes[currentQuote]
    )
    .filter(pair => (pair["base"].toLowerCase().includes(current_search.toLowerCase())))
    .map(pair => ({
      ...pair,
      volume: (Object.keys(pairs).includes(pair.id) ? pairs[pair.id].volume : "-" ),
      change: (Object.keys(pairs).includes(pair.id) ? pairs[pair.id].change : "0" )
    }))
    .sort(function(a,b){return (current_sort_dsc ? 1 : -1)*(a[current_sort_index] > b[current_sort_index] ? -1 : 1)})
  }

  renderQuotes(){
    const { tokens, favorite_pairs_anonymous } = this.props
    const { favorite_pairs } = this.state
    const fav = common.isUserLogin() ? favorite_pairs : favorite_pairs_anonymous
    const quotes = Object.keys(tokens).filter((key)=> (tokens[key]["is_quote"] && key != "WETH"))
      .reduce((res, quote) => {
        res[quote] = Object.keys(tokens).filter((key)=> (tokens[key]["sp_limit_order"]))
          .reduce((vt, key) =>{
            return key == quote ? vt : vt.concat({
                id: key+"_"+quote,
                base: key, quote: quote,
                price: (+converter.divOfTwoNumber(tokens[key].rate, quote == "ETH" ? '1000000000000000000' : tokens[quote].rate)).toFixed(5),
                is_favorite: fav.includes(key+"_"+quote),
                volume: "-",
                change: "0"
            });
          }, []);
        return res
      },{})
    return quotes;
  }

  renderTh = () => {
    return [
      { html: "Pair", field: "base" },
      { html: "Price", field: "price" },
      { html: "Volume", field: "volume" },
      { html: "Change", field: "change" }
    ].map((i, index) => (
      <div className={`c${index+1}`}>
        <SortableComponent
          Wrapper={"span"}
          key={i["html"]}
          text={i["html"]}
          onClick={(is_dsc) => this.onSort(i["field"], is_dsc)}
          isActive={this.state.current_sort_index == i["field"]} />

    ))
  }

  onPairClick = (base, quote) => {
    this.props.selectSourceAndDestToken(quote == "ETH" ? "WETH" : quote, base);
  }
  render(){
    const quotes = this.renderQuotes()
    const { tokens, currentQuote } = this.props
    const list = Object.keys(quotes).length > 0 ? this.search(quotes) : []
    return (

          { Object.keys(tokens).length > 0 ?

                <QuoteList onClick={this.onQuoteClick} currentQuote={currentQuote} quotes={["FAV"].concat(Object.keys(quotes))}/>
                <Search onSearch={this.onSearch}/>

                    {this.renderTh()}

                  {list.map(pair =>

 this.onPairClick(pair["base"], pair["quote"])}>

 this.onFavoriteClick(pair["base"], pair["quote"], !pair["is_favorite"])}>

{pair["base"] + "/" + pair["quote"]}

{pair["price"]}

{pair["volume"]}

                    <div className={`${pair["change"] > 0 ? "up" : "down"} c4`}>{Math.abs(pair["change"])}%

)}

 :

}

    )
  }
}
<commit_msg>Add priority token<commit_after>import React from "react"
import * as common from "../../../utils/common"
import * as converter from "../../../utils/converter"
import { connect } from "react-redux"
import * as limitOrderActions from "../../../actions/limitOrderActions"
import { ProcessingModal, SortableComponent } from "../../../components/CommonElement"
import limitOrderServices from "../../../services/limit_order";
import { QuoteList, Search } from "../QuoteMarket"

@connect((store, props) => {
  const tokens = store.tokens.tokens
  const favorite_pairs_anonymous = store.limitOrder.favorite_pairs_anonymous
  const currentQuote = store.limitOrder.currentQuote
  return {
    tokens, favorite_pairs_anonymous, currentQuote
  }
})
export default class QuoteMarket extends React.Component{
  constructor() {
    super()
    this.state = {
      quotes: {},
      pairs: {},
      favorite_pairs: [],
      current_search: "",
      current_sort_index: "base",
      current_sort_dsc: true
    }
  }

  componentDidMount() {
    let i = 1
    this.intervalId = setInterval(() => {
      this.updateVolume()
    }, 2000);
    if (common.isUserLogin()) {
      limitOrderServices.getFavoritePairs().then(
        (res) => {
          this.setState({favorite_pairs: res.map(obj => `${obj.base.toUpperCase()}_${obj.quote.toUpperCase()}`)})
        }
      )
    }
  }

  componentWillUnmount() {
    clearInterval(this.intervalId);
  }

  updateVolume = () => {
    limitOrderServices.getVolumeAndChange()
    .then((res) => {
      this.setState((state, props) => ({pairs: res}))
    })
  }

  onQuoteClick = (quote) => {
    this.props.dispatch(limitOrderActions.updateCurrentQuote(quote))
  }

  onSearch = (text) => {
    this.setState((state, props) => ({current_search: text}))
  }

  onFavoriteClick = (base, quote, to_fav) => {
    if (common.isUserLogin()) {
      const {favorite_pairs} = this.state
      const index = favorite_pairs.indexOf(base+"_"+quote)
      if (index == -1){
        favorite_pairs.push(base+"_"+quote)
      }else {
        favorite_pairs.splice(index, 1)
      }
      this.setState({favorite_pairs: favorite_pairs})
      limitOrderServices.updateFavoritePairs(base, quote, to_fav)
    }else {
      this.props.dispatch(limitOrderActions.updateFavoriteAnonymous(base, quote, to_fav))
    }
  }

  onSort = (i, isDsc) => {
    this.setState((state, props)=>({current_sort_index: i, current_sort_dsc: isDsc}))
  }

  search(quotes){
    const { current_search, current_sort_index, current_sort_dsc, pairs } = this.state
    const { currentQuote } = this.props

    return (
      currentQuote === "FAV" ?
        Object.keys(quotes).reduce((res, key) => res.concat(quotes[key]),[]).filter((pair) => pair["is_favorite"]) :
        quotes[currentQuote]
    )
    .filter(pair => (pair["base"].toLowerCase().includes(current_search.toLowerCase())))
    .map(pair => ({
      ...pair,
      volume: (Object.keys(pairs).includes(pair.id) ? pairs[pair.id].volume : "-" ),
      change: (Object.keys(pairs).includes(pair.id) ? pairs[pair.id].change : "0" )
    }))
    .sort(function(a,b){return (current_sort_dsc ? 1 : -1)*(a[current_sort_index] > b[current_sort_index] ? -1 : 1)})
  }

  renderQuotes(){
    const { tokens, favorite_pairs_anonymous } = this.props
    const { favorite_pairs } = this.state
    const fav = common.isUserLogin() ? favorite_pairs : favorite_pairs_anonymous

    const quotes = Object.keys(tokens).filter((key)=> (tokens[key]["is_quote"] && key != "WETH"))
    .sort((first, second) => {
      const firstQuotePriority = tokens[first].quote_priority;
      const secondQuotePriority = tokens[second].quote_priority;

      if (firstQuotePriority && secondQuotePriority) {
        if (firstQuotePriority > secondQuotePriority) return -1;
        else if (firstQuotePriority < secondQuotePriority) return 1;
      }

      return 0;
    })

    const result = quotes.reduce((res, quote) => {
        res[quote] = Object.keys(tokens).filter((key)=> (tokens[key]["sp_limit_order"])).filter(key => {
          // if quote A priority < other quote priorities, remove other quotes from list token of quote A
          const quotePriority = tokens[quote].quote_priority;
          const tokenPriority = tokens[key].quote_priority;

          if (quotePriority && tokenPriority && quotePriority < tokenPriority) {
            // remove from list
            return false;
          }
          return true;
        })
          .reduce((vt, key) =>{
            return key == quote ? vt : vt.concat({
                id: key+"_"+quote,
                base: key, quote: quote,
                price: (+converter.divOfTwoNumber(tokens[key].rate, quote == "ETH" ? '1000000000000000000' : tokens[quote].rate)).toFixed(5),
                is_favorite: fav.includes(key+"_"+quote),
                volume: "-",
                change: "0"
            });
          }, []);
        return res
      },{});
    return result;
  }

  renderTh = () => {
    return [
      { html: "Pair", field: "base" },
      { html: "Price", field: "price" },
      { html: "Volume", field: "volume" },
      { html: "Change", field: "change" }
    ].map((i, index) => (
      <div className={`c${index+1}`}>
        <SortableComponent
          Wrapper={"span"}
          key={i["html"]}
          text={i["html"]}
          onClick={(is_dsc) => this.onSort(i["field"], is_dsc)}
          isActive={this.state.current_sort_index == i["field"]} />

    ))
  }

  onPairClick = (base, quote) => {
    this.props.selectSourceAndDestToken(quote == "ETH" ? "WETH" : quote, base);
  }
  render(){
    const quotes = this.renderQuotes()
    const { tokens, currentQuote } = this.props
    const list = Object.keys(quotes).length > 0 ? this.search(quotes) : []
    return (

          { Object.keys(tokens).length > 0 ?

                <QuoteList onClick={this.onQuoteClick} currentQuote={currentQuote} quotes={["FAV"].concat(Object.keys(quotes))}/>
                <Search onSearch={this.onSearch}/>

                    {this.renderTh()}

                  {list.map(pair =>

 this.onPairClick(pair["base"], pair["quote"])}>

 this.onFavoriteClick(pair["base"], pair["quote"], !pair["is_favorite"])}>

{pair["base"] + "/" + pair["quote"]}

{pair["price"]}

{pair["volume"]}

                    <div className={`${pair["change"] > 0 ? "up" : "down"} c4`}>{Math.abs(pair["change"])}%

)}

 :

}

    )
  }
}
<|endoftext|>


<commit_before>var queue = require('queue-async');
var fs = require('fs');
var util = require('util');
var Carmen = require('..');
var index = require('../lib/index');
var feature = require('../lib/util/feature');
var mem = require('../lib/api-mem');
var UPDATE = process.env.UPDATE;
var test = require('tape');

// limit_verify 1 implies that the correct result must be the very top
// result prior to context verification. It means even with a long list
// of competing results the correct candidate is sorted to the top.

// limit_verify 2 implies that there is some ambiguity prior to context
// verification (e.g. new york (city) vs new york (province)) that is sorted
// into the correct order after context verification occurs.

(function() {
    var conf = {
        province: new mem(null, function() {}),
        city: new mem(null, function() {}),
        street: new mem({ maxzoom:6, geocoder_address:1 }, function() {})
    };
    var c = new Carmen(conf);
    test('index province', function(t) {
        var province = {
            _id:1,
            _text:'new york, ny',
            _zxy:['6/32/32','6/33/32'],
            _center:[0,0]
        };
        conf.province.putGrid(6, 32, 32, solidGrid(province));
        conf.province.putGrid(6, 33, 32, solidGrid(province));
        index.update(conf.province, [province], t.end);
    });
    test('index city 1', function(t) {
        var city = {
            _id:1,
            _text:'new york, ny',
            _zxy:['6/32/32'],
            _center:[0,0]
        };
        conf.city.putGrid(6, 32, 32, solidGrid(city));
        index.update(conf.city, [city], t.end);
    });
    test('index city 2', function(t) {
        var city = {
            _id:2,
            _text:'tonawanda',
            _zxy:['6/33/32'],
            _center:[360/64,0]
        };
        conf.city.putGrid(6, 33, 32, solidGrid(city));
        index.update(conf.city, [city], t.end);
    });
    test('index street 1', function(t) {
        var street = {
            _id:1,
            _text:'west st',
            _zxy:['6/32/32'],
            _center:[0,0]
        };
        conf.street.putGrid(6, 32, 32, solidGrid(street));
        index.update(conf.street, [street], t.end);
    });
    test('index street 2', function(t) {
        var street = {
            _id:2,
            _text:'west st',
            _zxy:['6/33/32'],
            _center:[360/64,0]
        };
        conf.street.putGrid(6, 33, 32, solidGrid(street));
        index.update(conf.street, [street], t.end);
    });
    test('west st, tonawanda, ny', function(t) {
        c.geocode('west st tonawanda ny', { limit_verify:1 }, function(err, res) {
            t.ifError(err);
            t.deepEqual(res.features[0].place_name, 'west st, tonawanda, new york');
            t.end();
        });
    });
    test('west st, new york, ny', function(t) {
        c.geocode('west st new york ny', { limit_verify:1 }, function(err, res) {
            t.ifError(err);
            t.deepEqual(res.features[0].place_name, 'west st, new york, new york');
            t.end();
        });
    });
    test('new york', function(t) {
        c.geocode('new york', { limit_verify:2 }, function(err, res) {
            t.ifError(err);
            t.deepEqual(res.features[0].place_name, 'new york');
            t.deepEqual(res.features[0].id, 'province.1');
            t.end();
        });
    });
    test('new york new york', function(t) {
        c.geocode('new york new york', { limit_verify:2 }, function(err, res) {
            t.ifError(err);
            t.deepEqual(res.features[0].place_name, 'new york, new york');
            t.deepEqual(res.features[0].id, 'city.1');
            t.end();
        });
    });
    test('ny ny', function(t) {
        c.geocode('ny ny', { limit_verify:2 }, function(err, res) {
            t.ifError(err);
            t.deepEqual(res.features[0].place_name, 'new york, new york');
            t.deepEqual(res.features[0].id, 'city.1');
            t.end();
        });
    });
    // failing
    test.skip('new york ny', function(t) {
        c.geocode('new york ny', { limit_verify:2 }, function(err, res) {
            t.ifError(err);
            t.deepEqual(res.features[0].place_name, 'new york, new york');
            t.deepEqual(res.features[0].id, 'city.1');
            t.end();
        });
    });
})();

(function() {
    var conf = {
        province: new mem(null, function() {}),
        postcode: new mem(null, function() {}),
        city: new mem(null, function() {}),
        street: new mem({ maxzoom:6, geocoder_address:1 }, function() {})
    };
    var c = new Carmen(conf);
    test('index province', function(t) {
        var province = {
            _id:1,
            _text:'connecticut, ct',
            _zxy:['6/32/32'],
            _center:[0,0]
        };
        conf.province.putGrid(6, 32, 32, solidGrid(province));
        index.update(conf.province, [province], t.end);
    });
    test('index city', function(t) {
        var city = {
            _id:1,
            _text:'windsor',
            _zxy:['6/32/32'],
            _center:[0,0]
        };
        conf.city.putGrid(6, 32, 32, solidGrid(city));
        index.update(conf.city, [city], t.end);
    });
    test('index street', function(t) {
        var street = {
            _id:1,
            _text:'windsor ct',
            _zxy:['6/33/32'],
            _center:[360/64,0]
        };
        conf.street.putGrid(6, 33, 32, solidGrid(street));
        index.update(conf.street, [street], t.end);
    });
    // failing
    // city beats street at spatialmatch
    test.skip('windsor ct (limit 1)', function(t) {
        c.geocode('windsor ct', { limit_verify:1 }, function(err, res) {
            t.ifError(err);
            t.deepEqual(res.features[0].place_name, 'windsor, connecticut');
            t.deepEqual(res.features[0].id, 'city.1');
            t.end();
        });
    });
    // failing
    // city beats street at context sort
    test.skip('windsor ct (limit 2)', function(t) {
        c.geocode('windsor ct', { limit_verify:2 }, function(err, res) {
            t.ifError(err);
            t.deepEqual(res.features[0].place_name, 'windsor, connecticut');
            t.deepEqual(res.features[0].id, 'city.1');
            t.end();
        });
    });
})();

function solidGrid(feature) {
    return {
        "grid": [
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                "
        ],
        "keys": [
            "89"
        ],
        "data": {
            "89": feature
        }
    };
};

<commit_msg>Update tests to confirm first-in-hierarchy priority is preserved amongst ties.<commit_after>var queue = require('queue-async');
var fs = require('fs');
var util = require('util');
var Carmen = require('..');
var index = require('../lib/index');
var feature = require('../lib/util/feature');
var mem = require('../lib/api-mem');
var UPDATE = process.env.UPDATE;
var test = require('tape');

// limit_verify 1 implies that the correct result must be the very top
// result prior to context verification. It means even with a long list
// of competing results the correct candidate is sorted to the top.

// limit_verify 2 implies that there is some ambiguity prior to context
// verification (e.g. new york (city) vs new york (province)) that is sorted
// into the correct order after context verification occurs.

(function() {
    var conf = {
        province: new mem(null, function() {}),
        city: new mem(null, function() {}),
        street: new mem({ maxzoom:6, geocoder_address:1 }, function() {})
    };
    var c = new Carmen(conf);
    test('index province', function(t) {
        var province = {
            _id:1,
            _text:'new york, ny',
            _zxy:['6/32/32','6/33/32'],
            _center:[0,0]
        };
        conf.province.putGrid(6, 32, 32, solidGrid(province));
        conf.province.putGrid(6, 33, 32, solidGrid(province));
        index.update(conf.province, [province], t.end);
    });
    test('index city 1', function(t) {
        var city = {
            _id:1,
            _text:'new york, ny',
            _zxy:['6/32/32'],
            _center:[0,0]
        };
        conf.city.putGrid(6, 32, 32, solidGrid(city));
        index.update(conf.city, [city], t.end);
    });
    test('index city 2', function(t) {
        var city = {
            _id:2,
            _text:'tonawanda',
            _zxy:['6/33/32'],
            _center:[360/64,0]
        };
        conf.city.putGrid(6, 33, 32, solidGrid(city));
        index.update(conf.city, [city], t.end);
    });
    test('index street 1', function(t) {
        var street = {
            _id:1,
            _text:'west st',
            _zxy:['6/32/32'],
            _center:[0,0]
        };
        conf.street.putGrid(6, 32, 32, solidGrid(street));
        index.update(conf.street, [street], t.end);
    });
    test('index street 2', function(t) {
        var street = {
            _id:2,
            _text:'west st',
            _zxy:['6/33/32'],
            _center:[360/64,0]
        };
        conf.street.putGrid(6, 33, 32, solidGrid(street));
        index.update(conf.street, [street], t.end);
    });
    test('west st, tonawanda, ny', function(t) {
        c.geocode('west st tonawanda ny', { limit_verify:1 }, function(err, res) {
            t.ifError(err);
            t.deepEqual(res.features[0].place_name, 'west st, tonawanda, new york');
            t.end();
        });
    });
    test('west st, new york, ny', function(t) {
        c.geocode('west st new york ny', { limit_verify:1 }, function(err, res) {
            t.ifError(err);
            t.deepEqual(res.features[0].place_name, 'west st, new york, new york');
            t.end();
        });
    });
    test('new york', function(t) {
        c.geocode('new york', { limit_verify:1 }, function(err, res) {
            t.ifError(err);
            t.deepEqual(res.features[0].place_name, 'new york');
            t.deepEqual(res.features[0].id, 'province.1');
            t.end();
        });
    });
    test('new york new york', function(t) {
        c.geocode('new york new york', { limit_verify:1 }, function(err, res) {
            t.ifError(err);
            t.deepEqual(res.features[0].place_name, 'new york, new york');
            t.deepEqual(res.features[0].id, 'city.1');
            t.end();
        });
    });
    test('ny ny', function(t) {
        c.geocode('ny ny', { limit_verify:1 }, function(err, res) {
            t.ifError(err);
            t.deepEqual(res.features[0].place_name, 'new york, new york');
            t.deepEqual(res.features[0].id, 'city.1');
            t.end();
        });
    });
    // failing
    test.skip('new york ny', function(t) {
        c.geocode('new york ny', { limit_verify:2 }, function(err, res) {
            t.ifError(err);
            t.deepEqual(res.features[0].place_name, 'new york, new york');
            t.deepEqual(res.features[0].id, 'city.1');
            t.end();
        });
    });
})();

// Confirm that for equally relevant features across three indexes
// the first in hierarchy beats the others.
(function() {
    var conf = {
        country: new mem(null, function() {}),
        province: new mem(null, function() {}),
        city: new mem(null, function() {}),
    };
    var c = new Carmen(conf);
    test('index country', function(t) {
        var country = {
            _id:1,
            _text:'china',
            _zxy:['6/32/32'],
            _center:[0,0]
        };
        conf.country.putGrid(6, 32, 32, solidGrid(country));
        index.update(conf.country, [country], t.end);
    });
    test('index province', function(t) {
        var province = {
            _id:1,
            _text:'china',
            _zxy:['6/33/32'],
            _center:[360/64,0]
        };
        conf.province.putGrid(6, 33, 32, solidGrid(province));
        index.update(conf.province, [province], t.end);
    });
    test('index city', function(t) {
        var city = {
            _id:1,
            _text:'china',
            _zxy:['6/34/32'],
            _center:[360/64*2,0]
        };
        conf.city.putGrid(6, 34, 32, solidGrid(city));
        index.update(conf.city, [city], t.end);
    });
    test('china', function(t) {
        c.geocode('china', { limit_verify:1 }, function(err, res) {
            t.ifError(err);
            t.deepEqual(res.features[0].place_name, 'china');
            t.deepEqual(res.features[0].id, 'country.1');
            t.end();
        });
    });
})();

(function() {
    var conf = {
        province: new mem(null, function() {}),
        postcode: new mem(null, function() {}),
        city: new mem(null, function() {}),
        street: new mem({ maxzoom:6, geocoder_address:1 }, function() {})
    };
    var c = new Carmen(conf);
    test('index province', function(t) {
        var province = {
            _id:1,
            _text:'connecticut, ct',
            _zxy:['6/32/32'],
            _center:[0,0]
        };
        conf.province.putGrid(6, 32, 32, solidGrid(province));
        index.update(conf.province, [province], t.end);
    });
    test('index city', function(t) {
        var city = {
            _id:1,
            _text:'windsor',
            _zxy:['6/32/32'],
            _center:[0,0]
        };
        conf.city.putGrid(6, 32, 32, solidGrid(city));
        index.update(conf.city, [city], t.end);
    });
    test('index street', function(t) {
        var street = {
            _id:1,
            _text:'windsor ct',
            _zxy:['6/33/32'],
            _center:[360/64,0]
        };
        conf.street.putGrid(6, 33, 32, solidGrid(street));
        index.update(conf.street, [street], t.end);
    });
    // failing
    // city beats street at spatialmatch
    test.skip('windsor ct (limit 1)', function(t) {
        c.geocode('windsor ct', { limit_verify:1 }, function(err, res) {
            t.ifError(err);
            t.deepEqual(res.features[0].place_name, 'windsor, connecticut');
            t.deepEqual(res.features[0].id, 'city.1');
            t.end();
        });
    });
    // failing
    // city beats street at context sort
    test.skip('windsor ct (limit 2)', function(t) {
        c.geocode('windsor ct', { limit_verify:2 }, function(err, res) {
            t.ifError(err);
            t.deepEqual(res.features[0].place_name, 'windsor, connecticut');
            t.deepEqual(res.features[0].id, 'city.1');
            t.end();
        });
    });
})();

function solidGrid(feature) {
    return {
        "grid": [
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                ",
            "                                                                "
        ],
        "keys": [
            "89"
        ],
        "data": {
            "89": feature
        }
    };
};

<|endoftext|>


<commit_before>var hyperquest = require('hyperquest');
var concat = require('concat-stream');
var assert = require('assert');
var vm = require('vm');
var http = require('http');
var browserify = require('../');

var REPEAT_COUNT = 2;
if (process.env.npm_lifecycle_event === 'test:perf' ||
    process.env.npm_lifecycle_event === 'test' && process.env.CI) {
  REPEAT_COUNT = 50;

  console.warn('  Each file is downloaded ~' + REPEAT_COUNT + ' times in parallel to get some feel for how');
  console.warn('  performance scales.');
  console.warn();
  console.warn('  When comparing gzip and not gzip, don\'t forget to account for increased');
  console.warn('  time unzipping on the client.');
} else {
  console.warn('  To test the performance, run `npm run test:perf`');
  console.warn('  which will download each file 50 times in prallel');
}

var app = {middleware: []}
app.use = function (path, handler) {
  app.middleware.push(function (url, req, res, next) {
    if (url.pathname.indexOf(path) !== 0) return next()
    else {
      req.path = url.pathname.replace(path, '')
      handler(req, res, next)
    }
  })
}
app.get = function (path, handler) {
  app.middleware.push(function (url, req, res, next) {
    if (url.pathname !== path) return next()
    else handler(req, res, next)
  })
}

app.use('/file/jqparse.js', browserify(__dirname + '/directory/jquery.min.js', {cache: false, gzip: false, minify: false, debug: false}))
app.use('/file/jqnoparse.js', browserify(__dirname + '/directory/jquery.min.js', {cache: false, gzip: false, minify: false, debug: false, noParse: [__dirname + '/directory/jquery.min.js']}))

app.use('/file/beep.js', browserify(__dirname + '/directory/beep.js', {
  cache: 'dynamic',
  gzip: false,
  minify: false,
  debug: true
}));
app.use('/opt/file/beep.js', browserify(__dirname + '/directory/beep.js', {
  cache: true,
  precompile: true,
  gzip: true,
  minify: true,
  debug: false
}));
app.use('/file/boop.js', browserify(__dirname + '/directory/boop.js', {
  cache: 'dynamic',
  gzip: false,
  minify: false,
  debug: true
}));
app.use('/opt/file/boop.js', browserify(__dirname + '/directory/boop.js', {
  cache: true,
  gzip: true,
  minify: true,
  debug: false
}));
app.use('/syntax-error.js', browserify(__dirname + '/directory/syntax-error.js', {
  cache: 'dynamic',
  gzip: false,
  minify: false,
  debug: true
}));
app.use('/opt/syntax-error.js', browserify(__dirname + '/directory/syntax-error.js', {
  cache: true,
  gzip: true,
  minify: true,
  debug: false
}));
app.use('/weirddep.js', browserify(__dirname + '/directory/weirddep.js', {
  extensions: ['.weird']
}));
app.use('/opt/weirddep.js', browserify(__dirname + '/directory/weirddep.js', {
  extensions: ['.weird'],
  gzip: true
}));

app.use('/dir', browserify(__dirname + '/directory', {
  cache: 'dynamic',
  gzip: false,
  minify: false,
  debug: true
}));
app.use('/opt/dir', browserify(__dirname + '/directory', {
  cache: true,
  gzip: true,
  minify: true,
  debug: false
}));

app.use('/mod.js', browserify(['require-test'], {
  cache: 'dynamic',
  gzip: false,
  minify: false,
  debug: true,
  external: ['require-test']
}));
app.use('/opt/mod.js', browserify(['require-test'], {
  cache: true,
  precompile: true,
  gzip: true,
  minify: true,
  debug: false,
  external: ['require-test']
}));
app.use('/modObj.js', browserify([{'require-test': {expose: 'require-test-exposed'}}], {
  cache: false,
  gzip: false,
  minify: false,
  debug: true
}));
app.use('/opt/modObj.js', browserify([{'require-test': {expose: 'require-test-exposed'}}], {
  cache: true,
  gzip: true,
  minify: true,
  debug: false
}));

app.get('/dir/file.txt', function (req, res) {
  res.end('foo');
});
app.get('/opt/dir/file.txt', function (req, res) {
  res.end('foo');
});
app.get('/dir/non-existant.js', function (req, res) {
  res.end('bar');
});
app.get('/opt/dir/non-existant.js', function (req, res) {
  res.end('bar');
});

app.get('/no-minify.js', browserify(__dirname + '/directory/no-minify.js', {
  cache: false,
  gzip: false,
  minify: {
    mangle: false
  },
  debug: true
}));
app.get('/opt/no-minify.js', browserify(__dirname + '/directory/no-minify.js', {
  cache: true,
  gzip: true,
  minify: {
    mangle: false
  },
  debug: false
}));

app.get('/fullpaths.js', browserify(__dirname + '/directory/beep.js', {
  cache: false,
  gzip: false,
  minify: {
    mangle: false
  },
  debug: true,
  fullPaths: true
}));
app.get('/opt/fullpaths.js', browserify(__dirname + '/directory/beep.js', {
  cache: true,
  gzip: true,
  minify: {
    mangle: false
  },
  debug: false,
  fullPaths: true
}));

app.get('/opt/no-bundle-external.js', browserify(__dirname + '/directory/no-bundle-external.js', {
  bundleExternal: false,
  debug: false,
}));

var port;
(function () {
  var listeners = [];
  port = function (fn) {
    listeners.push(fn);
  };
  http.createServer(function (req, res) {
    var url = require('url').parse(req.url)
    var i = 0
    function next(err) {
      if (err) return res.statusCode = 500, res.end(err.stack || err.message || err);
      if (i === app.middleware.length) {
        console.dir(url)
        return res.statusCode = 404, res.end('404 file not found');
      }
      app.middleware[i++](url, req, res, next)
    }
    next()
  })
  .listen(0, function () {
    var pt = this.address().port;
    while (listeners.length) {
      listeners.shift()(pt);
    }
    port = function (fn) {
      fn(pt);
    }
  });
}());

function get(path, optimised, cb) {
  port(function (port) {
    var erred = false;
    hyperquest('http://localhost:' + port + (optimised ? '/opt' : '') + path, function (err, res) {
      erred = err || res.statusCode >= 400;
      if (err) return cb(err);
      if (res.statusCode >= 400) {
        var err = new Error('Server responded with status code ' + res.statusCode);
        err.statusCode = res.statusCode;
        return cb(err);
      }
    })
    .pipe(concat(function (res) {
      if (erred) return;
      return cb(null, res.toString());
    }));
  })
}
function getZip(path, optimised, cb) {
  if (/non-existant/.test(path) || /file\.txt/.test(path)) {
    return get(path, optimised, cb);
  }
  port(function (port) {
    hyperquest('http://localhost:' + port + (optimised ? '/opt' : '') + path, {headers: {'Accept-Encoding':'gzip'}},
      function (err, res) {
        if (err) return cb(err);
        if (res.statusCode >= 400) {
          var err = new Error('Server responded with status code ' + res.statusCode);
          err.statusCode = res.statusCode;
          return cb(err);
        }
        this.pipe(require('zlib').createGunzip())
            .pipe(concat(function (res) {
              return cb(null, res.toString());
            }));
      })
  })
}

function test(optimised, get, it) {
  var oldIt = it;
  it = function (name, fn) {
    return oldIt(name, function (done) {
      this.slow(100);
      fn(function (err) {
        if (err) return done(err);
        if (/syntax error/.test(name)) return done();
        fn(function (err) {
          if (err) return done(err);
          var pending = REPEAT_COUNT;
          for (var i = 0; i < REPEAT_COUNT; i++) {
            fn(then);
          };
          var called = false;
          function then(err) {
            if (err && !called) {
              called = true;
              return done(err);
            }
            if (--pending === 0 && !called) return done();
          }
        })
      })
    });
  };
  it.skip = oldIt.skip.bind(oldIt);
  describe('file', function () {
    it('browserifies beep', function (done) {
      get('/file/beep.js', optimised, function (err, res) {
        if (err) return done(err);
        vm.runInNewContext(res, {
          console: {
            log: function (txt) {
              assert.equal(txt, 'BEEP!');
              done();
            }
          }
        })
      });
    });
    it('browserifies boop', function (done) {
      get('/file/boop.js', optimised, function (err, res) {
        if (err) return done(err);
        vm.runInNewContext(res, {
          console: {
            log: function (txt) {
              assert.equal(txt, 'BOOP!');
              done();
            }
          }
        })
      });
    });
    it('returns error code 500 if there is a syntax error', function (done) {
      get('/syntax-error.js', optimised, function (err, res) {
        assert.equal(err.statusCode, 500);
        done();
      });
    })
  });
  describe('directory', function () {
    it('browserifies beep', function (done) {
      get('/dir/beep.js', optimised, function (err, res) {
        if (err) return done(err);
        vm.runInNewContext(res, {
          console: {
            log: function (txt) {
              assert.equal(txt, 'BEEP!');
              done();
            }
          }
        })
      });
    });
    it('browserifies boop', function (done) {
      get('/dir/boop.js', optimised, function (err, res) {
        if (err) return done(err);
        vm.runInNewContext(res, {
          console: {
            log: function (txt) {
              assert.equal(txt, 'BOOP!');
              done();
            }
          }
        })
      });
    });
    it('falls through if the file is not a JavaScript file', function (done) {
      get('/dir/file.txt', optimised, function (err, res) {
        if (err) return done(err);
        assert.equal(res, 'foo');
        done();
      });
    });
    it('falls through if the file does not exist', function (done) {
      get('/dir/non-existant.js', optimised, function (err, res) {
        if (err) return done(err);
        assert.equal(res, 'bar');
        done();
      });
    });
    // see: https://github.com/substack/node-browserify/pull/907
    it.skip('makes require available (using module options object)', function (done) {
      get('/modObj.js', optimised, function (err, res) {
        if (err) return done(err);
        vm.runInNewContext(res, {
          console: {
            log: function () {
              throw new Error('Module should wait to be required');
            }
          }
        });
        vm.runInNewContext(res + '\nrequire("require-test-exposed");', {
          console: {
            log: function (res) {
              assert.equal(res, 'required');
              done();
            }
          }
        });
      });
    });
  });
  describe('package', function () {
    it('makes require available', function (done) {
      get('/mod.js', optimised, function (err, res) {
        if (err) return done(err);
        vm.runInNewContext(res, {
          console: {
            log: function () {
              throw new Error('Module should wait to be required');
            }
          }
        });
        vm.runInNewContext(res + '\nrequire("require-test");', {
          console: {
            log: function (res) {
              assert.equal(res, 'required');
              done();
            }
          }
        });
      });
    });
  });
  describe('extensions', function () {
    it('includes files required with weird extensions', function (done) {
      get('/weirddep.js', optimised, function (err, res) {
        if (err) return done(err);
        vm.runInNewContext(res, {
          console: {
            log: function (txt) {
              assert.equal(txt, 'this is a weird file to require');
              done();
            }
          }
        })
      });
    });
  });
  describe('minify: options', function () {
    it('passes options to uglifyjs', function (done) {
      get('/no-minify.js', optimised, function (err, res) {
        if (err) return done(err);
        assert(/add\(foo,bar\){return foo\+bar}console\.log\(add\(1,2\)\)/.test(res));
        vm.runInNewContext(res, {
          console: {
            log: function (res) {
              assert.equal(res, 3);
              done();
            }
          }
        })
      });
    });
  });
  describe('passes other options to browserify', function () {
    it('passes fullPaths', function (done) {
      get('/fullpaths.js', optimised, function (err, res) {
        if (err) return done(err);
        assert(res.indexOf('test/directory/beep.js') != -1);

        vm.runInNewContext(res, {
          console: {
            log: function (res) {
              assert.equal(res, 'BEEP!');
              done();
            }
          }
        })
      });
    });
  });
}

describe('In NODE_ENV=development (default)', function () {
  test(false, get, it);
});

describe('In NODE_ENV=production', function () {
  describe('without gzip', function () {
    test(true, getZip, it);
  });
  describe('with gzip', function () {
    test(true, get, it);
  });
});

describe('options.noParse', function () {
  it('speeds things up by at least a factor of 5 (for jQuery)', function (done) {
    this.slow(1000)
    this.timeout(20000)
    var start = new Date();
    get('/file/jqparse.js', false, function (err, res) {
      if (err) return done(err);
      var middle = new Date();
      get('/file/jqnoparse.js', false, function (err, res) {
        if (err) return done(err);
        var end = new Date();
        assert((middle - start) > (end - middle) * 5, 'Without noParse was ' + (middle - start) + ' with noParse was ' + (end - middle));
        done();
      });
    });
  });
});

describe('options.bundleExternal= false', function () {
  it('Exclude node_modules and builtins', function (done) {
    this.slow(1000)
    this.timeout(20000)
    var start = new Date();
    get('/opt/no-bundle-external.js', false, function (err, res) {
      if (err) return done(err);
      assert.equal(res.match(/Copyright Joyent, Inc/), null);
      done();
    });
  });
});
<commit_msg>Fix test case<commit_after>var hyperquest = require('hyperquest');
var concat = require('concat-stream');
var assert = require('assert');
var vm = require('vm');
var http = require('http');
var browserify = require('../');

var REPEAT_COUNT = 2;
if (process.env.npm_lifecycle_event === 'test:perf' ||
    process.env.npm_lifecycle_event === 'test' && process.env.CI) {
  REPEAT_COUNT = 50;

  console.warn('  Each file is downloaded ~' + REPEAT_COUNT + ' times in parallel to get some feel for how');
  console.warn('  performance scales.');
  console.warn();
  console.warn('  When comparing gzip and not gzip, don\'t forget to account for increased');
  console.warn('  time unzipping on the client.');
} else {
  console.warn('  To test the performance, run `npm run test:perf`');
  console.warn('  which will download each file 50 times in prallel');
}

var app = {middleware: []}
app.use = function (path, handler) {
  app.middleware.push(function (url, req, res, next) {
    if (url.pathname.indexOf(path) !== 0) return next()
    else {
      req.path = url.pathname.replace(path, '')
      handler(req, res, next)
    }
  })
}
app.get = function (path, handler) {
  app.middleware.push(function (url, req, res, next) {
    if (url.pathname !== path) return next()
    else handler(req, res, next)
  })
}

app.use('/file/jqparse.js', browserify(__dirname + '/directory/jquery.min.js', {cache: false, gzip: false, minify: false, debug: false}))
app.use('/file/jqnoparse.js', browserify(__dirname + '/directory/jquery.min.js', {cache: false, gzip: false, minify: false, debug: false, noParse: [__dirname + '/directory/jquery.min.js']}))

app.use('/file/beep.js', browserify(__dirname + '/directory/beep.js', {
  cache: 'dynamic',
  gzip: false,
  minify: false,
  debug: true
}));
app.use('/opt/file/beep.js', browserify(__dirname + '/directory/beep.js', {
  cache: true,
  precompile: true,
  gzip: true,
  minify: true,
  debug: false
}));
app.use('/file/boop.js', browserify(__dirname + '/directory/boop.js', {
  cache: 'dynamic',
  gzip: false,
  minify: false,
  debug: true
}));
app.use('/opt/file/boop.js', browserify(__dirname + '/directory/boop.js', {
  cache: true,
  gzip: true,
  minify: true,
  debug: false
}));
app.use('/syntax-error.js', browserify(__dirname + '/directory/syntax-error.js', {
  cache: 'dynamic',
  gzip: false,
  minify: false,
  debug: true
}));
app.use('/opt/syntax-error.js', browserify(__dirname + '/directory/syntax-error.js', {
  cache: true,
  gzip: true,
  minify: true,
  debug: false
}));
app.use('/weirddep.js', browserify(__dirname + '/directory/weirddep.js', {
  extensions: ['.weird']
}));
app.use('/opt/weirddep.js', browserify(__dirname + '/directory/weirddep.js', {
  extensions: ['.weird'],
  gzip: true
}));

app.use('/dir', browserify(__dirname + '/directory', {
  cache: 'dynamic',
  gzip: false,
  minify: false,
  debug: true
}));
app.use('/opt/dir', browserify(__dirname + '/directory', {
  cache: true,
  gzip: true,
  minify: true,
  debug: false
}));

app.use('/mod.js', browserify(['require-test'], {
  cache: 'dynamic',
  gzip: false,
  minify: false,
  debug: true,
  external: ['require-test']
}));
app.use('/opt/mod.js', browserify(['require-test'], {
  cache: true,
  precompile: true,
  gzip: true,
  minify: true,
  debug: false,
  external: ['require-test']
}));
app.use('/modObj.js', browserify([{'require-test': {expose: 'require-test-exposed'}}], {
  cache: false,
  gzip: false,
  minify: false,
  debug: true
}));
app.use('/opt/modObj.js', browserify([{'require-test': {expose: 'require-test-exposed'}}], {
  cache: true,
  gzip: true,
  minify: true,
  debug: false
}));

app.get('/dir/file.txt', function (req, res) {
  res.end('foo');
});
app.get('/opt/dir/file.txt', function (req, res) {
  res.end('foo');
});
app.get('/dir/non-existant.js', function (req, res) {
  res.end('bar');
});
app.get('/opt/dir/non-existant.js', function (req, res) {
  res.end('bar');
});

app.get('/no-minify.js', browserify(__dirname + '/directory/no-minify.js', {
  cache: false,
  gzip: false,
  minify: {
    mangle: false
  },
  debug: true
}));
app.get('/opt/no-minify.js', browserify(__dirname + '/directory/no-minify.js', {
  cache: true,
  gzip: true,
  minify: {
    mangle: false
  },
  debug: false
}));

app.get('/fullpaths.js', browserify(__dirname + '/directory/beep.js', {
  cache: false,
  gzip: false,
  minify: {
    mangle: false
  },
  debug: true,
  fullPaths: true
}));
app.get('/opt/fullpaths.js', browserify(__dirname + '/directory/beep.js', {
  cache: true,
  gzip: true,
  minify: {
    mangle: false
  },
  debug: false,
  fullPaths: true
}));

app.get('/opt/no-bundle-external.js', browserify(__dirname + '/directory/no-bundle-external.js', {
  bundleExternal: false,
  debug: false,
}));

var port;
(function () {
  var listeners = [];
  port = function (fn) {
    listeners.push(fn);
  };
  http.createServer(function (req, res) {
    var url = require('url').parse(req.url)
    var i = 0
    function next(err) {
      if (err) return res.statusCode = 500, res.end(err.stack || err.message || err);
      if (i === app.middleware.length) {
        console.dir(url)
        return res.statusCode = 404, res.end('404 file not found');
      }
      app.middleware[i++](url, req, res, next)
    }
    next()
  })
  .listen(0, function () {
    var pt = this.address().port;
    while (listeners.length) {
      listeners.shift()(pt);
    }
    port = function (fn) {
      fn(pt);
    }
  });
}());

function get(path, optimised, cb) {
  port(function (port) {
    var erred = false;
    hyperquest('http://localhost:' + port + (optimised ? '/opt' : '') + path, function (err, res) {
      erred = err || res.statusCode >= 400;
      if (err) return cb(err);
      if (res.statusCode >= 400) {
        var err = new Error('Server responded with status code ' + res.statusCode);
        err.statusCode = res.statusCode;
        return cb(err);
      }
    })
    .pipe(concat(function (res) {
      if (erred) return;
      return cb(null, res.toString());
    }));
  })
}
function getZip(path, optimised, cb) {
  if (/non-existant/.test(path) || /file\.txt/.test(path)) {
    return get(path, optimised, cb);
  }
  port(function (port) {
    hyperquest('http://localhost:' + port + (optimised ? '/opt' : '') + path, {headers: {'Accept-Encoding':'gzip'}},
      function (err, res) {
        if (err) return cb(err);
        if (res.statusCode >= 400) {
          var err = new Error('Server responded with status code ' + res.statusCode);
          err.statusCode = res.statusCode;
          return cb(err);
        }
        this.pipe(require('zlib').createGunzip())
            .pipe(concat(function (res) {
              return cb(null, res.toString());
            }));
      })
  })
}

function test(optimised, get, it) {
  var oldIt = it;
  it = function (name, fn) {
    return oldIt(name, function (done) {
      this.slow(100);
      fn(function (err) {
        if (err) return done(err);
        if (/syntax error/.test(name)) return done();
        fn(function (err) {
          if (err) return done(err);
          var pending = REPEAT_COUNT;
          for (var i = 0; i < REPEAT_COUNT; i++) {
            fn(then);
          };
          var called = false;
          function then(err) {
            if (err && !called) {
              called = true;
              return done(err);
            }
            if (--pending === 0 && !called) return done();
          }
        })
      })
    });
  };
  it.skip = oldIt.skip.bind(oldIt);
  describe('file', function () {
    it('browserifies beep', function (done) {
      get('/file/beep.js', optimised, function (err, res) {
        if (err) return done(err);
        vm.runInNewContext(res, {
          console: {
            log: function (txt) {
              assert.equal(txt, 'BEEP!');
              done();
            }
          }
        })
      });
    });
    it('browserifies boop', function (done) {
      get('/file/boop.js', optimised, function (err, res) {
        if (err) return done(err);
        vm.runInNewContext(res, {
          console: {
            log: function (txt) {
              assert.equal(txt, 'BOOP!');
              done();
            }
          }
        })
      });
    });
    it('returns error code 500 if there is a syntax error', function (done) {
      get('/syntax-error.js', optimised, function (err, res) {
        assert.equal(err.statusCode, 500);
        done();
      });
    })
  });
  describe('directory', function () {
    it('browserifies beep', function (done) {
      get('/dir/beep.js', optimised, function (err, res) {
        if (err) return done(err);
        vm.runInNewContext(res, {
          console: {
            log: function (txt) {
              assert.equal(txt, 'BEEP!');
              done();
            }
          }
        })
      });
    });
    it('browserifies boop', function (done) {
      get('/dir/boop.js', optimised, function (err, res) {
        if (err) return done(err);
        vm.runInNewContext(res, {
          console: {
            log: function (txt) {
              assert.equal(txt, 'BOOP!');
              done();
            }
          }
        })
      });
    });
    it('falls through if the file is not a JavaScript file', function (done) {
      get('/dir/file.txt', optimised, function (err, res) {
        if (err) return done(err);
        assert.equal(res, 'foo');
        done();
      });
    });
    it('falls through if the file does not exist', function (done) {
      get('/dir/non-existant.js', optimised, function (err, res) {
        if (err) return done(err);
        assert.equal(res, 'bar');
        done();
      });
    });
    // see: https://github.com/substack/node-browserify/pull/907
    it.skip('makes require available (using module options object)', function (done) {
      get('/modObj.js', optimised, function (err, res) {
        if (err) return done(err);
        vm.runInNewContext(res, {
          console: {
            log: function () {
              throw new Error('Module should wait to be required');
            }
          }
        });
        vm.runInNewContext(res + '\nrequire("require-test-exposed");', {
          console: {
            log: function (res) {
              assert.equal(res, 'required');
              done();
            }
          }
        });
      });
    });
  });
  describe('package', function () {
    it('makes require available', function (done) {
      get('/mod.js', optimised, function (err, res) {
        if (err) return done(err);
        vm.runInNewContext(res, {
          console: {
            log: function () {
              throw new Error('Module should wait to be required');
            }
          }
        });
        vm.runInNewContext(res + '\nrequire("require-test");', {
          console: {
            log: function (res) {
              assert.equal(res, 'required');
              done();
            }
          }
        });
      });
    });
  });
  describe('extensions', function () {
    it('includes files required with weird extensions', function (done) {
      get('/weirddep.js', optimised, function (err, res) {
        if (err) return done(err);
        vm.runInNewContext(res, {
          console: {
            log: function (txt) {
              assert.equal(txt, 'this is a weird file to require');
              done();
            }
          }
        })
      });
    });
  });
  describe('minify: options', function () {
    it('passes options to uglifyjs', function (done) {
      get('/no-minify.js', optimised, function (err, res) {
        if (err) return done(err);
        assert(res.indexOf("console.log(function(foo,bar){return foo+bar}(1,2))") !== -1);
        vm.runInNewContext(res, {
          console: {
            log: function (res) {
              assert.equal(res, 3);
              done();
            }
          }
        })
      });
    });
  });
  describe('passes other options to browserify', function () {
    it('passes fullPaths', function (done) {
      get('/fullpaths.js', optimised, function (err, res) {
        if (err) return done(err);
        assert(res.indexOf('test/directory/beep.js') != -1);

        vm.runInNewContext(res, {
          console: {
            log: function (res) {
              assert.equal(res, 'BEEP!');
              done();
            }
          }
        })
      });
    });
  });
}

describe('In NODE_ENV=development (default)', function () {
  test(false, get, it);
});

describe('In NODE_ENV=production', function () {
  describe('without gzip', function () {
    test(true, getZip, it);
  });
  describe('with gzip', function () {
    test(true, get, it);
  });
});

describe('options.noParse', function () {
  it('speeds things up by at least a factor of 5 (for jQuery)', function (done) {
    this.slow(1000)
    this.timeout(20000)
    var start = new Date();
    get('/file/jqparse.js', false, function (err, res) {
      if (err) return done(err);
      var middle = new Date();
      get('/file/jqnoparse.js', false, function (err, res) {
        if (err) return done(err);
        var end = new Date();
        assert((middle - start) > (end - middle) * 5, 'Without noParse was ' + (middle - start) + ' with noParse was ' + (end - middle));
        done();
      });
    });
  });
});

describe('options.bundleExternal= false', function () {
  it('Exclude node_modules and builtins', function (done) {
    this.slow(1000)
    this.timeout(20000)
    var start = new Date();
    get('/opt/no-bundle-external.js', false, function (err, res) {
      if (err) return done(err);
      assert.equal(res.match(/Copyright Joyent, Inc/), null);
      done();
    });
  });
});
<|endoftext|>