<commit_before>(function( jStat, Math ) {

var slice = [].slice,
	isNumber = jStat.utils.isNumber;

// flag==true denotes use of sample standard deviation
// Z Statistics
jStat.extend({
	// 2 different parameter lists:
	// ( value, mean, sd )
	// ( value, array, flag )
	zscore : function() {
		var args = slice.call( arguments );
		if ( isNumber( args[1] )) {
			return ( args[0] - args[1] ) / args[2];
		}
		return ( args[0] - jStat.mean( args[1] )) / jStat.stdev( args[1], args[2] );
	},

	// 3 different paramter lists:
	// ( value, mean, sd, sides )
	// ( zscore, sides )
	// ( value, array, sides, flag )
	ztest : function() {
		var args = slice.call( arguments );
		if ( args.length === 4 ) {
			if( isNumber( args[1] )) {
				return ( args[3] === 1 ) ?
					(1-jStat.normal.cdf( Math.abs( args[0] ), args[1], args[2] )) :
				( 2 *  jStat.normal.cdf( Math.abs( args[0] ), args[1], args[2] )- 2);
			}
			return ( args[2] === 1 ) ?
				( 1 - jStat.normal.cdf( Math.abs( args[0] ), jStat.mean( args[1] ), jStat.stdev( args[1],args[3] ))) :
			( 2 * jStat.normal.cdf( Math.abs( args[0] ), jStat.mean( args[1] ), jStat.stdev( args[1],args[3] ))-2);
		}
		return ( args[1] === 1 ) ?
			( 1 - jStat.normal.cdf( Math.abs( args[0] ), 0, 1 )) :
		( 2 * jStat.normal.cdf( Math.abs( args[0] ), 0, 1 )-2);
	}
});

jStat.extend( jStat.fn, {
	zscore : function( value, flag ) {
		return ( value - this.mean()) / this.stdev( flag );
	},

	ztest : function( value, sides, flag ) {
		var zscore = Math.abs( this.zscore( value, flag ));
		return ( sides === 1 ) ?
			( 1 - jStat.normal.cdf( zscore, 0, 1 )) :
		(2 * jStat.normal.cdf( zscore, 0, 1 ) -2);
	}
});

// T Statistics
jStat.extend({
	// 2 parameter lists
	// ( value, mean, sd, n )
	// ( value, array )
	tscore : function() {
		var args = slice.call( arguments );
		return ( args.length === 4 ) ?
			(( args[0] - args[1] ) / ( args[2] / Math.sqrt( args[3] ))) :
		(( args[0] - jStat.mean( args[1] )) / ( jStat.stdev( args[1], true ) / Math.sqrt( args[1].length )));
	},

	// 3 different paramter lists:
	// ( value, mean, sd, n, sides )
	// ( tscore, n, sides )
	// ( value, array, sides )
	ttest : function() {
		var args = slice.call( arguments );
		var tscore;
		if ( args.length === 5 ) {
			tscore = Math.abs( jStat.tscore( args[0], args[1], args[2], args[3] ));
			return ( args[4] === 1 ) ?
				( 1 - jStat.studentt.cdf( tscore, args[3] )) :
			( 2 * jStat.studentt.cdf( tscore, args[3])-2);
		}
		if ( isNumber( args[1] )) {
			tscore = Math.abs( args[0] )
			return ( args[2] == 1 ) ?
				( 1 - jStat.studentt.cdf( tscore, args[1])) :
			( 2 * jStat.studentt.cdf( tscore, args[1])-2);
		}
		tscore = Math.abs( jStat.tscore( args[0], args[1] ))
		return ( args[2] == 1 ) ?
			( 1 - jStat.studentt.cdf( tscore, args[1].length-1)) :
		( 2 * jStat.studentt.cdf( tscore, args[1].length-1)-2);
	}
});

jStat.extend( jStat.fn, {
	tscore : function( value ) {
		return ( value - this.mean()) / ( this.stdev( true ) / Math.sqrt( this.cols()));
	},

	ttest : function( value, sides ) {
		return ( sides === 1 ) ?
			( 1 - jStat.studentt.cdf( Math.abs( this.tscore(value)), this.cols()-1)) :
		( 2 * jStat.studentt.cdf( Math.abs( this.tscore(value)), this.cols()-1)-2);
	}
});

// F Statistics
jStat.extend({
	// Paramter list is as follows:
	// ( array1, array2, array3, ... )
	// or it is an array of arrays
	// array of arrays conversion
	anovafscore : function() {
		var args = slice.call( arguments ),
			expVar, sample, sampMean, sampSampMean, tmpargs, unexpVar, i, j;
		if ( args.length === 1 ) {
			tmpargs = new Array( args[0].length );
			for ( i = 0; i < args[0].length; i++ ) {
				tmpargs[i] = args[0][i];
			}
			args = tmpargs;
		}
		// 2 sample case
		if ( args.length === 2 ) {
			return jStat.variance( args[0] ) / jStat.variance( args[1] );
		}
		// Builds sample array
		sample = new Array();
		for ( i = 0; i < args.length; i++ ) {
			sample = sample.concat( args[i] );
		}
		sampMean = jStat.mean( sample );
		// Computes the explained variance
		expVar = 0;
		for ( i = 0; i < args.length; i++ ) {
			expVar = expVar + args[i].length * Math.pow( jStat.mean( args[i] ) - sampMean, 2 );
		}
		expVar /= ( args.length - 1 );
		// Computes unexplained variance
		unexpVar = 0;
		for ( i = 0; i < args.length; i++ ) {
			sampSampMean = jStat.mean( args[i] );
			for ( j = 0; j < args[i].length; j++ ) {
				unexpVar += Math.pow( args[i][j] - sampSampMean, 2 );
			}
		}
		unexpVar /= ( sample.length - args.length );
		return expVar / unexpVar;
	},

	// 2 different paramter setups
	// ( array1, array2, array3, ... )
	// ( anovafscore, df1, df2 )
	anovaftest : function() {
		var args = slice.call( arguments ),
			df1, df2, n, i;
		if ( isNumber( args[0] )) {
			return 1 - jStat.centralF.cdf( args[0], args[1], args[2] );
		}
		anovafscore = jStat.anovafscore( args );
		df1 = args.length - 1;
		n = 0;
		for ( i = 0; i < args.length; i++ ) {
			n = n + args[i].length;
		}
		df2 = n - df1 - 1;
		return 1 - jStat.centralF.cdf( anovafscore, df1, df2 );
	},

	ftest : function( fscore, df1, df2 ) {
		return 1 - jStat.centralF.cdf( fscore, df1, df2 );
	}
});

jStat.extend( jStat.fn, {
	anovafscore : function() {
		return jStat.anovafscore( this.toArray());
	},

	anovaftest: function() {
		var n = 0,
			i;
		for ( i = 0; i < this.length; i++ ) {
			n = n + this[i].length;
		}
		return jStat.ftest( this.anovafscore(), this.length - 1, n - this.length );
	}
});

// Error Bounds
jStat.extend({
	// 2 different parameter setups
	// ( value, alpha, sd, n )
	// ( value, alpha, array )
	normalci : function() {
		var args = slice.call( arguments ),
			ans = new Array(2),
			change;
		if ( args.length === 4 ) {
			change = Math.abs( jStat.normal.inv( args[1] / 2, 0, 1 ) * args[2] / Math.sqrt( args[3] ));
		} else {
			change = Math.abs( jStat.normal.inv( args[1] / 2, 0, 1 ) * jStat.stdev( args[2] ) / Math.sqrt( args[2].length ));
		}
		ans[0] = args[0] - change;
		ans[1] = args[0] + change;
		return ans;
	},

	// 2 different parameter setups
	// ( value, alpha, sd, n )
	// ( value, alpha, array )
	tci : function() {
		var args = slice.call( arguments ),
			ans = new Array(2),
			change;
		if ( args.length === 4 ) {
			change = Math.abs( jStat.studentt.inv( args[1] / 2, args[3] - 1 ) * args[2] / Math.sqrt( args[3] ));
		} else {
			change = Math.abs( jStat.studentt.inv( args[1] / 2, args[2].length ) * jStat.stdev( args[2], true ) / Math.sqrt( args[2].length ));
		}
		ans[0] = args[0] - change;
		ans[1] = args[0] + change;
		return ans;
	},

	significant : function( pvalue, alpha ) {
		return pvalue < alpha;
	}
});

jStat.extend( jStat.fn, {
	normalci : function( value, alpha ) {
		return jStat.normalci( value, alpha, this.toArray());
	},

	tci : function( value, alpha ) {
		return jStat.tci( value, alpha, this.toArray());
	}
});

}( this.jStat, Math ));
<commit_msg>Fixes Multiply by -1 Error<commit_after>(function( jStat, Math ) {

var slice = [].slice,
	isNumber = jStat.utils.isNumber;

// flag==true denotes use of sample standard deviation
// Z Statistics
jStat.extend({
	// 2 different parameter lists:
	// ( value, mean, sd )
	// ( value, array, flag )
	zscore : function() {
		var args = slice.call( arguments );
		if ( isNumber( args[1] )) {
			return ( args[0] - args[1] ) / args[2];
		}
		return ( args[0] - jStat.mean( args[1] )) / jStat.stdev( args[1], args[2] );
	},

	// 3 different paramter lists:
	// ( value, mean, sd, sides )
	// ( zscore, sides )
	// ( value, array, sides, flag )
	ztest : function() {
		var args = slice.call( arguments );
		if ( args.length === 4 ) {
			if( isNumber( args[1] )) {
				return ( args[3] === 1 ) ?
					(1-jStat.normal.cdf( Math.abs( args[0] ), args[1], args[2] )) :
				( 2 -  jStat.normal.cdf( Math.abs( args[0] ), args[1], args[2] )* 2);
			}
			return ( args[2] === 1 ) ?
				( 1 - jStat.normal.cdf( Math.abs( args[0] ), jStat.mean( args[1] ), jStat.stdev( args[1],args[3] ))) :
			( 2 - jStat.normal.cdf( Math.abs( args[0] ), jStat.mean( args[1] ), jStat.stdev( args[1],args[3] ))*2);
		}
		return ( args[1] === 1 ) ?
			( 1 - jStat.normal.cdf( Math.abs( args[0] ), 0, 1 )) :
		( 2 - jStat.normal.cdf( Math.abs( args[0] ), 0, 1 )*2);
	}
});

jStat.extend( jStat.fn, {
	zscore : function( value, flag ) {
		return ( value - this.mean()) / this.stdev( flag );
	},

	ztest : function( value, sides, flag ) {
		var zscore = Math.abs( this.zscore( value, flag ));
		return ( sides === 1 ) ?
			( 1 - jStat.normal.cdf( zscore, 0, 1 )) :
		(2 - jStat.normal.cdf( zscore, 0, 1 ) * 2);
	}
});

// T Statistics
jStat.extend({
	// 2 parameter lists
	// ( value, mean, sd, n )
	// ( value, array )
	tscore : function() {
		var args = slice.call( arguments );
		return ( args.length === 4 ) ?
			(( args[0] - args[1] ) / ( args[2] / Math.sqrt( args[3] ))) :
		(( args[0] - jStat.mean( args[1] )) / ( jStat.stdev( args[1], true ) / Math.sqrt( args[1].length )));
	},

	// 3 different paramter lists:
	// ( value, mean, sd, n, sides )
	// ( tscore, n, sides )
	// ( value, array, sides )
	ttest : function() {
		var args = slice.call( arguments );
		var tscore;
		if ( args.length === 5 ) {
			tscore = Math.abs( jStat.tscore( args[0], args[1], args[2], args[3] ));
			return ( args[4] === 1 ) ?
				( 1 - jStat.studentt.cdf( tscore, args[3] )) :
			( 2 - jStat.studentt.cdf( tscore, args[3])*2);
		}
		if ( isNumber( args[1] )) {
			tscore = Math.abs( args[0] )
			return ( args[2] == 1 ) ?
				( 1 - jStat.studentt.cdf( tscore, args[1])) :
			( 2 - jStat.studentt.cdf( tscore, args[1]) * 2);
		}
		tscore = Math.abs( jStat.tscore( args[0], args[1] ))
		return ( args[2] == 1 ) ?
			( 1 - jStat.studentt.cdf( tscore, args[1].length-1)) :
		( 2 - jStat.studentt.cdf( tscore, args[1].length-1) * 2);
	}
});

jStat.extend( jStat.fn, {
	tscore : function( value ) {
		return ( value - this.mean()) / ( this.stdev( true ) / Math.sqrt( this.cols()));
	},

	ttest : function( value, sides ) {
		return ( sides === 1 ) ?
			( 1 - jStat.studentt.cdf( Math.abs( this.tscore(value)), this.cols()-1)) :
		( 2 * jStat.studentt.cdf( Math.abs( this.tscore(value)), this.cols()-1)-2);
	}
});

// F Statistics
jStat.extend({
	// Paramter list is as follows:
	// ( array1, array2, array3, ... )
	// or it is an array of arrays
	// array of arrays conversion
	anovafscore : function() {
		var args = slice.call( arguments ),
			expVar, sample, sampMean, sampSampMean, tmpargs, unexpVar, i, j;
		if ( args.length === 1 ) {
			tmpargs = new Array( args[0].length );
			for ( i = 0; i < args[0].length; i++ ) {
				tmpargs[i] = args[0][i];
			}
			args = tmpargs;
		}
		// 2 sample case
		if ( args.length === 2 ) {
			return jStat.variance( args[0] ) / jStat.variance( args[1] );
		}
		// Builds sample array
		sample = new Array();
		for ( i = 0; i < args.length; i++ ) {
			sample = sample.concat( args[i] );
		}
		sampMean = jStat.mean( sample );
		// Computes the explained variance
		expVar = 0;
		for ( i = 0; i < args.length; i++ ) {
			expVar = expVar + args[i].length * Math.pow( jStat.mean( args[i] ) - sampMean, 2 );
		}
		expVar /= ( args.length - 1 );
		// Computes unexplained variance
		unexpVar = 0;
		for ( i = 0; i < args.length; i++ ) {
			sampSampMean = jStat.mean( args[i] );
			for ( j = 0; j < args[i].length; j++ ) {
				unexpVar += Math.pow( args[i][j] - sampSampMean, 2 );
			}
		}
		unexpVar /= ( sample.length - args.length );
		return expVar / unexpVar;
	},

	// 2 different paramter setups
	// ( array1, array2, array3, ... )
	// ( anovafscore, df1, df2 )
	anovaftest : function() {
		var args = slice.call( arguments ),
			df1, df2, n, i;
		if ( isNumber( args[0] )) {
			return 1 - jStat.centralF.cdf( args[0], args[1], args[2] );
		}
		anovafscore = jStat.anovafscore( args );
		df1 = args.length - 1;
		n = 0;
		for ( i = 0; i < args.length; i++ ) {
			n = n + args[i].length;
		}
		df2 = n - df1 - 1;
		return 1 - jStat.centralF.cdf( anovafscore, df1, df2 );
	},

	ftest : function( fscore, df1, df2 ) {
		return 1 - jStat.centralF.cdf( fscore, df1, df2 );
	}
});

jStat.extend( jStat.fn, {
	anovafscore : function() {
		return jStat.anovafscore( this.toArray());
	},

	anovaftest: function() {
		var n = 0,
			i;
		for ( i = 0; i < this.length; i++ ) {
			n = n + this[i].length;
		}
		return jStat.ftest( this.anovafscore(), this.length - 1, n - this.length );
	}
});

// Error Bounds
jStat.extend({
	// 2 different parameter setups
	// ( value, alpha, sd, n )
	// ( value, alpha, array )
	normalci : function() {
		var args = slice.call( arguments ),
			ans = new Array(2),
			change;
		if ( args.length === 4 ) {
			change = Math.abs( jStat.normal.inv( args[1] / 2, 0, 1 ) * args[2] / Math.sqrt( args[3] ));
		} else {
			change = Math.abs( jStat.normal.inv( args[1] / 2, 0, 1 ) * jStat.stdev( args[2] ) / Math.sqrt( args[2].length ));
		}
		ans[0] = args[0] - change;
		ans[1] = args[0] + change;
		return ans;
	},

	// 2 different parameter setups
	// ( value, alpha, sd, n )
	// ( value, alpha, array )
	tci : function() {
		var args = slice.call( arguments ),
			ans = new Array(2),
			change;
		if ( args.length === 4 ) {
			change = Math.abs( jStat.studentt.inv( args[1] / 2, args[3] - 1 ) * args[2] / Math.sqrt( args[3] ));
		} else {
			change = Math.abs( jStat.studentt.inv( args[1] / 2, args[2].length ) * jStat.stdev( args[2], true ) / Math.sqrt( args[2].length ));
		}
		ans[0] = args[0] - change;
		ans[1] = args[0] + change;
		return ans;
	},

	significant : function( pvalue, alpha ) {
		return pvalue < alpha;
	}
});

jStat.extend( jStat.fn, {
	normalci : function( value, alpha ) {
		return jStat.normalci( value, alpha, this.toArray());
	},

	tci : function( value, alpha ) {
		return jStat.tci( value, alpha, this.toArray());
	}
});

}( this.jStat, Math ));
<|endoftext|>


<commit_before>/*
 * thar - Automatic content anchors link plugin for jQuery
 * https://github.com/gocom/thar
 *
 * Copyright (C) 2013 Jukka Svahn
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

/**
 * @name jQuery
 * @class
 */

/**
 * @name fn
 * @class
 * @memberOf jQuery
 */

;(function (factory)
{
    if (typeof define === 'function' && define.amd)
    {
        define(['jquery'], factory);
    }
    else
    {
        factory(jQuery);
    }
}(function ($)
{
    var hash = window.location.hash.substr(1), occurrences = {'' : 0}, methods = {};

    /**
     * Sets an anchor ID from the element text contents.
     *
     * @return   {Object}         this
     * @method   setAnchorID
     * @memberof jQuery.fn.thar
     */

    methods.setAnchorID = function ()
    {
        return this.each(function ()
        {
            var $this = $(this), id = $this.attr('id'), content;

            if (!id)
            {
                content = $this.text();

                id = encodeURIComponent(content.replace(/\s/g, '-'))
                    .replace(/[^A-Z0-9\-]/gi, '-')
                    .substr(0, 255)
                    .replace(/^[\d\-]|-$/g, '')
                    .replace(/-{2,}/g, '-')
                    .toLowerCase();

                if ($.type(occurrences[id]) !== 'undefined')
                {
                    occurrences[id]++;
                    id += '_' + occurrences[id];
                }
                else if (document.getElementById(id))
                {
                    occurrences[id] = 1;
                    id += '_1';
                }
                else
                {
                    occurrences[id] = 1;
                }

                $this.attr('id', id);
            }
        });
    };

    /**
     * Scrolls to the selected element.
     *
     * @return   {Object}         this
     * @method   scrollTo
     * @memberof jQuery.fn.thar
     */

    methods.scrollTo = function ()
    {
        var $this = $(this).eq(0), id = $this.attr('id');

        $('html, body').animate({
            scrollTop : $this.offset().top
        }, 1000, 'swing', function ()
        {
            if (id)
            {
                window.location.hash = '#' + id;
            }
        });

        return this;
    };

    /**
     * Renders content anchor links.
     *
     * @param    {Object}         options                   Options
     * @param    {String}         [options.prefix='']       A prefix added to the generated links
     * @param    {String|Boolean} [options.anchor=>#167] The anchor link text
     * @return   {Object}         this
     * @method   init
     * @memberof jQuery.fn.thar
     */

    methods.init = function (options)
    {
        options = $.extend({
            'anchor' : '§'
        }, options);

        var ul = $('
');

        return this.thar('setAnchorID').each(function ()
        {
            var _this = this, $this = $(this), id = $this.attr('id'), anchor, content = $this.text();

            if ($this.hasClass('jquery-thar'))
            {
                return;
            }

            $this.addClass('jquery-thar').trigger('anchorcreate.thar');

            if (id === hash)
            {
                methods.scrollTo.apply(this);

                $this.trigger('anchorload.thar', {
                    'id' : id
                });

                hash = false;
            }

            ul.append(
                $('
')
                    .addClass('jquery-thar-to-' + id)
                    .html(
                        $('')
                            .attr('href', '#' + id)
                            .text(content)
                            .on('click.thar', function (e)
                            {
                                e.preventDefault();
                                methods.scrollTo.apply(_this);
                            })
                    )
            );

            if (options.anchor !== false)
            {
                anchor = $('')
                    .attr('href', '#' + id)
                    .on('click.thar', function (e)
                    {
                        e.preventDefault();
                        methods.scrollTo.apply(_this);
                    });

                if (options.anchor === true)
                {
                    $this.wrapInner(anchor);
                }
                else
                {
                    $this.prepend(anchor.html(options.anchor)).prepend(' ');
                }
            }
        })
        .extend({
            tharResults :
            {
                'ul' : ul
            }
        });
    };

    /**
     * Renders content anchor links.
     *
     * @param    {String}  [method=init] The called method
     * @param    {Object}  [options={}]  Options passed to the method
     * @class    thar
     * @memberof jQuery.fn
     */

    $.fn.thar = function (method, options)
    {
        if ($.type(method) !== 'string' || $.type(methods[method]) !== 'function')
        {
            options = method;
            method = 'init';
        }

        return methods[method].call(this, options);
    };
}));<commit_msg>Prevent ID collisions.<commit_after>/*
 * thar - Automatic content anchors link plugin for jQuery
 * https://github.com/gocom/thar
 *
 * Copyright (C) 2013 Jukka Svahn
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

/**
 * @name jQuery
 * @class
 */

/**
 * @name fn
 * @class
 * @memberOf jQuery
 */

;(function (factory)
{
    if (typeof define === 'function' && define.amd)
    {
        define(['jquery'], factory);
    }
    else
    {
        factory(jQuery);
    }
}(function ($)
{
    var hash = window.location.hash.substr(1), methods = {};

    /**
     * Sets an anchor ID from the element text contents.
     *
     * @return   {Object}         this
     * @method   setAnchorID
     * @memberof jQuery.fn.thar
     */

    methods.setAnchorID = function ()
    {
        return this.each(function ()
        {
            var $this = $(this), id = $this.attr('id'), content, occurrences = 1;

            if (!id)
            {
                content = $this.text();

                id = encodeURIComponent(content.replace(/\s/g, '-'))
                    .replace(/[^A-Z0-9\-]/gi, '-')
                    .substr(0, 255)
                    .replace(/^[\d\-]|-$/g, '')
                    .replace(/-{2,}/g, '-')
                    .toLowerCase();

                uniqueID = id;

                while (1)
                {
                    if (!document.getElementById(uniqueID))
                    {
                        $this.attr('id', uniqueID);
                        return;
                    }

                    uniqueID = id + '-' + (occurrences++);
                }
            }
        });
    };

    /**
     * Scrolls to the selected element.
     *
     * @return   {Object}         this
     * @method   scrollTo
     * @memberof jQuery.fn.thar
     */

    methods.scrollTo = function ()
    {
        var $this = $(this).eq(0), id = $this.attr('id');

        $('html, body').animate({
            scrollTop : $this.offset().top
        }, 1000, 'swing', function ()
        {
            if (id)
            {
                window.location.hash = '#' + id;
            }
        });

        return this;
    };

    /**
     * Renders content anchor links.
     *
     * @param    {Object}         options                   Options
     * @param    {String}         [options.prefix='']       A prefix added to the generated links
     * @param    {String|Boolean} [options.anchor=>#167] The anchor link text
     * @return   {Object}         this
     * @method   init
     * @memberof jQuery.fn.thar
     */

    methods.init = function (options)
    {
        options = $.extend({
            'anchor' : '§'
        }, options);

        var ul = $('
');

        return this.thar('setAnchorID').each(function ()
        {
            var _this = this, $this = $(this), id = $this.attr('id'), anchor, content = $this.text();

            if ($this.hasClass('jquery-thar'))
            {
                return;
            }

            $this.addClass('jquery-thar').trigger('anchorcreate.thar');

            if (id === hash)
            {
                methods.scrollTo.apply(this);

                $this.trigger('anchorload.thar', {
                    'id' : id
                });

                hash = false;
            }

            ul.append(
                $('
')
                    .addClass('jquery-thar-to-' + id)
                    .html(
                        $('')
                            .attr('href', '#' + id)
                            .text(content)
                            .on('click.thar', function (e)
                            {
                                e.preventDefault();
                                methods.scrollTo.apply(_this);
                            })
                    )
            );

            if (options.anchor !== false)
            {
                anchor = $('')
                    .attr('href', '#' + id)
                    .on('click.thar', function (e)
                    {
                        e.preventDefault();
                        methods.scrollTo.apply(_this);
                    });

                if (options.anchor === true)
                {
                    $this.wrapInner(anchor);
                }
                else
                {
                    $this.prepend(anchor.html(options.anchor)).prepend(' ');
                }
            }
        })
        .extend({
            tharResults :
            {
                'ul' : ul
            }
        });
    };

    /**
     * Renders content anchor links.
     *
     * @param    {String}  [method=init] The called method
     * @param    {Object}  [options={}]  Options passed to the method
     * @class    thar
     * @memberof jQuery.fn
     */

    $.fn.thar = function (method, options)
    {
        if ($.type(method) !== 'string' || $.type(methods[method]) !== 'function')
        {
            options = method;
            method = 'init';
        }

        return methods[method].call(this, options);
    };
}));<|endoftext|>


<commit_before>(function (window, undefined) {

	'use strict';

	var root = this,
	doc = root.document,

	slice = Array.prototype.slice,
	hasOwnProperty = Object.prototype.hasOwnProperty;

	var regXContainsTag = /^\s*<(\w+|!)[^>]*>/;
	var regXDataType = /^\[object\s+(.*?)\]$/;

	var tool = function(selector, context) {
		return new Tool(selector, context);
	};

	// Constructor
	var Tool = function(selector, context) {

		var nodes, currentContext = doc;

        if (context){
			if (context.nodeType){//it's either a document node or element node
				currentContext = context;
			} else { //else it's a string selector, use it to select a node
				currentContext = doc.querySelector(context);
			}
		}

		if (!selector || selector === '' || typeof selector === 'string' && selector.trim() === '') {
			this.length = 0;
			return this;
		}

		if (typeof selector === 'string' && regXContainsTag.test(selector)) {
			var divEl = currentContext.createElement('div');
			divEl.className = 'tool-frag';

			var docFrag = currentContext.createDocumentFragment();
			docFrag.appendChild(divEl);

			var queryDiv = docFrag.querySelector('div');
			queryDiv.textContent = selector;

			var numChildren = queryDiv.children.length;

			for (var c = 0; c < numChildren; c++) {
				this[c] = queryDiv[c];
			}

			this.length = numChildren;

			return this;
		}

		if (typeof selector === 'object' && selector.nodeName) {
			this.length = 1;
			this[0] = selector;

			return this;
		}

		if (typeof selector !== 'string') {
			nodes = selector;
		}
		else {
			nodes = currentContext.querySelectorAll(selector.trim());
		}

		for (var i = 0, nodeLen = nodes.length; i < nodeLen; i++) {
			this[i] = nodes[i];
		}

		this.length = nodes.length;

		return this;
	};

	root.tool = tool;

	tool.fn = Tool.prototype = {
		constructor: tool,

		version: '0.0.1',

		each: function(callback) {
			var len = this.length;

			for (var i = 0; i < len; i++) {
				callback.call(this[i], i, this[i]);
			}

			return this;
			// return tool.each(this, callback);
		},

		size: function() {
			console.log(this.type());
			return this.length;
		},

		get: function(index) {
			return index === undefined ? this[0] : this[index];
		},

		at: function(index) {
			var res = this.get(index);
			return tool(res);
		},

		first: function() {
			return tool(this[0]);
		},

		last: function() {
			return tool(this[this.length - 1]);
		},

		map: function (callback) {
			var results = [];

			this.each(function(value, key) {

			})

			for (var i = 0; i < this.length; i++) {
				results.push(callback.call(this, this[i], i));
			}

			return results;
        },

		show: function() {
			return this.each(function() {
				this.style.display = 'block';
			});
		},

		hide: function() {
			return this.each(function() {
				this.style.display = 'none';
			});
		},

		html: function(html) {
			if (html) {
				return this.each(function() {
					this.innerHTML = html;
				});
			}
			else {
				return this[0].innerHTML;
			}
		},

		text: function(text) {
			if (text) {
				return this.each(function() {
					this.textContent = text;
				});
			}
			else {
				return this[0].textContent.trim();
			}
		},

		empty: function() {
			return this.each(function() {
				this.textContent = '';
			});
		},

		children: function() {
			var res = [],
				kids = this[0].childNodes;

			for (var i in kids) {
				if (kids[i].nodeType === 1) {
					res.push(kids[i]);
				}
			}

			return tool(res);
		},

		has: function(selector) {
			var found = false;

			this.each(function() {
				var collection = this.querySelectorAll(selector);
				if (collection.length) {
					found = true;
				}
			});

			return found;
		},

		find: function(selector) {
			var res = [];

			this.each(function() {
				var collection = this.querySelectorAll(selector);
				if (collection.length) {
					tool.each(collection, function() {
						res.push(this);
					});
				}
			});

			return tool(res);
		},

		append: function(thing) {
			return this.each(function() {
				if (typeof thing === 'string') {
					this.insertAdjacentHTML('beforeend', thing);
				}
				else {
					var that = this;
					tool(thing).each(function(name, value) {
						that.insertAdjacentHTML('beforeend', value.outerHTML);
					});
				}
			});
		},

		prepend: function(thing) {
			return this.each(function() {
				if (typeof thing === 'string') {
					this.insertAdjacentHTML('afterbegin', thing);
				}
				else {
					var that = this;
					tool(thing).each(function(name, value) {
						that.insertAdjacentHTML('afterbegin', value.outerHTML);
					});
				}
			});
		}

	};

	tool.each = function(obj, callback) {
		var name,
			length = obj.length;

		if (length === undefined) {
			for (name in obj) {
				if (callback.call(obj[name], name) === false) {
					break;
				}
			}
		}
		else {
			for (var i = 0; i < length; i++) {
				if (callback.call(obj[i], i) === false) {
					break;
				}
			}
		}

		return tool(obj);
	};

	tool.type = function(obj) {
		var res = Object.prototype.toString.call(obj).match(regXDataType)[1].toLowerCase();
		return res;
	};

}).call(this);
<commit_msg>appendTo method<commit_after>(function (window, undefined) {

	'use strict';

	var root = this,
	doc = root.document,

	slice = Array.prototype.slice,
	hasOwnProperty = Object.prototype.hasOwnProperty;

	var regXContainsTag = /^\s*<(\w+|!)[^>]*>/;
	var regXDataType = /^\[object\s+(.*?)\]$/;

	var tool = function(selector, context) {
		return new Tool(selector, context);
	};

	// Constructor
	var Tool = function(selector, context) {

		var nodes, currentContext = doc;

        if (context){
			if (context.nodeType){//it's either a document node or element node
				currentContext = context;
			} else { //else it's a string selector, use it to select a node
				currentContext = doc.querySelector(context);
			}
		}

		if (!selector || selector === '' || typeof selector === 'string' && selector.trim() === '') {
			this.length = 0;
			return this;
		}

		if (typeof selector === 'string' && regXContainsTag.test(selector)) {
			var divEl = currentContext.createElement('div');
			divEl.className = 'tool-frag';

			var docFrag = currentContext.createDocumentFragment();
			docFrag.appendChild(divEl);

			var queryDiv = docFrag.querySelector('div');
			queryDiv.textContent = selector;

			var numChildren = queryDiv.children.length;

			for (var c = 0; c < numChildren; c++) {
				this[c] = queryDiv[c];
			}

			this.length = numChildren;

			return this;
		}

		if (typeof selector === 'object' && selector.nodeName) {
			this.length = 1;
			this[0] = selector;

			return this;
		}

		if (typeof selector !== 'string') {
			nodes = selector;
		}
		else {
			nodes = currentContext.querySelectorAll(selector.trim());
		}

		for (var i = 0, nodeLen = nodes.length; i < nodeLen; i++) {
			this[i] = nodes[i];
		}

		this.length = nodes.length;

		return this;
	};

	root.tool = tool;

	tool.fn = Tool.prototype = {
		constructor: tool,

		version: '0.0.1',

		each: function(callback) {
			var len = this.length;

			for (var i = 0; i < len; i++) {
				callback.call(this[i], i, this[i]);
			}

			return this;
			// return tool.each(this, callback);
		},

		size: function() {
			console.log(this.type());
			return this.length;
		},

		get: function(index) {
			return index === undefined ? this[0] : this[index];
		},

		at: function(index) {
			var res = this.get(index);
			return tool(res);
		},

		first: function() {
			return tool(this[0]);
		},

		last: function() {
			return tool(this[this.length - 1]);
		},

		map: function (callback) {
			var results = [];

			this.each(function(value, key) {

			})

			for (var i = 0; i < this.length; i++) {
				results.push(callback.call(this, this[i], i));
			}

			return results;
        },

		show: function() {
			return this.each(function() {
				this.style.display = 'block';
			});
		},

		hide: function() {
			return this.each(function() {
				this.style.display = 'none';
			});
		},

		html: function(html) {
			if (html) {
				return this.each(function() {
					this.innerHTML = html;
				});
			}
			else {
				return this[0].innerHTML;
			}
		},

		text: function(text) {
			if (text) {
				return this.each(function() {
					this.textContent = text;
				});
			}
			else {
				return this[0].textContent.trim();
			}
		},

		empty: function() {
			return this.each(function() {
				this.textContent = '';
			});
		},

		children: function() {
			var res = [],
				kids = this[0].childNodes;

			for (var i in kids) {
				if (kids[i].nodeType === 1) {
					res.push(kids[i]);
				}
			}

			return tool(res);
		},

		has: function(selector) {
			var found = false;

			this.each(function() {
				var collection = this.querySelectorAll(selector);
				if (collection.length) {
					found = true;
				}
			});

			return found;
		},

		find: function(selector) {
			var res = [];

			this.each(function() {
				var collection = this.querySelectorAll(selector);
				if (collection.length) {
					tool.each(collection, function() {
						res.push(this);
					});
				}
			});

			return tool(res);
		},

		append: function(thing) {
			return this.each(function() {
				if (typeof thing === 'string') {
					this.insertAdjacentHTML('beforeend', thing);
				}
				else {
					var that = this;
					tool(thing).each(function(name, value) {
						that.insertAdjacentHTML('beforeend', value.outerHTML);
					});
				}
			});
		},

		prepend: function(thing) {
			return this.each(function() {
				if (typeof thing === 'string') {
					this.insertAdjacentHTML('afterbegin', thing);
				}
				else {
					var that = this;
					tool(thing).each(function(name, value) {
						that.insertAdjacentHTML('afterbegin', value.outerHTML);
					});
				}
			});
		},

		appendTo: function(selector) {
			return this.each(function() {
				tool(selector).append(this);
			});
		}

	};

	tool.each = function(obj, callback) {
		var name,
			length = obj.length;

		if (length === undefined) {
			for (name in obj) {
				if (callback.call(obj[name], name) === false) {
					break;
				}
			}
		}
		else {
			for (var i = 0; i < length; i++) {
				if (callback.call(obj[i], i) === false) {
					break;
				}
			}
		}

		return tool(obj);
	};

	tool.type = function(obj) {
		var res = Object.prototype.toString.call(obj).match(regXDataType)[1].toLowerCase();
		return res;
	};

}).call(this);
<|endoftext|>


<commit_before>import Decimal from "big.js";

import {
    error
} from "./error";

import { seq, first, isSeq, empty } from "./seq";

import { isNode, isEmptyNode } from "./access";

import { isArray, get as aGet } from "./array";

import { isMap, get as mGet } from "./map";

import { transform, compose, forEach, filter, foldLeft, into, range } from "./transducers";

// TODO complete math (e.g. type checks for idiv and friends)

// one big pile
export const operatorMap = {
    "+": "plus",
    "-": "minus",
    "*": "times",
    "div": "dividedBy",
    "/": "dividedBy",
    "idiv": "dividedBy",
    "eq": "equals",
    "ne": "equals",
    "gt": "greaterThan",
    "lt": "lessThan",
    "ge": "greaterThanEquals",
    "le": "lessThanEquals",
    "&&": "and",
    "||": "or",
    "!": "not"
};

export const generalOperatorMap = {
    ">": "greaterThan",
    "<": "lessThan",
    ">=": "greaterThanEquals",
    "<=": "lessThanEquals",
    "=": "equals",
    "!=": "equals"
};

class UntypedAtomic extends String {
    constructor(a) {
        super(a);
        this._value = a;
    }
    cast(other) {
        //If the atomic value is an instance of xdt:untypedAtomic
        //and the other is an instance of a numeric type,
        //then the xdt:untypedAtomic value is cast to the type xs:double.

        //If the atomic value is an instance of xdt:untypedAtomic
        //and the other is an instance of xdt:untypedAtomic or xs:string,
        //then the xdt:untypedAtomic value is cast to the type xs:string.

        //If the atomic value is an instance of xdt:untypedAtomic
        //and the other is not an instance of xs:string, xdt:untypedAtomic, or any numeric type,
        //then the xdt:untypedAtomic value is cast to the dynamic type of the other value.

        // NO-OP, moved elsewhere
    }
    toString() {
        return this._value.toString();
    }
    valueOf() {
        return this._value.valueOf();
    }
}

class Integer extends Decimal {
    constructor(a) {
        super(a);
        this.constructor = Integer;
    }
}

class Float extends Number {
    constructor(a) {
        var temp = new Float32Array(1);
        temp[0] = +a;
        super(temp[0]);
        this._f = temp[0];
        this._d = a;
    }
    toString() {
        var temp = new Float64Array(1);
        temp[0] = +this._d;
        return temp[0].toString();
    }
    valueOf() {
        return this._f;
    }
}

const compProto = {
    equals(other) {
        return this.valueOf() === other.valueOf();
    },
    greaterThan(other) {
        return this.valueOf() > other.valueOf();
    },
    lessThan(other) {
        return this.valueOf() < other.valueOf();
    },
    greaterThanEquals(other) {
        return this.valueOf() >= other.valueOf();
    },
    lessThanEquals(other) {
        return this.valueOf() <= other.valueOf();
    }
};

const opProto = {
    plus(other) {
        return this + other;
    },
    minus(other) {
        return this - other;
    },
    times(other) {
        return this * other;
    },
    dividedBy(other) {
        return this / other;
    }
};

// mixin comparators
Object.assign(String.prototype, compProto);

Object.assign(Float.prototype, compProto, opProto);

Object.assign(Number.prototype, compProto, opProto);

Object.assign(Boolean.prototype, compProto);

Object.assign(Decimal.prototype, compProto);

// TODO decimal opt-in/out
const zeroInt = () => new Decimal(0);
const zero = () => Number(0);
const emptyString = () => String();

// TODO create from Type classes
export function decimal($a) {
    // type test
    if ($a === undefined) return ;
    return cast($a, Decimal, zeroInt);
}

export function integer($a) {
    if(isSeq($a)) return forEach($a, integer);
    return cast(Math.floor($a), Integer, zeroInt);
}

export function string($a) {
    // type test
    if($a === undefined) return emptyString();
    return isSeq($a) || isNode($a) ? data($a) : cast($a, String, emptyString);
}

export function number($a) {
    // type test
    return cast($a, Number, zero);
}

export function float($a) {
    // type test
    return cast($a, Float, zero);
}

export function double($a) {
    // type test
    return cast($a, Number, zero);
}

export function boolean($a) {
    // type test
    return _boolean($a);
}

export function cast($a, $b) {
    if(isSeq($a)) return op($a,_cast, $b);
    return _cast($a,$b);
}

function _convert(a, type) {
    if (a !== undefined && a.constructor !== type) {
        return _cast(a, type);
    }
    return a;
}

function _cast(a, b) {
    if (a.constructor !== b) a = new b(a.toString());
    return a;
}

export function to($a, $b) {
    let a = first($a);
    let b = first($b);
    a = a !== undefined ? +a.valueOf() : 1;
    b = b !== undefined ? +b.valueOf() : 0;
    return range(b + 1, a);
}

export function indexOf($a, $b) {
    $a = first($a);
    $b = first($b);
    return $a.findKeys(function(i) {
        return _boolean($b.op("equals", i));
    });
}

export function call(...a) {
    let f = first(a[0]);
    if (isArray(f)) {
        return aGet(f,first(a[1]));
    } else if (isMap(f)) {
        return mGet(f,first(a[1]));
    } else {
        return f.apply(this, a.slice(1));
    }
}

function numbertest(a) {
    var c = a.constructor;
    if (c == String || c == Boolean) return;
    return true;
}

function _op(op, invert, a, b) {
    var ret;
    if (a !== undefined) {
        if (typeof a[op] == "function") {
            if (!numbertest(a)) return error("err:XPTY0004", a.constructor.name + "(" + a + ") can not be operand for " + op);
            if (!numbertest(b)) return error("err:XPTY0004", b.constructor.name + "(" + b + ") can not be operand for " + op);
            var ab = _promote(a, b);
            if (ab instanceof Error) {
                return ab;
            }
            a = ab[0];
            b = ab[1];
            ret = a[op](b);
        } else {
            throw new Error("Operator " + op + " not implemented");
        }
    }
    return invert ? !ret : ret;
}

function _comp(op, invert, a, b) {
    var ret;
    if (a !== undefined) {
        if (typeof a[op] == "function") {
            var ab = _promote(a, b);
            if (ab instanceof Error) {
                return ab;
            }
            a = ab[0];
            b = ab[1];
            ret = a[op](b);
        } else {
            throw new Error("Operator " + op + " not implemented for " + a + " (" + (a.constructor.name) + ")");
        }
    }
    //console.log(a,b,op,ret);

    return invert ? !ret : ret;
}

function _promote(a, b) {
    // TODO FIXME use JS type casting! 1 == "1"
    //If each operand is an instance of one of the types xs:string or xs:anyURI, then both operands are cast to type xs:string.
    //If each operand is an instance of one of the types xs:decimal or xs:float, then both operands are cast to type xs:float.
    //If each operand is an instance of one of the types xs:decimal, xs:float, or xs:double, then both operands are cast to type xs:double.
    var c = a.constructor,
        d = b.constructor;
    if (c == Number || d == Number) {
        if (c == Integer || c == Decimal || c == Float || c == UntypedAtomic) {
            a = +a.toString();
            c = Number;
        }
        if (d == Integer || d == Decimal || d == Float || d == UntypedAtomic) {
            b = +b.toString();
            d = Number;
        }
    }
    if (c == Integer || d == Integer) {
        if (c == Decimal || c == UntypedAtomic) {
            a = c == UntypedAtomic ? new Integer(a.toString()) : a;
            c = Integer;
        }
        if (d == Decimal || d == UntypedAtomic) {
            b = d == UntypedAtomic ? new Integer(b.toString()) : b;
            d = Integer;
        }
    }
    if (c == String || d == String) {
        if (c == UntypedAtomic) {
            a = a.toString();
            c = String;
        }
        if (d == UntypedAtomic) {
            b = a.toString();
            d = String;
        }
    }
    if (c != d) {
        //throw new Error("Cannot compare operands: " + c.name + " and " + d.name);
        return error("err:XPTY0004", "Cannot compare operands: " + c.name + " and " + d.name);
    }
    return [a, b];
}

function _opReducer(iterable, opfn, other, general) {
    var otherIsSeq = isSeq(other);
    if (general) {
        /*if(!isSeq(iterable)) {
            var v = iterable;
            return (otherIsSeq ? foldLeft(other, false, function (pre, cur) {
                return pre || opfn(v, cur);
            }) : opfn(v, other));
        } else {*/
            return foldLeft(iterable,false,function(acc, v) {
                return acc || (otherIsSeq ? foldLeft(other,false,function(pre, cur) {
                    return pre || opfn(v, cur);
                }) : opfn(v, other));
            });
        //}
    } else if (!isSeq(iterable) || iterable.size == 1) {
        let b = otherIsSeq ? first(other) : other;
        return opfn(first(iterable), b);
    } else {
        return forEach(iterable,function(v) {
            return otherIsSeq ? foldLeft(other,false,function(pre, cur) {
                return pre || opfn(v, cur);
            }) : opfn(v, other);
        });
    }
}

// TODO without eval!
function isNodeSeq($a) {
    return node(first($a));
}

// FIXME the unmarshalling of seqs is probably more efficient than anything else...
// EXCEPT a filter + a lazy foldRight maybe
export function _boolean($a) {
    if(isSeq($a)){
        var s = $a.size;
        if(!s) return false;
        var a = first($a);
        var _isNode = isNode(a);
        if (s > 1 && !_isNode) {
            return error("err:FORG0006");
        }
        return _isNode ? true : !!a.valueOf();
    }
    return !!$a.valueOf();
}

export function and($a, $b) {
    return _boolean($a) && _boolean($b);
}

export function or($a, $b) {
    return _boolean($a) || _boolean($b);
}

export function not($a) {
    return !first($a);
}

const logic = {
    and: and,
    or: or,
    not: not
};

const opinv = {
    ne: true,
    '!=': true
};
export function op($a, operator, $b) {
    var invert = false,
        comp = false,
        general = false,
        hasOp = false,
        operatorName;
    var opfn;
    if (typeof operator == "string") {
        invert = opinv[operator];
        hasOp = operator in operatorMap;
        if(!hasOp){
            general = operator in generalOperatorMap;
            if(!general) return error("xxx", "No such operator");
            operatorName = generalOperatorMap[operator];
        } else {
            operatorName = operatorMap[operator];
        }
        if (logic[operatorName]) {
            return logic[operatorName]($a, $b);
        } else {
            comp = compProto.hasOwnProperty(operatorName);
            opfn = comp ? _comp.bind(null, operatorName, invert) : _op.bind(null, operatorName, invert);
        }
        if (comp) {
            $a = data($a);
            $b = data($b);
        }
        if (!general) {
            if (empty($a)) return $a;
            if (empty($b)) return $b;
            // FIXME NOT! allow arithmetic on sequences (why not?)...
            // FIXME reduce when comp result is seq of booleans
            if ($b.size > 1) return error("err:XPTY0004");
        }
    } else if (typeof operator == "function") {
        opfn = operator;
    } else {
        return error("xxx", "No such operator");
    }
    return _opReducer($a, opfn, $b, general);
}

export function data($a) {
    return dataImpl($a);
}

function dataImpl(node, fltr = false) {
    var ret;
    if (isSeq(node)) {
        if (empty(node)) return node;
        //ret = node.map(_ => dataImpl(_, fltr)).filter(_ => _ !== undefined);
        var a = into(node,compose(forEach(_ => dataImpl(_, fltr)),filter(_ => undefined !== _)),seq());
        if (!a.size) {
            ret = new UntypedAtomic("");
        } else {
            ret = a;
        }
        return ret;
    }
    if(isEmptyNode(node)) return undefined;
    if (!isNode(node)) return node;
    var type = node.type;
    if (fltr && fltr === type) return undefined;
    if (type === 1) {
        ret = into(node,compose(forEach(_ => dataImpl(_, fltr)),filter(_ => undefined !== _)),seq());
    } else {
        ret = node.value;
        if (typeof ret == "string") {
            ret = !ret ? undefined : _cast(ret, UntypedAtomic);
        }
    }
    return isSeq(ret) && !ret.size ? new UntypedAtomic("") : ret;
}

export function instanceOf($a, $b) {
    let a = first($a);
    let b = first($b);
    var t = a === undefined || b === undefined ? false : a.constructor === b.constructor;
    return t;
}

export function minus($a) {
    var a = first($a);
    if (typeof a.neg == "function") return a.neg();
    return -a;
}

export function round($a) {
    let a = first($a);
    if(!a) return integer(0);
	return integer(typeof a.round == "function" ? a.round() : Math.round(a));
}

export function floor($a) {
    let a = first($a);
    if (!a) return integer(0);
    return integer(typeof a.floor == "function" ? a.floor() : Math.floor(a));
}
<commit_msg>moved to big.js compat<commit_after>import Decimal from "big.js";

import {
    error
} from "./error";

import { seq, first, isSeq, empty } from "./seq";

import { isNode, isEmptyNode } from "./access";

import { isArray, get as aGet } from "./array";

import { isMap, get as mGet } from "./map";

import { transform, compose, forEach, filter, foldLeft, into, range } from "./transducers";

// TODO complete math (e.g. type checks for idiv and friends)

// one big pile
export const operatorMap = {
    "+": "plus",
    "-": "minus",
    "*": "times",
    "div": "div",
    "/": "div",
    "idiv": "div",
    "eq": "eq",
    "ne": "eq",
    "gt": "gt",
    "lt": "lt",
    "ge": "gte",
    "le": "gte",
    "&&": "and",
    "||": "or",
    "!": "not"
};

export const generalOperatorMap = {
    ">": "gt",
    "<": "lt",
    ">=": "gte",
    "<=": "lte",
    "=": "eq",
    "!=": "eq"
};

class UntypedAtomic extends String {
    constructor(a) {
        super(a);
        this._value = a;
    }
    cast(other) {
        //If the atomic value is an instance of xdt:untypedAtomic
        //and the other is an instance of a numeric type,
        //then the xdt:untypedAtomic value is cast to the type xs:double.

        //If the atomic value is an instance of xdt:untypedAtomic
        //and the other is an instance of xdt:untypedAtomic or xs:string,
        //then the xdt:untypedAtomic value is cast to the type xs:string.

        //If the atomic value is an instance of xdt:untypedAtomic
        //and the other is not an instance of xs:string, xdt:untypedAtomic, or any numeric type,
        //then the xdt:untypedAtomic value is cast to the dynamic type of the other value.

        // NO-OP, moved elsewhere
    }
    toString() {
        return this._value.toString();
    }
    valueOf() {
        return this._value.valueOf();
    }
}

class Integer extends Decimal {
    constructor(a) {
        super(a);
        this.constructor = Integer;
    }
}

class Float extends Number {
    constructor(a) {
        var temp = new Float32Array(1);
        temp[0] = +a;
        super(temp[0]);
        this._f = temp[0];
        this._d = a;
    }
    toString() {
        var temp = new Float64Array(1);
        temp[0] = +this._d;
        return temp[0].toString();
    }
    valueOf() {
        return this._f;
    }
}

const compProto = {
    eq(other) {
        return this.valueOf() === other.valueOf();
    },
    gt(other) {
        return this.valueOf() > other.valueOf();
    },
    lt(other) {
        return this.valueOf() < other.valueOf();
    },
    gte(other) {
        return this.valueOf() >= other.valueOf();
    },
    lte(other) {
        return this.valueOf() <= other.valueOf();
    }
};

const opProto = {
    plus(other) {
        return this + other;
    },
    minus(other) {
        return this - other;
    },
    times(other) {
        return this * other;
    },
    div(other) {
        return this / other;
    }
};

// mixin comparators
Object.assign(String.prototype, compProto);

Object.assign(Float.prototype, compProto, opProto);

Object.assign(Number.prototype, compProto, opProto);

Object.assign(Boolean.prototype, compProto);

// TODO decimal opt-in/out
const zeroInt = () => new Decimal(0);
const zero = () => Number(0);
const emptyString = () => String();

// TODO create from Type classes
export function decimal($a) {
    // type test
    if ($a === undefined) return ;
    return cast($a, Decimal, zeroInt);
}

export function integer($a) {
    if(isSeq($a)) return forEach($a, integer);
    return cast(Math.floor($a), Integer, zeroInt);
}

export function string($a) {
    // type test
    if($a === undefined) return emptyString();
    return isSeq($a) || isNode($a) ? data($a) : cast($a, String, emptyString);
}

export function number($a) {
    // type test
    return cast($a, Number, zero);
}

export function float($a) {
    // type test
    return cast($a, Float, zero);
}

export function double($a) {
    // type test
    return cast($a, Number, zero);
}

export function boolean($a) {
    // type test
    return _boolean($a);
}

export function cast($a, $b) {
    if(isSeq($a)) return op($a,_cast, $b);
    return _cast($a,$b);
}

function _convert(a, type) {
    if (a !== undefined && a.constructor !== type) {
        return _cast(a, type);
    }
    return a;
}

function _cast(a, b) {
    if (a.constructor !== b) a = new b(a.toString());
    return a;
}

export function to($a, $b) {
    let a = first($a);
    let b = first($b);
    a = a !== undefined ? +a.valueOf() : 1;
    b = b !== undefined ? +b.valueOf() : 0;
    return range(b + 1, a);
}

export function indexOf($a, $b) {
    $a = first($a);
    $b = first($b);
    return $a.findKeys(function(i) {
        return _boolean($b.op("equals", i));
    });
}

export function call(...a) {
    let f = first(a[0]);
    if (isArray(f)) {
        return aGet(f,first(a[1]));
    } else if (isMap(f)) {
        return mGet(f,first(a[1]));
    } else {
        return f.apply(this, a.slice(1));
    }
}

function numbertest(a) {
    var c = a.constructor;
    if (c == String || c == Boolean) return;
    return true;
}

function _op(op, invert, a, b) {
    var ret;
    if (a !== undefined) {
        if (typeof a[op] == "function") {
            if (!numbertest(a)) return error("err:XPTY0004", a.constructor.name + "(" + a + ") can not be operand for " + op);
            if (!numbertest(b)) return error("err:XPTY0004", b.constructor.name + "(" + b + ") can not be operand for " + op);
            var ab = _promote(a, b);
            if (ab instanceof Error) {
                return ab;
            }
            a = ab[0];
            b = ab[1];
            ret = a[op](b);
        } else {
            throw new Error("Operator " + op + " not implemented");
        }
    }
    return invert ? !ret : ret;
}

function _comp(op, invert, a, b) {
    var ret;
    if (a !== undefined) {
        if (typeof a[op] == "function") {
            var ab = _promote(a, b);
            if (ab instanceof Error) {
                return ab;
            }
            a = ab[0];
            b = ab[1];
            ret = a[op](b);
        } else {
            throw new Error("Operator " + op + " not implemented for " + a + " (" + (a.constructor.name) + ")");
        }
    }
    //console.log(a,b,op,ret);

    return invert ? !ret : ret;
}

function _promote(a, b) {
    // TODO FIXME use JS type casting! 1 == "1"
    //If each operand is an instance of one of the types xs:string or xs:anyURI, then both operands are cast to type xs:string.
    //If each operand is an instance of one of the types xs:decimal or xs:float, then both operands are cast to type xs:float.
    //If each operand is an instance of one of the types xs:decimal, xs:float, or xs:double, then both operands are cast to type xs:double.
    var c = a.constructor,
        d = b.constructor;
    if (c == Number || d == Number) {
        if (c == Integer || c == Decimal || c == Float || c == UntypedAtomic) {
            a = +a.toString();
            c = Number;
        }
        if (d == Integer || d == Decimal || d == Float || d == UntypedAtomic) {
            b = +b.toString();
            d = Number;
        }
    }
    if (c == Integer || d == Integer) {
        if (c == Decimal || c == UntypedAtomic) {
            a = c == UntypedAtomic ? new Integer(a.toString()) : a;
            c = Integer;
        }
        if (d == Decimal || d == UntypedAtomic) {
            b = d == UntypedAtomic ? new Integer(b.toString()) : b;
            d = Integer;
        }
    }
    if (c == String || d == String) {
        if (c == UntypedAtomic) {
            a = a.toString();
            c = String;
        }
        if (d == UntypedAtomic) {
            b = a.toString();
            d = String;
        }
    }
    if (c != d) {
        //throw new Error("Cannot compare operands: " + c.name + " and " + d.name);
        return error("err:XPTY0004", "Cannot compare operands: " + c.name + " and " + d.name);
    }
    return [a, b];
}

function _opReducer(iterable, opfn, other, general) {
    var otherIsSeq = isSeq(other);
    if (general) {
        /*if(!isSeq(iterable)) {
            var v = iterable;
            return (otherIsSeq ? foldLeft(other, false, function (pre, cur) {
                return pre || opfn(v, cur);
            }) : opfn(v, other));
        } else {*/
            return foldLeft(iterable,false,function(acc, v) {
                return acc || (otherIsSeq ? foldLeft(other,false,function(pre, cur) {
                    return pre || opfn(v, cur);
                }) : opfn(v, other));
            });
        //}
    } else if (!isSeq(iterable) || iterable.size == 1) {
        let b = otherIsSeq ? first(other) : other;
        return opfn(first(iterable), b);
    } else {
        return forEach(iterable,function(v) {
            return otherIsSeq ? foldLeft(other,false,function(pre, cur) {
                return pre || opfn(v, cur);
            }) : opfn(v, other);
        });
    }
}

// TODO without eval!
function isNodeSeq($a) {
    return node(first($a));
}

// FIXME the unmarshalling of seqs is probably more efficient than anything else...
// EXCEPT a filter + a lazy foldRight maybe
export function _boolean($a) {
    if(isSeq($a)){
        var s = $a.size;
        if(!s) return false;
        var a = first($a);
        var _isNode = isNode(a);
        if (s > 1 && !_isNode) {
            return error("err:FORG0006");
        }
        return _isNode ? true : !!a.valueOf();
    }
    return !!$a.valueOf();
}

export function and($a, $b) {
    return _boolean($a) && _boolean($b);
}

export function or($a, $b) {
    return _boolean($a) || _boolean($b);
}

export function not($a) {
    return !first($a);
}

const logic = {
    and: and,
    or: or,
    not: not
};

const opinv = {
    ne: true,
    '!=': true
};
export function op($a, operator, $b) {
    var invert = false,
        comp = false,
        general = false,
        hasOp = false,
        operatorName;
    var opfn;
    if (typeof operator == "string") {
        invert = opinv[operator];
        hasOp = operator in operatorMap;
        if(!hasOp){
            general = operator in generalOperatorMap;
            if(!general) return error("xxx", "No such operator");
            operatorName = generalOperatorMap[operator];
        } else {
            operatorName = operatorMap[operator];
        }
        if (logic[operatorName]) {
            return logic[operatorName]($a, $b);
        } else {
            comp = compProto.hasOwnProperty(operatorName);
            opfn = comp ? _comp.bind(null, operatorName, invert) : _op.bind(null, operatorName, invert);
        }
        if (comp) {
            $a = data($a);
            $b = data($b);
        }
        if (!general) {
            if (empty($a)) return $a;
            if (empty($b)) return $b;
            // FIXME NOT! allow arithmetic on sequences (why not?)...
            // FIXME reduce when comp result is seq of booleans
            if ($b.size > 1) return error("err:XPTY0004");
        }
    } else if (typeof operator == "function") {
        opfn = operator;
    } else {
        return error("xxx", "No such operator");
    }
    return _opReducer($a, opfn, $b, general);
}

export function data($a) {
    return dataImpl($a);
}

function dataImpl(node, fltr = false) {
    var ret;
    if (isSeq(node)) {
        if (empty(node)) return node;
        //ret = node.map(_ => dataImpl(_, fltr)).filter(_ => _ !== undefined);
        var a = into(node,compose(forEach(_ => dataImpl(_, fltr)),filter(_ => undefined !== _)),seq());
        if (!a.size) {
            ret = new UntypedAtomic("");
        } else {
            ret = a;
        }
        return ret;
    }
    if(isEmptyNode(node)) return undefined;
    if (!isNode(node)) return node;
    var type = node.type;
    if (fltr && fltr === type) return undefined;
    if (type === 1) {
        ret = into(node,compose(forEach(_ => dataImpl(_, fltr)),filter(_ => undefined !== _)),seq());
    } else {
        ret = node.value;
        if (typeof ret == "string") {
            ret = !ret ? undefined : _cast(ret, UntypedAtomic);
        }
    }
    return isSeq(ret) && !ret.size ? new UntypedAtomic("") : ret;
}

export function instanceOf($a, $b) {
    let a = first($a);
    let b = first($b);
    var t = a === undefined || b === undefined ? false : a.constructor === b.constructor;
    return t;
}

export function minus($a) {
    var a = first($a);
    if (typeof a.neg == "function") return a.neg();
    return -a;
}

export function round($a) {
    let a = first($a);
    if(!a) return integer(0);
	return integer(typeof a.round == "function" ? a.round() : Math.round(a));
}

export function floor($a) {
    let a = first($a);
    if (!a) return integer(0);
    return integer(typeof a.floor == "function" ? a.floor() : Math.floor(a));
}
<|endoftext|>


<commit_before>function replaceTemplateUrl(lines) {
    const regEx = /(^\s*templateUrl:\s*)['"](.*)['"](,*)$/;
    const lineNumbers = lines.reduce((result, line, i) => (/templateUrl/.test(line) ? result.concat(i) : result), []);

    if (!lineNumbers.length) {
        return lines;
    }

    const templateRequires = lineNumbers.map((lineNumber, i) => {
        const [, , templateUrl] = regEx.exec(lines[lineNumber]);
        const lineReplacement = lines[lineNumber].replace(regEx, `$1template${i + 1}$3`);

        return {
            templateUrl,
            lineNumber,
            lineReplacement
        };
    });

    const updatedLines = lines;

    templateRequires.forEach((x) => {
        updatedLines[x.lineNumber] = x.lineReplacement;
    });

    return [].concat(
        templateRequires.map((x, i) => `const template${i + 1} = require('${x.templateUrl}');`),
        ``,
        updatedLines
    );
}

module.exports = {
    replaceTemplateUrl
};
<commit_msg>Returns an array instead of array.concat<commit_after>function replaceTemplateUrl(lines) {
    const regEx = /(^\s*templateUrl:\s*)['"](.*)['"](,*)$/;
    const lineNumbers = lines.reduce((result, line, i) => (/templateUrl/.test(line) ? result.concat(i) : result), []);

    if (!lineNumbers.length) {
        return lines;
    }

    const templateRequires = lineNumbers.map((lineNumber, i) => {
        const [, , templateUrl] = regEx.exec(lines[lineNumber]);
        const lineReplacement = lines[lineNumber].replace(regEx, `$1template${i + 1}$3`);

        return {
            templateUrl,
            lineNumber,
            lineReplacement
        };
    });

    const updatedLines = lines;

    templateRequires.forEach((x) => {
        updatedLines[x.lineNumber] = x.lineReplacement;
    });

    return [
        ...templateRequires.map((x, i) => `const template${i + 1} = require('${x.templateUrl}');`),
        ``,
        ...updatedLines
    ];
}

module.exports = {
    replaceTemplateUrl
};
<|endoftext|>


<commit_before>/*
 * Copyright 2015 Google Inc. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
var Util = window.Util || {};

Util.MIN_TIMESTEP = 0.001;
Util.MAX_TIMESTEP = 1;

Util.clamp = function(value, min, max) {
  return Math.min(Math.max(min, value), max);
};

Util.isIOS = function() {
  return /iPad|iPhone|iPod/.test(navigator.platform);
};

Util.isFirefoxAndroid = function() {
  return /firefox/i.test(navigator.userAgent) && /android/i.test(navigator.userAgent);
};

// Helper method to validate the time steps of sensor timestamps.
Util.isTimestampDeltaValid = function(timestampDeltaS) {
  if (isNaN(timestampDeltaS)) {
    return false;
  }
  if (timestampDeltaS <= Util.MIN_TIMESTEP) {
    return false;
  }
  if (timestampDeltaS > Util.MAX_TIMESTEP) {
    return false;
  }
  return true;
};

module.exports = Util;
<commit_msg>lower MIN_TIMESTEP to 0.0001<commit_after>/*
 * Copyright 2015 Google Inc. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
var Util = window.Util || {};

Util.MIN_TIMESTEP = 0.0001;
Util.MAX_TIMESTEP = 1;

Util.clamp = function(value, min, max) {
  return Math.min(Math.max(min, value), max);
};

Util.isIOS = function() {
  return /iPad|iPhone|iPod/.test(navigator.platform);
};

Util.isFirefoxAndroid = function() {
  return /firefox/i.test(navigator.userAgent) && /android/i.test(navigator.userAgent);
};

// Helper method to validate the time steps of sensor timestamps.
Util.isTimestampDeltaValid = function(timestampDeltaS) {
  if (isNaN(timestampDeltaS)) {
    return false;
  }
  if (timestampDeltaS <= Util.MIN_TIMESTEP) {
    return false;
  }
  if (timestampDeltaS > Util.MAX_TIMESTEP) {
    return false;
  }
  return true;
};

module.exports = Util;
<|endoftext|>


<commit_before>const { parse: parseURL } = require('url');

exports.parseURL = (url) => {
    const parsed = parseURL(url, true);
    switch (parsed.hostname) {
        case 'www.youtube.com':
        case 'youtube.com':
        case 'm.youtube.com': {
            const idRegex = /^[a-zA-Z0-9-_]+$/;
            if (parsed.pathname === '/watch') {
                if (!idRegex.test(parsed.query.v)) return null;
                return {
                    type: 'video',
                    id: parsed.query.v
                };
            } else if (parsed.pathname === '/playlist') {
                if(!idRegex.test(parsed.query.list)) return null;
                return {
                    type: 'playlist',
                    id: parsed.query.list
                };
            } else if (parsed.pathname.startsWith('/channel/')) {
                const id = parsed.pathname.replace('/channel/', '');
                if (!idRegex.test(id)) return null;
                return {
                    type: 'channel',
                    id
                };
            }

            return null;
        }
        case 'youtu.be':
            return /\/^[a-zA-Z0-9-_]+$/.test(parsed.pathname) ? { type: 'video', id: parsed.pathname.slice(1) } : null;
        default:
            return null;
    }
};
<commit_msg>document parseURL, rename imported url parser var<commit_after>const { parse } = require('url');

/**
 * Parse a string as a potential YouTube resource URL.
 * @param {string} url
 * @returns {?{type: string, id: string}}
 */
exports.parseURL = (url) => {
    const parsed = parse(url, true);
    switch (parsed.hostname) {
        case 'www.youtube.com':
        case 'youtube.com':
        case 'm.youtube.com': {
            const idRegex = /^[a-zA-Z0-9-_]+$/;
            if (parsed.pathname === '/watch') {
                if (!idRegex.test(parsed.query.v)) return null;
                return {
                    type: 'video',
                    id: parsed.query.v
                };
            } else if (parsed.pathname === '/playlist') {
                if(!idRegex.test(parsed.query.list)) return null;
                return {
                    type: 'playlist',
                    id: parsed.query.list
                };
            } else if (parsed.pathname.startsWith('/channel/')) {
                const id = parsed.pathname.replace('/channel/', '');
                if (!idRegex.test(id)) return null;
                return {
                    type: 'channel',
                    id
                };
            }

            return null;
        }
        case 'youtu.be':
            return /\/^[a-zA-Z0-9-_]+$/.test(parsed.pathname) ? { type: 'video', id: parsed.pathname.slice(1) } : null;
        default:
            return null;
    }
};
<|endoftext|>


<commit_before>'use strict'
var iterator = exports.iterator = typeof Symbol === 'function' && Symbol.iterator || undefined

exports.INTERNAL = function () {}

// Returns an array or throws. The returned object may or may not be a safe
// copy. The only safe operations are to synchronously loop through the object.
// After control is given back to the caller, the object must not be used.
// The returned array COULD be a subclass of Array.
exports.asArray = function (iterable) {
	if (Array.isArray(iterable)) {
		return iterable
	}
	if (iterator && iterable != null && typeof iterable[iterator] === 'function') {
		var arr = []
		var it = iterable[iterator]()
		var item
		while (!(item = it.next()).done) {
			arr.push(item.value)
		}
		return arr
	}
	throw new TypeError('Expected value to be an iterable object.')
}

// Returns whether the given catch predicate should catch the exception reason.
exports.catchesError = function (predicate, reason) {
	if (predicate === Error || (predicate && predicate.prototype instanceof Error)) {
		return reason instanceof predicate
	}
	if (typeof predicate === 'function') {
		return !!predicate(reason)
	}
	if (predicate && typeof predicate === 'object') {
		var keys = Object.keys(predicate)
		for (var i=0, len=keys.length; i<len; i++) {
			var key = keys[i]
			if (reason[key] != predicate[key]) {
				return false
			}
		}
		if (len > 0) {
			return true
		}
	}
	warn('The predicate passed to .catch() is invalid, and will be ignored.', arguments[2]._trace) // @[/development]
	return false
}

// @[browser]
// A safe, cross-browser log function.
exports.console = {
	log: function () {
		if (typeof console === 'object' && console) {
			Function.prototype.apply.call(console.log, console, arguments)
		}
	},
	// @[development]
	warn: function () {
		if (typeof console === 'object' && console) {
			Function.prototype.apply.call(console.warn, console, arguments)
		}
	},
	// @[/]
	error: function () {
		if (typeof console === 'object' && console) {
			Function.prototype.apply.call(console.error, console, arguments)
		}
	}
}
// @[/]

// @[development]
// This must be at the bottom of the page so that warn.js doesn't load an
// uninitialized util.js.
var warn = require('./warn')
// @[/]
<commit_msg>updated comment<commit_after>'use strict'
var iterator = exports.iterator = typeof Symbol === 'function' && Symbol.iterator || undefined

exports.INTERNAL = function () {}

// Returns an array or throws. The returned object may or may not be a safe
// copy. The only safe operations are to synchronously loop through the object.
// After control is given back to the caller, the object must not be used.
// The returned array COULD be a subclass of Array.
exports.asArray = function (iterable) {
	if (Array.isArray(iterable)) {
		return iterable
	}
	if (iterator && iterable != null && typeof iterable[iterator] === 'function') {
		var arr = []
		var it = iterable[iterator]()
		var item
		while (!(item = it.next()).done) {
			arr.push(item.value)
		}
		return arr
	}
	throw new TypeError('Expected value to be an iterable object.')
}

// Returns whether the given catch predicate should catch the exception reason.
exports.catchesError = function (predicate, reason) {
	if (predicate === Error || (predicate && predicate.prototype instanceof Error)) {
		return reason instanceof predicate
	}
	if (typeof predicate === 'function') {
		return !!predicate(reason)
	}
	if (predicate && typeof predicate === 'object') {
		var keys = Object.keys(predicate)
		for (var i=0, len=keys.length; i<len; i++) {
			var key = keys[i]
			if (reason[key] != predicate[key]) {
				return false
			}
		}
		if (len > 0) {
			return true
		}
	}
	warn('The predicate passed to .catch() is invalid, and will be ignored.', arguments[2]._trace) // @[/development]
	return false
}

// @[browser]
// Safe, cross-browser log functions.
exports.console = {
	log: function () {
		if (typeof console === 'object' && console) {
			Function.prototype.apply.call(console.log, console, arguments)
		}
	},
	// @[development]
	warn: function () {
		if (typeof console === 'object' && console) {
			Function.prototype.apply.call(console.warn, console, arguments)
		}
	},
	// @[/]
	error: function () {
		if (typeof console === 'object' && console) {
			Function.prototype.apply.call(console.error, console, arguments)
		}
	}
}
// @[/]

// @[development]
// This must be at the bottom of the page so that warn.js doesn't load an
// uninitialized util.js.
var warn = require('./warn')
// @[/]
<|endoftext|>


<commit_before>import assign from 'assign-deep'

const inBrowser = typeof window !== 'undefined' && window !== null

export const hasIntersectionObserver = checkIntersectionObserver()

function checkIntersectionObserver () {
  if (inBrowser &&
    'IntersectionObserver' in window &&
    'IntersectionObserverEntry' in window &&
    'intersectionRatio' in window.IntersectionObserverEntry.prototype) {
  // Minimal polyfill for Edge 15's lack of `isIntersecting`
  // See: https://github.com/w3c/IntersectionObserver/issues/211
    if (!('isIntersecting' in window.IntersectionObserverEntry.prototype)) {
      Object.defineProperty(window.IntersectionObserverEntry.prototype,
        'isIntersecting', {
          get: function () {
            return this.intersectionRatio > 0
          }
        })
    }
    return true
  }
  return false
}

export const modeType = {
  event: 'event',
  observer: 'observer'
}

// CustomEvent polyfill for IE
const CustomEvent = (function () {
  if (!inBrowser) return
  // not IE
  if (typeof window.CustomEvent === 'function') return window.CustomEvent
  function CustomEvent (event, params) {
    params = params || { bubbles: false, cancelable: false, detail: undefined }
    var evt = document.createEvent('CustomEvent')
    evt.initCustomEvent(event, params.bubbles, params.cancelable, params.detail)
    return evt
  }
  CustomEvent.prototype = window.Event.prototype
  return CustomEvent
})()

function remove (arr, item) {
  if (!arr.length) return
  const index = arr.indexOf(item)
  if (index > -1) return arr.splice(index, 1)
}

function some (arr, fn) {
  let has = false
  for (let i = 0, len = arr.length; i < len; i++) {
    if (fn(arr[i])) {
      has = true
      break
    }
  }
  return has
}

function getBestSelectionFromSrcset (el, scale) {
  if (el.tagName !== 'IMG' || !el.getAttribute('data-srcset')) return

  let options = el.getAttribute('data-srcset')
  const result = []
  const container = el.parentNode
  const containerWidth = container.offsetWidth * scale

  let spaceIndex
  let tmpSrc
  let tmpWidth

  options = options.trim().split(',')

  options.map(item => {
    item = item.trim()
    spaceIndex = item.lastIndexOf(' ')
    if (spaceIndex === -1) {
      tmpSrc = item
      tmpWidth = 999998
    } else {
      tmpSrc = item.substr(0, spaceIndex)
      tmpWidth = parseInt(item.substr(spaceIndex + 1, item.length - spaceIndex - 2), 10)
    }
    result.push([tmpWidth, tmpSrc])
  })

  result.sort(function (a, b) {
    if (a[0] < b[0]) {
      return 1
    }
    if (a[0] > b[0]) {
      return -1
    }
    if (a[0] === b[0]) {
      if (b[1].indexOf('.webp', b[1].length - 5) !== -1) {
        return 1
      }
      if (a[1].indexOf('.webp', a[1].length - 5) !== -1) {
        return -1
      }
    }
    return 0
  })
  let bestSelectedSrc = ''
  let tmpOption

  for (let i = 0; i < result.length; i++) {
    tmpOption = result[i]
    bestSelectedSrc = tmpOption[1]
    const next = result[i + 1]
    if (next && next[0] < containerWidth) {
      bestSelectedSrc = tmpOption[1]
      break
    } else if (!next) {
      bestSelectedSrc = tmpOption[1]
      break
    }
  }

  return bestSelectedSrc
}

function find (arr, fn) {
  let item
  for (let i = 0, len = arr.length; i < len; i++) {
    if (fn(arr[i])) {
      item = arr[i]
      break
    }
  }
  return item
}

const getDPR = (scale = 1) => inBrowser ? (window.devicePixelRatio || scale) : scale

function supportWebp () {
  if (!inBrowser) return false

  let support = true
  const d = document

  try {
    const elem = document.createElement('canvas');

    if (!!(elem.getContext && elem.getContext('2d'))) {
      support = elem.toDataURL('image/webp').indexOf('data:image/webp') === 0;
    }
  } catch (err) {
    support = false
  }

  return support
}

function throttle (action, delay) {
  let timeout = null
  let lastRun = 0
  return function () {
    if (timeout) {
      return
    }
    let elapsed = Date.now() - lastRun
    let context = this
    let args = arguments
    let runCallback = function () {
      lastRun = Date.now()
      timeout = false
      action.apply(context, args)
    }
    if (elapsed >= delay) {
      runCallback()
    } else {
      timeout = setTimeout(runCallback, delay)
    }
  }
}

function testSupportsPassive () {
  if (!inBrowser) return
  let support = false
  try {
    let opts = Object.defineProperty({}, 'passive', {
      get: function () {
        support = true
      }
    })
    window.addEventListener('test', null, opts)
  } catch (e) {}
  return support
}

const supportsPassive = testSupportsPassive()

const _ = {
  on (el, type, func, capture = false) {
    if (supportsPassive) {
      el.addEventListener(type, func, {
        capture: capture,
        passive: true
      })
    } else {
      el.addEventListener(type, func, capture)
    }
  },
  off (el, type, func, capture = false) {
    el.removeEventListener(type, func, capture)
  }
}

const loadImageAsync = (item, resolve, reject) => {
  let image = new Image()
  if (!item || !item.src) {
    const err = new Error('image src is required')
    return reject(err)
  }

  image.src = item.src
  if (item.cors) {
    image.crossOrigin = item.cors
  }

  image.onload = function () {
    resolve({
      naturalHeight: image.naturalHeight,
      naturalWidth: image.naturalWidth,
      src: image.src
    })
  }

  image.onerror = function (e) {
    reject(e)
  }
}

const style = (el, prop) => {
  return typeof getComputedStyle !== 'undefined'
    ? getComputedStyle(el, null).getPropertyValue(prop)
    : el.style[prop]
}

const overflow = (el) => {
  return style(el, 'overflow') + style(el, 'overflow-y') + style(el, 'overflow-x')
}

const scrollParent = (el) => {
  if (!inBrowser) return
  if (!(el instanceof HTMLElement)) {
    return window
  }

  let parent = el

  while (parent) {
    if (parent === document.body || parent === document.documentElement) {
      break
    }

    if (!parent.parentNode) {
      break
    }

    if (/(scroll|auto)/.test(overflow(parent))) {
      return parent
    }

    parent = parent.parentNode
  }

  return window
}

function isObject (obj) {
  return obj !== null && typeof obj === 'object'
}

function ObjectKeys (obj) {
  if (!(obj instanceof Object)) return []
  if (Object.keys) {
    return Object.keys(obj)
  } else {
    let keys = []
    for (let key in obj) {
      if (obj.hasOwnProperty(key)) {
        keys.push(key)
      }
    }
    return keys
  }
}

function ArrayFrom (arrLike) {
  let len = arrLike.length
  const list = []
  for (let i = 0; i < len; i++) {
    list.push(arrLike[i])
  }
  return list
}

function noop () {}

class ImageCache {
  constructor ({ max }) {
    this.options = {
      max: max || 100
    }
    this._caches = []
  }

  has (key) {
    return this._caches.indexOf(key) > -1
  }

  add (key) {
    if (this.has(key)) return
    this._caches.push(key)
    if (this._caches.length > this.options.max) {
      this.free()
    }
  }

  free () {
    this._caches.shift()
  }
}

export {
  ImageCache,
  inBrowser,
  CustomEvent,
  remove,
  some,
  find,
  assign,
  noop,
  ArrayFrom,
  _,
  isObject,
  throttle,
  supportWebp,
  getDPR,
  scrollParent,
  loadImageAsync,
  getBestSelectionFromSrcset,
  ObjectKeys
}
<commit_msg>fix eslint error (#452)<commit_after>import assign from 'assign-deep'

const inBrowser = typeof window !== 'undefined' && window !== null

export const hasIntersectionObserver = checkIntersectionObserver()

function checkIntersectionObserver () {
  if (inBrowser &&
    'IntersectionObserver' in window &&
    'IntersectionObserverEntry' in window &&
    'intersectionRatio' in window.IntersectionObserverEntry.prototype) {
  // Minimal polyfill for Edge 15's lack of `isIntersecting`
  // See: https://github.com/w3c/IntersectionObserver/issues/211
    if (!('isIntersecting' in window.IntersectionObserverEntry.prototype)) {
      Object.defineProperty(window.IntersectionObserverEntry.prototype,
        'isIntersecting', {
          get: function () {
            return this.intersectionRatio > 0
          }
        })
    }
    return true
  }
  return false
}

export const modeType = {
  event: 'event',
  observer: 'observer'
}

// CustomEvent polyfill for IE
const CustomEvent = (function () {
  if (!inBrowser) return
  // not IE
  if (typeof window.CustomEvent === 'function') return window.CustomEvent
  function CustomEvent (event, params) {
    params = params || { bubbles: false, cancelable: false, detail: undefined }
    var evt = document.createEvent('CustomEvent')
    evt.initCustomEvent(event, params.bubbles, params.cancelable, params.detail)
    return evt
  }
  CustomEvent.prototype = window.Event.prototype
  return CustomEvent
})()

function remove (arr, item) {
  if (!arr.length) return
  const index = arr.indexOf(item)
  if (index > -1) return arr.splice(index, 1)
}

function some (arr, fn) {
  let has = false
  for (let i = 0, len = arr.length; i < len; i++) {
    if (fn(arr[i])) {
      has = true
      break
    }
  }
  return has
}

function getBestSelectionFromSrcset (el, scale) {
  if (el.tagName !== 'IMG' || !el.getAttribute('data-srcset')) return

  let options = el.getAttribute('data-srcset')
  const result = []
  const container = el.parentNode
  const containerWidth = container.offsetWidth * scale

  let spaceIndex
  let tmpSrc
  let tmpWidth

  options = options.trim().split(',')

  options.map(item => {
    item = item.trim()
    spaceIndex = item.lastIndexOf(' ')
    if (spaceIndex === -1) {
      tmpSrc = item
      tmpWidth = 999998
    } else {
      tmpSrc = item.substr(0, spaceIndex)
      tmpWidth = parseInt(item.substr(spaceIndex + 1, item.length - spaceIndex - 2), 10)
    }
    result.push([tmpWidth, tmpSrc])
  })

  result.sort(function (a, b) {
    if (a[0] < b[0]) {
      return 1
    }
    if (a[0] > b[0]) {
      return -1
    }
    if (a[0] === b[0]) {
      if (b[1].indexOf('.webp', b[1].length - 5) !== -1) {
        return 1
      }
      if (a[1].indexOf('.webp', a[1].length - 5) !== -1) {
        return -1
      }
    }
    return 0
  })
  let bestSelectedSrc = ''
  let tmpOption

  for (let i = 0; i < result.length; i++) {
    tmpOption = result[i]
    bestSelectedSrc = tmpOption[1]
    const next = result[i + 1]
    if (next && next[0] < containerWidth) {
      bestSelectedSrc = tmpOption[1]
      break
    } else if (!next) {
      bestSelectedSrc = tmpOption[1]
      break
    }
  }

  return bestSelectedSrc
}

function find (arr, fn) {
  let item
  for (let i = 0, len = arr.length; i < len; i++) {
    if (fn(arr[i])) {
      item = arr[i]
      break
    }
  }
  return item
}

const getDPR = (scale = 1) => inBrowser ? (window.devicePixelRatio || scale) : scale

function supportWebp () {
  if (!inBrowser) return false

  let support = true

  try {
    const elem = document.createElement('canvas')

    if (elem.getContext && elem.getContext('2d')) {
      support = elem.toDataURL('image/webp').indexOf('data:image/webp') === 0
    }
  } catch (err) {
    support = false
  }

  return support
}

function throttle (action, delay) {
  let timeout = null
  let lastRun = 0
  return function () {
    if (timeout) {
      return
    }
    let elapsed = Date.now() - lastRun
    let context = this
    let args = arguments
    let runCallback = function () {
      lastRun = Date.now()
      timeout = false
      action.apply(context, args)
    }
    if (elapsed >= delay) {
      runCallback()
    } else {
      timeout = setTimeout(runCallback, delay)
    }
  }
}

function testSupportsPassive () {
  if (!inBrowser) return
  let support = false
  try {
    let opts = Object.defineProperty({}, 'passive', {
      get: function () {
        support = true
      }
    })
    window.addEventListener('test', null, opts)
  } catch (e) {}
  return support
}

const supportsPassive = testSupportsPassive()

const _ = {
  on (el, type, func, capture = false) {
    if (supportsPassive) {
      el.addEventListener(type, func, {
        capture: capture,
        passive: true
      })
    } else {
      el.addEventListener(type, func, capture)
    }
  },
  off (el, type, func, capture = false) {
    el.removeEventListener(type, func, capture)
  }
}

const loadImageAsync = (item, resolve, reject) => {
  let image = new Image()
  if (!item || !item.src) {
    const err = new Error('image src is required')
    return reject(err)
  }

  image.src = item.src
  if (item.cors) {
    image.crossOrigin = item.cors
  }

  image.onload = function () {
    resolve({
      naturalHeight: image.naturalHeight,
      naturalWidth: image.naturalWidth,
      src: image.src
    })
  }

  image.onerror = function (e) {
    reject(e)
  }
}

const style = (el, prop) => {
  return typeof getComputedStyle !== 'undefined'
    ? getComputedStyle(el, null).getPropertyValue(prop)
    : el.style[prop]
}

const overflow = (el) => {
  return style(el, 'overflow') + style(el, 'overflow-y') + style(el, 'overflow-x')
}

const scrollParent = (el) => {
  if (!inBrowser) return
  if (!(el instanceof HTMLElement)) {
    return window
  }

  let parent = el

  while (parent) {
    if (parent === document.body || parent === document.documentElement) {
      break
    }

    if (!parent.parentNode) {
      break
    }

    if (/(scroll|auto)/.test(overflow(parent))) {
      return parent
    }

    parent = parent.parentNode
  }

  return window
}

function isObject (obj) {
  return obj !== null && typeof obj === 'object'
}

function ObjectKeys (obj) {
  if (!(obj instanceof Object)) return []
  if (Object.keys) {
    return Object.keys(obj)
  } else {
    let keys = []
    for (let key in obj) {
      if (obj.hasOwnProperty(key)) {
        keys.push(key)
      }
    }
    return keys
  }
}

function ArrayFrom (arrLike) {
  let len = arrLike.length
  const list = []
  for (let i = 0; i < len; i++) {
    list.push(arrLike[i])
  }
  return list
}

function noop () {}

class ImageCache {
  constructor ({ max }) {
    this.options = {
      max: max || 100
    }
    this._caches = []
  }

  has (key) {
    return this._caches.indexOf(key) > -1
  }

  add (key) {
    if (this.has(key)) return
    this._caches.push(key)
    if (this._caches.length > this.options.max) {
      this.free()
    }
  }

  free () {
    this._caches.shift()
  }
}

export {
  ImageCache,
  inBrowser,
  CustomEvent,
  remove,
  some,
  find,
  assign,
  noop,
  ArrayFrom,
  _,
  isObject,
  throttle,
  supportWebp,
  getDPR,
  scrollParent,
  loadImageAsync,
  getBestSelectionFromSrcset,
  ObjectKeys
}
<|endoftext|>